New design (#2797)

* refactor node form UI to use new ListItem model

* add new list item row types and widgets

* add style wrapper

* remove print [skip ci]

* 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

* 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)

* Enhance LNURL payment integration (#3041)

* feat: enhance LNURL support and Lightning payment handling

- Improve LNURL decoding and encoding with expanded prefix handling.
- Add support for parsing and validating LNURL payment invoices.
- Introduce logic for fetching LNURL payment request amounts.
- Update payment flow to integrate LNURL and Lightning-specific conditions.
- Refactor BOLT11 prefix validation and amount extraction logic.

* fix: simplify LNURL invoice validation by removing redundant BOLT11 check

---------

Signed-off-by: black5box <black5box@outlook.com>
Co-authored-by: Serhii <borodenko.sv@gmail.com>
Co-authored-by: malik1004x <malikowskirobert@gmail.com>
Co-authored-by: Konstantin Ullrich <konstantinullrich12@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>
Co-authored-by: Konstantin Ullrich <konstantin@cakewallet.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>
This commit is contained in:
Omar Hatem
2026-03-11 04:26:57 +02:00
committed by GitHub
co-authored by Serhii malik1004x Konstantin Ullrich tuxsudo black5box cyan David Adegoke Konstantin Ullrich Edwin den Boer Serhii Serhii-Borodenko rottenwheel
parent 18c36acc14
commit 084fd6bb1e
775 changed files with 60901 additions and 29638 deletions
+53 -45
View File
@@ -12,9 +12,9 @@ import 'package:cake_wallet/entities/provider_types.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cw_core/crypto_amount_format.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:mobx/mobx.dart';
part 'buy_sell_view_model.g.dart';
@@ -24,8 +24,7 @@ class BuySellViewModel = BuySellViewModelBase with _$BuySellViewModel;
abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with Store {
BuySellViewModelBase(
AppStore appStore,
) : _cryptoNumberFormat = NumberFormat(),
cryptoAmount = '',
) : _cryptoAmount = '',
fiatAmount = '',
cryptoCurrencyAddress = '',
isCryptoCurrencyAddressEnabled = false,
@@ -54,7 +53,6 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
isCryptoCurrencyAddressEnabled = !(cryptoCurrency == wallet.currency);
}
final NumberFormat _cryptoNumberFormat;
late Timer bestRateSync;
List<BuyProvider> get availableBuyProviders {
@@ -79,11 +77,12 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
}
double get amount {
final formattedFiatAmount = double.tryParse(fiatAmount) ?? 200.0;
final formattedCryptoAmount =
double.tryParse(cryptoAmount) ?? (cryptoCurrency == CryptoCurrency.btc ? 0.001 : 1);
final formattedFiatAmount = double.tryParse(fiatAmount);
final formattedCryptoAmount = double.tryParse(_cryptoAmount);
return isBuyAction ? formattedFiatAmount : formattedCryptoAmount;
return isBuyAction
? formattedFiatAmount ?? 200.0
: formattedCryptoAmount ?? (cryptoCurrency == CryptoCurrency.btc ? 0.001 : 1);
}
final AppStore _appStore;
@@ -120,7 +119,11 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
CryptoCurrency cryptoCurrency;
@observable
String cryptoAmount;
String _cryptoAmount;
@computed
String get cryptoAmount =>
_appStore.amountParsingProxy.getDisplayCryptoAmount(_cryptoAmount, cryptoCurrency);
@observable
String fiatAmount;
@@ -164,6 +167,9 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
? (buySellQuotState as BuySellQuotFailed).errorMessage
: null;
@computed
bool get useSatoshi => _appStore.amountParsingProxy.useSatoshi(cryptoCurrency);
@action
void reset() {
cryptoCurrency = wallet.currency;
@@ -200,26 +206,23 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
if (amount.isEmpty) {
fiatAmount = '';
cryptoAmount = '';
_cryptoAmount = '';
return;
}
final enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0;
if (!isReadyToTrade && !isBuySellQuoteFailed) {
cryptoAmount = S.current.fetching;
_cryptoAmount = S.current.fetching;
return;
} else if (isBuySellQuoteFailed) {
cryptoAmount = '';
_cryptoAmount = '';
return;
}
if (bestRateQuote != null) {
_cryptoNumberFormat.maximumFractionDigits = cryptoCurrency.decimals;
cryptoAmount = _cryptoNumberFormat
.format(enteredAmount / bestRateQuote!.rate)
.toString()
.replaceAll(RegExp('\\,'), '');
final enteredAmount = double.tryParse(fiatAmount.replaceAll(',', '.')) ?? 0;
final amount = enteredAmount / bestRateQuote!.rate;
_cryptoAmount = amount.toString().withMaxDecimals(cryptoCurrency.decimals);
} else {
await calculateBestRate();
}
@@ -227,16 +230,14 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
@action
Future<void> changeCryptoAmount({required String amount}) async {
cryptoAmount = amount;
_cryptoAmount = _appStore.amountParsingProxy.getCanonicalCryptoAmount(amount, cryptoCurrency);
if (amount.isEmpty) {
fiatAmount = '';
cryptoAmount = '';
_cryptoAmount = '';
return;
}
final enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0;
if (!isReadyToTrade && !isBuySellQuoteFailed) {
fiatAmount = S.current.fetching;
return;
@@ -246,10 +247,10 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
}
if (bestRateQuote != null) {
fiatAmount = _cryptoNumberFormat
.format(enteredAmount * bestRateQuote!.rate)
.toString()
.replaceAll(RegExp('\\,'), '');
final enteredAmount = double.tryParse(_cryptoAmount.replaceAll(',', '.')) ?? 0;
fiatAmount =
(enteredAmount * bestRateQuote!.rate).toString().withMaxDecimals(fiatCurrency.decimals);
} else {
await calculateBestRate();
}
@@ -338,7 +339,7 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
Future<void> _initialize() async {
_setProviders();
cryptoAmount = '';
_cryptoAmount = '';
fiatAmount = '';
cryptoCurrencyAddress = _getInitialCryptoCurrencyAddress();
paymentMethodState = InitialPaymentMethod();
@@ -348,19 +349,25 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
}
String _getInitialCryptoCurrencyAddress() {
return cryptoCurrency == wallet.currency ? wallet.walletAddresses.address : '';
if (cryptoCurrency == wallet.currency) {
if ([CryptoCurrency.zec, CryptoCurrency.btc].contains(cryptoCurrency)) {
return wallet.walletAddresses.addressForBuy;
}
return wallet.walletAddresses.address;
}
return '';
}
@action
Future<void> _getAvailablePaymentTypes() async {
paymentMethodState = PaymentMethodLoading();
selectedPaymentMethod = null;
final result = await Future.wait(providerList.map((element) => element
.getAvailablePaymentTypes(fiatCurrency.title, cryptoCurrency, isBuyAction)
.timeout(
Duration(seconds: 10),
onTimeout: () => [],
)));
final result = await Future.wait(providerList.map((element) =>
element.getAvailablePaymentTypes(fiatCurrency.title, cryptoCurrency, isBuyAction).timeout(
Duration(seconds: 10),
onTimeout: () => [],
)));
final List<PaymentMethod> tempPaymentMethods = [];
@@ -394,11 +401,11 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
final List<BuyProvider> validProviders = providerList.where((provider) {
if (isBuyAction) {
return provider.supportedCryptoList.any((pair) =>
pair.from == cryptoCurrency && pair.to == fiatCurrency);
return provider.supportedCryptoList
.any((pair) => pair.from == cryptoCurrency && pair.to == fiatCurrency);
} else {
return provider.supportedFiatList.any((pair) =>
pair.from == fiatCurrency && pair.to == cryptoCurrency);
return provider.supportedFiatList
.any((pair) => pair.from == fiatCurrency && pair.to == cryptoCurrency);
}
}).toList();
@@ -441,7 +448,6 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
validQuotes.sort((a, b) => a.payout.compareTo(b.payout));
}
final Set<String> addedProviders = {};
final List<Quote> uniqueProviderQuotes = validQuotes.where((element) {
if (addedProviders.contains(element.provider.title)) return false;
@@ -449,10 +455,11 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
return true;
}).toList();
final List<Quote> successRateQuotes = validQuotes.where((element) =>
element.provider is OnRamperBuyProvider &&
element.recommendations.contains(ProviderRecommendation.successRate)
).toList();
final List<Quote> successRateQuotes = validQuotes
.where((element) =>
element.provider is OnRamperBuyProvider &&
element.recommendations.contains(ProviderRecommendation.successRate))
.toList();
for (final quote in successRateQuotes) {
if (!uniqueProviderQuotes.contains(quote)) {
@@ -507,7 +514,8 @@ abstract class BuySellViewModelBase extends WalletChangeListenerViewModel with S
if (e.toString().contains("403")) {
buySellQuotState = BuySellQuotFailed(errorMessage: "Using Tor is not supported");
} else {
buySellQuotState = BuySellQuotFailed(errorMessage: "Something went wrong please try again later");
buySellQuotState =
BuySellQuotFailed(errorMessage: "Something went wrong please try again later");
}
}
}
@@ -107,7 +107,10 @@ abstract class CakePayBuyCardViewModelBase with Store {
List<CakePayPaymentMethod> get availableMethods {
switch (walletType) {
case WalletType.bitcoin:
return [CakePayPaymentMethod.BTC];
return [
CakePayPaymentMethod.BTC,
if (sendViewModel.wallet.isSoftwareWallet) CakePayPaymentMethod.BTC_LN
];
case WalletType.litecoin:
return [
CakePayPaymentMethod.LTC,
@@ -1,4 +1,9 @@
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/contact_record.dart';
import 'package:cake_wallet/entities/parse_address_from_domain.dart';
import 'package:cake_wallet/src/screens/send/widgets/extract_address_from_parsed.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/core/execution_state.dart';
@@ -17,6 +22,7 @@ abstract class ContactViewModelBase with Store {
_contact = contact,
name = contact?.name ?? '',
address = contact?.address ?? '',
displayName = contact?.displayName ?? '',
currency = contact?.type,
lastChange = contact?.lastChange;
@@ -30,6 +36,9 @@ abstract class ContactViewModelBase with Store {
@observable
String address;
@observable
String displayName;
@observable
CryptoCurrency? currency;
@@ -52,6 +61,15 @@ abstract class ContactViewModelBase with Store {
currency = null;
}
Future<void> extractParsedAddress(BuildContext context) async{
if(currency == null) return;
final parsedAddress = await getIt.get<AddressResolver>().resolve(context, address, currency!);
if(parsedAddress.name.isNotEmpty) {
displayName = parsedAddress.name;
}
address = await extractAddressFromParsed(null, parsedAddress);
}
Future<void> save() async {
try {
state = IsExecutingState();
@@ -70,11 +88,12 @@ abstract class ContactViewModelBase with Store {
_contact.name = name;
_contact.address = address;
_contact.type = currency!;
_contact.displayName = displayName;
_contact.lastChange = now;
await _contact.save();
} else {
await _contacts
.add(Contact(name: name, address: address, type: currency!, lastChange: now));
.add(Contact(name: name, address: address, type: currency!, lastChange: now, displayName: displayName));
}
lastChange = now;
+129 -142
View File
@@ -1,39 +1,42 @@
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/entities/calculate_fiat_amount.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/sort_balance_types.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cw_core/crypto_amount_format.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cw_core/balance.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/erc20_token.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/entities/calculate_fiat_amount.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:mobx/mobx.dart';
part 'balance_view_model.g.dart';
class BalanceRecord {
const BalanceRecord(
{required this.availableBalance,
required this.additionalBalance,
required this.secondAvailableBalance,
required this.secondAdditionalBalance,
required this.frozenBalance,
required this.fiatAvailableBalance,
required this.fiatAdditionalBalance,
required this.fiatFrozenBalance,
required this.fiatSecondAvailableBalance,
required this.fiatSecondAdditionalBalance,
required this.asset,
required this.formattedAssetTitle});
const BalanceRecord({
required this.availableBalance,
required this.additionalBalance,
required this.secondAvailableBalance,
required this.secondAdditionalBalance,
required this.frozenBalance,
required this.fiatAvailableBalance,
required this.fiatAdditionalBalance,
required this.fiatFrozenBalance,
required this.fiatSecondAvailableBalance,
required this.fiatSecondAdditionalBalance,
required this.asset,
required this.secondAsset,
required this.formattedAssetTitle,
});
final String fiatAdditionalBalance;
final String fiatAvailableBalance;
@@ -46,14 +49,26 @@ class BalanceRecord {
final String fiatSecondAdditionalBalance;
final String fiatSecondAvailableBalance;
final CryptoCurrency asset;
final CryptoCurrency secondAsset;
final String formattedAssetTitle;
String get combinedAvailableBalance =>
((double.tryParse(availableBalance) ?? 0) + (double.tryParse(secondAvailableBalance) ?? 0))
.toString().withMaxDecimals(8);
String get combinedFiatAvailableBalance =>
fiatAvailableBalance.split(" ").first +
" " +
((double.tryParse(fiatAvailableBalance.split(" ").last) ?? 0) +
(double.tryParse(fiatSecondAvailableBalance.split(" ").last) ?? 0))
.toString().withMaxDecimals(8);
}
class BalanceViewModel = BalanceViewModelBase with _$BalanceViewModel;
abstract class BalanceViewModelBase with Store {
BalanceViewModelBase(
{required this.appStore, required this.settingsStore, required this.fiatConvertationStore})
{required this.appStore, required this.settingsStore, required this.fiatConversionStore})
: isReversing = false,
isShowCard = appStore.wallet?.walletInfo.isShowIntroCakePayCard ?? false,
wallet = appStore.wallet! {
@@ -64,9 +79,7 @@ abstract class BalanceViewModelBase with Store {
_checkMweb();
reaction((_) => settingsStore.mwebAlwaysScan, (bool value) {
_checkMweb();
});
reaction((_) => settingsStore.mwebAlwaysScan, (_) => _checkMweb());
}
void _checkMweb() {
@@ -77,9 +90,7 @@ abstract class BalanceViewModelBase with Store {
final AppStore appStore;
final SettingsStore settingsStore;
final FiatConversionStore fiatConvertationStore;
bool get canReverse => false;
final FiatConversionStore fiatConversionStore;
@observable
bool isReversing;
@@ -87,17 +98,12 @@ abstract class BalanceViewModelBase with Store {
@observable
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> wallet;
@computed
bool get hasSilentPayments => wallet.type == WalletType.bitcoin && !wallet.isHardwareWallet;
@computed
double get price {
final price = fiatConvertationStore.prices[appStore.wallet!.currency];
final price = fiatConversionStore.prices[appStore.wallet!.currency];
if (price == null) {
// price should update on next fetch:
return 0;
}
// price should update on next fetch:
if (price == null) return 0;
return price;
}
@@ -111,15 +117,13 @@ abstract class BalanceViewModelBase with Store {
@computed
bool get isHomeScreenSettingsEnabled =>
isEVMCompatibleChain(wallet.type) ||
wallet.type == WalletType.solana ||
wallet.type == WalletType.tron ||
wallet.type == WalletType.zano;
[WalletType.solana, WalletType.tron, WalletType.zano].contains(wallet.type);
@computed
bool get isEVMCompatible => isEVMCompatibleChain(wallet.type);
@computed
bool get hasAccounts => wallet.type == WalletType.monero || wallet.type == WalletType.wownero;
bool get hasAccounts => [WalletType.monero, WalletType.wownero].contains(wallet.type);
@computed
SortBalanceBy get sortBalanceBy => settingsStore.sortBalanceBy;
@@ -213,16 +217,16 @@ abstract class BalanceViewModelBase with Store {
String additionalBalance(CryptoCurrency cryptoCurrency) {
final balance = _currencyBalance(cryptoCurrency);
if (displayMode == BalanceDisplayMode.hiddenBalance) {
return '0.0';
}
if (displayMode == BalanceDisplayMode.hiddenBalance || balance.additional == BigInt.zero) return '0.0';
return balance.formattedAdditionalBalance;
return cryptoCurrency.formatAmount(balance.additional);
}
@computed
Map<CryptoCurrency, BalanceRecord> get balances {
return wallet.balance.map((key, value) {
var secondAsset = key == CryptoCurrency.ltc ? CryptoCurrency.ltcmweb : key;
if (displayMode == BalanceDisplayMode.hiddenBalance) {
final fiatCurrency = settingsStore.fiatCurrency;
return MapEntry(
@@ -241,60 +245,62 @@ abstract class BalanceViewModelBase with Store {
fiatSecondAdditionalBalance:
isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
asset: key,
secondAsset: secondAsset,
formattedAssetTitle: _formatterAsset(key)));
}
final fiatCurrency = settingsStore.fiatCurrency;
final price = key.isPotentialScam ? 0.0 : fiatConvertationStore.prices[key] ?? 0;
final price = key.isPotentialScam
? 0.0
: fiatConversionStore.prices[key == CryptoCurrency.btcln ? CryptoCurrency.btc : key] ?? 0;
// if (price == null) {
// throw Exception('Price is null for: $key');
// }
final additionalFiatBalance = isFiatDisabled
? ''
: (fiatCurrency.toString() +
' ' +
_getFiatBalance(price: price, cryptoAmount: value.formattedAdditionalBalance));
final available = evm?.getERC20AvailableBalance(value) ??
(value.fullAvailableBalance - (value.secondAvailable ?? BigInt.zero));
final additional = evm?.getERC20AvailableBalance(value) ??
(value.additional - (value.secondAdditional ?? BigInt.zero));
final availableFiatBalance = isFiatDisabled
? ''
: (fiatCurrency.toString() +
' ' +
_getFiatBalance(price: price, cryptoAmount: value.formattedAvailableBalance));
: '$fiatCurrency ${_getFiatBalance(price: price, cryptoAmount: key.formatAmount(available))}';
final additionalFiatBalance = isFiatDisabled
? ''
: '$fiatCurrency ${_getFiatBalance(price: price, cryptoAmount: key.formatAmount(additional))}';
final frozenFiatBalance = isFiatDisabled
? ''
: (fiatCurrency.toString() +
' ' +
_getFiatBalance(price: price, cryptoAmount: getFormattedFrozenBalance(value)));
final secondAdditionalFiatBalance = isFiatDisabled
? ''
: (fiatCurrency.toString() +
' ' +
_getFiatBalance(price: price, cryptoAmount: value.formattedSecondAdditionalBalance));
: '$fiatCurrency ${_getFiatBalance(price: price, cryptoAmount: value.frozen != null ? key.formatAmount(value.frozen!) : null)}';
final secondAvailableFiatBalance = isFiatDisabled
? ''
: (fiatCurrency.toString() +
' ' +
_getFiatBalance(price: price, cryptoAmount: value.formattedSecondAvailableBalance));
: '$fiatCurrency ${_getFiatBalance(price: price, cryptoAmount: value.secondAvailable != null ? key.formatAmount(value.secondAvailable!) : null)}';
final secondAdditionalFiatBalance = isFiatDisabled
? ''
: '$fiatCurrency ${_getFiatBalance(price: price, cryptoAmount: value.secondAdditional != null ? key.formatAmount(value.secondAdditional!) : null)}';
return MapEntry(
key,
BalanceRecord(
availableBalance: value.formattedAvailableBalance,
additionalBalance: value.formattedAdditionalBalance,
frozenBalance: getFormattedFrozenBalance(value),
secondAvailableBalance: value.formattedSecondAvailableBalance,
secondAdditionalBalance: value.formattedSecondAdditionalBalance,
fiatAdditionalBalance: additionalFiatBalance,
fiatAvailableBalance: availableFiatBalance,
fiatFrozenBalance: frozenFiatBalance,
fiatSecondAvailableBalance: secondAvailableFiatBalance,
fiatSecondAdditionalBalance: secondAdditionalFiatBalance,
asset: key,
formattedAssetTitle: _formatterAsset(key)));
key,
BalanceRecord(
availableBalance: _getFormattedCryptoAmount(key, available),
fiatAvailableBalance: availableFiatBalance,
additionalBalance: _getFormattedCryptoAmount(key, additional),
fiatAdditionalBalance: additionalFiatBalance,
frozenBalance:
(value.frozen ?? BigInt.zero) > BigInt.zero ? _getFormattedCryptoAmount(key, value.frozen??BigInt.zero) : '',
fiatFrozenBalance: frozenFiatBalance,
secondAvailableBalance: _getFormattedCryptoAmount(secondAsset, value.secondAvailable??BigInt.zero),
fiatSecondAvailableBalance: secondAvailableFiatBalance,
secondAdditionalBalance: _getFormattedCryptoAmount(secondAsset, value.secondAdditional??BigInt.zero),
fiatSecondAdditionalBalance: secondAdditionalFiatBalance,
asset: key,
secondAsset: secondAsset,
formattedAssetTitle: _formatterAsset(key),
),
);
});
}
@@ -302,47 +308,48 @@ abstract class BalanceViewModelBase with Store {
bool mwebEnabled = false;
bool hasAdditionalBalance(CryptoCurrency currency) {
bool isWalletTypeActivated = _hasAdditionalBalanceForWalletType(wallet.type);
bool isNotZeroAmount = additionalBalance(currency) != "0.0";
final isWalletTypeActivated = _hasAdditionalBalanceForWalletType(wallet.type);
final isNotZeroAmount = additionalBalance(currency) != "0.0";
return isWalletTypeActivated && isNotZeroAmount;
}
@computed
bool get hasSecondAdditionalBalance =>
mwebEnabled && _hasSecondAdditionalBalanceForWalletType(wallet.type);
bool get hasSecondAdditionalBalance {
if (wallet.type == WalletType.litecoin && mwebEnabled) {
return (wallet.balance[CryptoCurrency.ltc]?.secondAdditional ?? 0) != 0;
} else if (wallet.type == WalletType.bitcoin) {
return (wallet.balance[CryptoCurrency.btc]?.secondAdditional ?? 0) != 0;
}
return false;
}
@computed
bool get hasSecondAvailableBalance =>
mwebEnabled && _hasSecondAvailableBalanceForWalletType(wallet.type);
bool _hasAdditionalBalanceForWalletType(WalletType type) {
switch (type) {
case WalletType.monero:
case WalletType.wownero:
case WalletType.zano:
case WalletType.decred:
case WalletType.zcash:
bool get hasSecondAvailableBalance {
switch (wallet.type) {
case WalletType.bitcoin:
return true;
case WalletType.litecoin:
return mwebEnabled;
default:
return false;
}
}
bool _hasSecondAdditionalBalanceForWalletType(WalletType type) {
if (wallet.type == WalletType.litecoin) {
if ((wallet.balance[CryptoCurrency.ltc]?.secondAdditional ?? 0) != 0) {
return true;
}
}
return false;
}
bool _hasAdditionalBalanceForWalletType(WalletType type) => [
WalletType.monero,
WalletType.wownero,
WalletType.zano,
WalletType.decred,
WalletType.zcash
].contains(type);
bool _hasSecondAvailableBalanceForWalletType(WalletType type) {
if (wallet.type == WalletType.litecoin) {
return true;
}
return false;
String _getFormattedCryptoAmount(CryptoCurrency cryptoCurrency, BigInt? amount) {
if (amount == null) return "";
return appStore.amountParsingProxy
.getDisplayCryptoStringFromBigInt(amount, cryptoCurrency)
.withMaxDecimals(8).withLocalSeperator(settingsStore.languageCode);
}
@computed
@@ -351,25 +358,15 @@ abstract class BalanceViewModelBase with Store {
balance.sort((BalanceRecord a, BalanceRecord b) {
if (wallet.currency == CryptoCurrency.xhv) {
if (b.asset == CryptoCurrency.xhv) {
return 1;
}
if (b.asset == CryptoCurrency.xhv) return 1;
if (b.asset == CryptoCurrency.xusd) {
if (a.asset == CryptoCurrency.xhv) {
return -1;
}
if (a.asset == CryptoCurrency.xhv) return -1;
return 1;
}
if (b.asset == CryptoCurrency.xbtc) {
return 1;
}
if (b.asset == CryptoCurrency.xeur) {
return 1;
}
if (b.asset == CryptoCurrency.xbtc) return 1;
if (b.asset == CryptoCurrency.xeur) return 1;
return 0;
}
@@ -396,9 +393,9 @@ abstract class BalanceViewModelBase with Store {
switch (sortBalanceBy) {
case SortBalanceBy.FiatBalance:
final aFiatBalance = _getFiatBalance(
price: fiatConvertationStore.prices[a.asset] ?? 0, cryptoAmount: a.availableBalance);
price: fiatConversionStore.prices[a.asset] ?? 0, cryptoAmount: a.availableBalance);
final bFiatBalance = _getFiatBalance(
price: fiatConvertationStore.prices[b.asset] ?? 0, cryptoAmount: b.availableBalance);
price: fiatConversionStore.prices[b.asset] ?? 0, cryptoAmount: b.availableBalance);
return (double.tryParse(bFiatBalance) ?? 0)
.compareTo((double.tryParse(aFiatBalance)) ?? 0);
@@ -416,9 +413,7 @@ abstract class BalanceViewModelBase with Store {
Balance _currencyBalance(CryptoCurrency cryptoCurrency) {
final balance = wallet.balance[cryptoCurrency];
if (balance == null) {
throw Exception('No balance for ${wallet.currency}');
}
if (balance == null) throw Exception('No balance for ${wallet.currency}');
return balance;
}
@@ -431,9 +426,7 @@ abstract class BalanceViewModelBase with Store {
@action
void _onWalletChange(
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo>? wallet) {
if (wallet == null) {
return;
}
if (wallet == null) return;
this.wallet = wallet;
_onCurrentWalletChangeReaction?.reaction.dispose();
@@ -459,27 +452,21 @@ abstract class BalanceViewModelBase with Store {
String _getFiatBalance({required double price, String? cryptoAmount}) {
if (cryptoAmount == null || cryptoAmount.isEmpty || double.tryParse(cryptoAmount) == null) {
return '0.00';
return '0.00'.withLocalSeperator(settingsStore.languageCode);
}
return calculateFiatAmount(price: price, cryptoAmount: cryptoAmount);
return calculateFiatAmount(price: price, cryptoAmount: cryptoAmount)
.withLocalSeperator(settingsStore.languageCode);
}
String _formatterAsset(CryptoCurrency asset) {
switch (wallet.type) {
case WalletType.haven:
final assetStringified = asset.toString();
if (asset != CryptoCurrency.xhv && assetStringified[0].toUpperCase() == 'X') {
return assetStringified.replaceFirst('X', 'x');
}
return asset.toString();
default:
return asset.toString();
final assetString = asset.toString();
if (wallet.type == WalletType.haven &&
asset != CryptoCurrency.xhv &&
assetString[0].toUpperCase() == 'X') {
return assetString.replaceFirst('X', 'x');
}
}
String getFormattedFrozenBalance(Balance walletBalance) =>
walletBalance.formattedUnAvailableBalance;
return appStore.amountParsingProxy.getCryptoSymbol(asset);
}
}
@@ -5,6 +5,8 @@ import 'dart:io' show Platform;
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/key_service.dart';
import "package:cw_core/balance_card_style_settings.dart";
import 'package:cake_wallet/core/trade_monitor.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/entities/exchange_api_mode.dart';
@@ -14,6 +16,7 @@ import 'package:cake_wallet/entities/sync_status_display_mode.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/nano/nano.dart';
import 'package:cake_wallet/order/order_provider_description.dart';
import 'package:cake_wallet/src/widgets/alert_with_one_action.dart';
import 'package:cake_wallet/store/dashboard/order_filter_store.dart';
@@ -23,7 +26,6 @@ import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cake_wallet/utils/tor.dart';
import 'package:cake_wallet/wownero/wownero.dart' as wow;
import 'package:cake_wallet/nano/nano.dart';
import 'package:cake_wallet/store/anonpay/anonpay_transactions_store.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/dashboard/orders_store.dart';
@@ -45,6 +47,8 @@ import 'package:cake_wallet/view_model/dashboard/transaction_list_item.dart';
import 'package:cake_wallet/view_model/settings/sync_mode.dart';
import 'package:cryptography/cryptography.dart';
import 'package:cw_core/balance.dart';
import 'package:cw_core/card_design.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_history.dart';
@@ -62,7 +66,6 @@ import 'package:mobx/mobx.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cake_wallet/core/trade_monitor.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/evm/evm.dart';
@@ -200,6 +203,8 @@ abstract class DashboardViewModelBase with Store {
name = appStore.wallet!.name,
type = appStore.wallet!.type,
transactions = ObservableList<TransactionListItem>(),
cardDesigns = ObservableList<CardDesign>(),
cardOrder = ObservableMap<int, int>(),
wallet = appStore.wallet! {
showDecredInfoCard = wallet.type == WalletType.decred &&
(sharedPreferences.getBool(PreferencesKey.showDecredInfoCard) ?? true);
@@ -238,7 +243,7 @@ abstract class DashboardViewModelBase with Store {
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('monero_transaction_history_item_${transaction.id}_key'),
),
),
@@ -268,7 +273,7 @@ abstract class DashboardViewModelBase with Store {
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('wownero_transaction_history_item_${transaction.id}_key'),
),
),
@@ -282,7 +287,7 @@ abstract class DashboardViewModelBase with Store {
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('${_wallet.type.name}_transaction_history_item_${transaction.id}_key'),
),
),
@@ -294,9 +299,11 @@ abstract class DashboardViewModelBase with Store {
// subname = nano!.getCurrentAccount(_wallet).label;
// }
reaction((_) => appStore.wallet, (wallet) {
_walletChangeDisposer?.reaction.dispose();
_walletChangeDisposer = reaction((_) => appStore.wallet, (wallet) {
_onWalletChange(wallet);
_checkMweb();
loadCardDesigns();
showDecredInfoCard = wallet?.type == WalletType.decred &&
sharedPreferences.getBool(PreferencesKey.showDecredInfoCard) != false;
@@ -314,7 +321,9 @@ abstract class DashboardViewModelBase with Store {
if (![WalletType.solana, WalletType.tron].contains(wallet.type)) {
try {
confirmations =
appStore.wallet!.transactionHistory.transactions.values.first.confirmations + 1;
appStore.wallet!.transactionHistory.transactions.values.first.confirmations +
appStore.wallet!.transactionHistory.transactions.values.last.confirmations +
1;
} catch (_) {}
}
return length * confirmations;
@@ -328,6 +337,8 @@ abstract class DashboardViewModelBase with Store {
});
}
loadCardDesigns();
_checkMweb();
reaction((_) => settingsStore.mwebAlwaysScan, (bool value) => _checkMweb());
@@ -351,13 +362,97 @@ abstract class DashboardViewModelBase with Store {
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('${wallet.type.name}_transaction_history_item_${transaction.id}_key'),
),
),
);
}
@computed
bool get isSyncHeavy {
if ([WalletType.monero, WalletType.wownero, WalletType.decred, WalletType.zcash, WalletType.zano].contains(wallet.type)) {
return true;
}
if (wallet.type == WalletType.bitcoin && silentPaymentsScanningActive && hasSilentPayments) {
return true;
}
if (wallet.type == WalletType.litecoin && mwebEnabled && hasMweb) {
return true;
}
return false;
}
@action
Future<void> loadCardDesigns() async {
final accountStyleSettings =
await BalanceCardStyleSettings.getAll(wallet.walletInfo.internalId);
late final int numAccounts;
if (wallet.type == WalletType.monero) {
numAccounts = monero!.getAccountList(wallet).accounts.length;
} else if (wallet.type == WalletType.wownero) {
numAccounts = wow.wownero!.getAccountList(wallet).accounts.length;
} else if (wallet.type == WalletType.bitcoin) {
// bitcoin and lightning
numAccounts = 2;
} else {
numAccounts = 1;
}
cardDesigns.clear();
Map<int, int> newOrder = {};
for (int i = 0; i < numAccounts; i++) {
late final int index;
if(balanceViewModel.hasAccounts) {
index = i;
} else if(wallet.type == WalletType.bitcoin && i == 1) {
index = 0;
} else {
index = -1;
}
final setting = accountStyleSettings
.where((e) => e.accountIndex == index)
.firstOrNull;
late final CryptoCurrency curr;
if(wallet.type == WalletType.bitcoin && i == 1) {
curr = CryptoCurrency.btcln;
} else {
curr = wallet.currency;
}
cardDesigns.add(CardDesign.fromStyleSettings(setting, curr));
if(setting?.cardOrder != null) {
newOrder[setting!.cardOrder] = i;
}
}
// making sure ALL accounts have numbers, even the ones that existed before this feature was a thing
for (int i = 0; i < numAccounts; i++) {
if (!newOrder.containsKey(i) && !(wallet.type != WalletType.bitcoin && i == 1)) {
int free = 0;
while (newOrder.containsValue(free)) {
free++;
}
if(wallet.type == WalletType.bitcoin) {
newOrder[free] = 0;
} else {
newOrder[free] = i;
}
}
}
cardOrder = newOrder.asObservable();
}
void _transactionDisposerCallback(int _) async {
// Simple check to prevent the callback from being called multiple times in the same frame
if (_isTransactionDisposerCallbackRunning) return;
@@ -390,7 +485,7 @@ abstract class DashboardViewModelBase with Store {
transactions.addAll(relevantTxs.map((tx) => TransactionListItem(
transaction: tx,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('${wallet.type.name}_transaction_history_item_${tx.id}_key'),
)));
} finally {
@@ -426,8 +521,15 @@ abstract class DashboardViewModelBase with Store {
@observable
bool isShowThirdYatIntroduction;
@observable
ObservableList<CardDesign> cardDesigns;
@observable
ObservableMap<int, int> cardOrder;
@computed
bool get isDarkTheme => appStore.themeStore.currentTheme.isDark;
@computed
String get address => wallet.walletAddresses.address;
@@ -437,6 +539,24 @@ abstract class DashboardViewModelBase with Store {
@computed
SyncStatus get status => wallet.syncStatus;
@computed
bool get shouldShowMwebAd {
if(wallet.type != WalletType.litecoin) return false;
if(mwebEnabled) return false;
if(settingsStore.mwebAdDismissed) return false;
return true;
}
@action
void dismissMwebAd(bool enableMweb) {
if(enableMweb) setMwebEnabled();
settingsStore.mwebAdDismissed = true;
}
@computed
String get syncStatusText {
var statusText = '';
@@ -456,13 +576,40 @@ abstract class DashboardViewModelBase with Store {
return statusText;
}
@computed
double get confirmationProgress {
int received = 0;
int needed = 0;
for (final transaction in transactions) {
if (transaction.neededConfirmations == 0) {
continue;
}
if(transaction.transaction.confirmations >= transaction.neededConfirmations) {
continue;
}
received += transaction.transaction.confirmations;
needed += transaction.neededConfirmations;
}
if (needed == 0) {
return 1;
}
return received / needed;
}
@computed
BalanceDisplayMode get balanceDisplayMode => appStore.settingsStore.balanceDisplayMode;
@computed
@Deprecated("Replaced by showApps")
bool get shouldShowMarketPlaceInDashboard =>
appStore.settingsStore.shouldShowMarketPlaceInDashboard;
@computed
bool get showApps => appStore.settingsStore.shouldShowMarketPlaceInDashboard;
@computed
List<TradeListItem> get trades =>
tradesStore.trades.where((trade) {
@@ -520,6 +667,10 @@ abstract class DashboardViewModelBase with Store {
@observable
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> wallet;
@computed
bool get hasLightning =>
wallet.type == WalletType.bitcoin && wallet.isSoftwareWallet && bitcoin!.useLightning(wallet);
@computed
bool get isTestnet => wallet.type == WalletType.bitcoin && bitcoin!.isTestnet(wallet);
@@ -581,7 +732,7 @@ abstract class DashboardViewModelBase with Store {
];
return errors;
}
@computed
bool get showZcashMissingFundsCard {
if (wallet.type != WalletType.zcash) return false;
@@ -706,8 +857,11 @@ abstract class DashboardViewModelBase with Store {
}
bool get hasBgsyncNetworkConstraints => Platform.isAndroid;
bool get hasBgsyncBatteryNotLowConstraints => Platform.isAndroid;
bool get hasBgsyncChargingConstraints => Platform.isAndroid;
bool get hasBgsyncDeviceIdleConstraints => Platform.isAndroid;
@observable
@@ -860,12 +1014,12 @@ abstract class DashboardViewModelBase with Store {
mwebEnabled = false;
bitcoin!.setMwebEnabled(wallet, false);
}
@action
@action
Future<void> rescanInternalChangeZcash() async {
await zcash!.rescanInternalChange(wallet);
}
@action
void dismissZcash() {
settingsStore.showZcashMissingFundsCard = false;
@@ -946,6 +1100,8 @@ abstract class DashboardViewModelBase with Store {
ReactionDisposer? _transactionDisposer;
ReactionDisposer? _walletChangeDisposer;
ReactionDisposer? _chainChangeDisposer;
@computed
@@ -1086,7 +1242,9 @@ abstract class DashboardViewModelBase with Store {
if (![WalletType.solana, WalletType.tron].contains(wallet.type)) {
try {
confirmations =
appStore.wallet!.transactionHistory.transactions.values.first.confirmations + 1;
appStore.wallet!.transactionHistory.transactions.values.first.confirmations +
appStore.wallet!.transactionHistory.transactions.values.last.confirmations +
1;
} catch (_) {}
}
return length * confirmations;
@@ -1120,7 +1278,7 @@ abstract class DashboardViewModelBase with Store {
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('monero_transaction_history_item_${transaction.id}_key'),
),
),
@@ -1140,7 +1298,7 @@ abstract class DashboardViewModelBase with Store {
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
appStore: appStore,
key: ValueKey('wownero_transaction_history_item_${transaction.id}_key'),
),
),
@@ -1304,7 +1462,7 @@ abstract class DashboardViewModelBase with Store {
if (wallet.chainId == 1 && tx.evmSignatureName == 'approval')
return ' (${tx.evmSignatureName})';
return '';
}
@@ -405,7 +405,7 @@ abstract class HomeSettingsViewModelBase with Store {
void _updateFiatPrices(CryptoCurrency token) async {
if (token.isPotentialScam) return; // don't fetch price data for potential scam tokens
try {
_balanceViewModel.fiatConvertationStore.prices[token] =
_balanceViewModel.fiatConversionStore.prices[token] =
await FiatConversionService.fetchPrice(
crypto: token,
fiat: _settingsStore.fiatCurrency,
+1 -1
View File
@@ -52,7 +52,7 @@ abstract class NFTViewModelBase with Store {
Future<void> getNFTAssetByWallet() async {
final wallet = appStore.wallet!;
if (!isNFTACtivatedChain(wallet.type, wallet.chainId)) return;
if (!isNFTACtivatedChain(wallet.type, chainId: wallet.chainId)) return;
final walletAddress = wallet.walletInfo.address;
log('Fetching wallet NFTs for $walletAddress');
@@ -12,67 +12,26 @@ class ReceiveOptionViewModel = ReceiveOptionViewModelBase with _$ReceiveOptionVi
abstract class ReceiveOptionViewModelBase with Store {
ReceiveOptionViewModelBase(this._wallet, this.initialPageOption)
: selectedReceiveOption = initialPageOption ??
(_wallet.type == WalletType.bitcoin ||
_wallet.type == WalletType.litecoin
([WalletType.bitcoin, WalletType.litecoin].contains(_wallet.type)
? bitcoin!.getSelectedAddressType(_wallet)
: (_wallet.type == WalletType.decred && _wallet.isTestnet)
: (_wallet.type == WalletType.decred && _wallet.isTestnet)
? ReceivePageOption.testnet
: _wallet.type == WalletType.zcash
? zcash!.getSelectedAddressType(_wallet)
: ReceivePageOption.mainnet),
_options = [] {
final walletType = _wallet.type;
switch (walletType) {
case WalletType.bitcoin:
_options = [
...bitcoin!.getBitcoinReceivePageOptions(_wallet),
...ReceivePageOptions.where((element) => element != ReceivePageOption.mainnet)
];
break;
case WalletType.litecoin:
_options = [
...bitcoin!.getLitecoinReceivePageOptions(_wallet),
...ReceivePageOptions.where((element) => element != ReceivePageOption.mainnet)
];
break;
case WalletType.haven:
_options = [ReceivePageOption.mainnet];
break;
case WalletType.decred:
if (_wallet.isTestnet) {
_options = [
ReceivePageOption.testnet,
...ReceivePageOptions.where(
(element) => element != ReceivePageOption.mainnet)
];
} else {
_options = ReceivePageOptions;
}
break;
case WalletType.zcash:
_options = [
...zcash!.getZcashReceivePageOptions(_wallet),
...ReceivePageOptions.where((element) => element != ReceivePageOption.mainnet)
];
break;
default:
_options = ReceivePageOptions;
}
}
: ReceivePageOption.mainnet);
final WalletBase _wallet;
final ReceivePageOption? initialPageOption;
List<ReceivePageOption> _options;
@observable
ReceivePageOption selectedReceiveOption;
List<ReceivePageOption> get options => _options;
List<ReceivePageOption> get options => _wallet.walletAddresses.receivePageOptions;
String get walletTypeString => walletTypeToString(_wallet.type);
@action
void selectReceiveOption(ReceivePageOption option) {
selectedReceiveOption = option;
}
void selectReceiveOption(ReceivePageOption option) => selectedReceiveOption = option;
}
+15 -12
View File
@@ -1,26 +1,29 @@
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/view_model/dashboard/action_list_item.dart';
import "package:cake_wallet/entities/balance_display_mode.dart";
import "package:cake_wallet/exchange/trade.dart";
import "package:cake_wallet/store/app_store.dart";
import "package:cake_wallet/view_model/dashboard/action_list_item.dart";
class TradeListItem extends ActionListItem {
TradeListItem({
required this.trade,
required this.settingsStore,
required this.appStore,
required super.key,
});
final Trade trade;
final SettingsStore settingsStore;
final AppStore appStore;
BalanceDisplayMode get displayMode => settingsStore.balanceDisplayMode;
BalanceDisplayMode get displayMode => appStore.settingsStore.balanceDisplayMode;
String get tradeFormattedAmount =>
displayMode == BalanceDisplayMode.hiddenBalance ? '---' : trade.amountFormatted();
String get tradeFormattedAmount => displayMode == BalanceDisplayMode.hiddenBalance
? "---"
: appStore.amountParsingProxy.getDisplayCryptoAmount(trade.amountFormatted(), trade.from!);
String get tradeFormattedReceiveAmount => displayMode == BalanceDisplayMode.hiddenBalance
? "---"
: appStore.amountParsingProxy
.getDisplayCryptoAmount(trade.receiveAmountFormatted(), trade.to!);
String get tradeFormattedReceiveAmount =>
displayMode == BalanceDisplayMode.hiddenBalance ? '---' : trade.receiveAmountFormatted();
@override
DateTime get date => trade.createdAt!;
}
@@ -6,14 +6,15 @@ import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/nano/nano.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/crypto_amount_format.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/view_model/dashboard/action_list_item.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
@@ -26,17 +27,17 @@ class TransactionListItem extends ActionListItem with Keyable {
TransactionListItem({
required this.transaction,
required this.balanceViewModel,
required this.settingsStore,
required AppStore appStore,
required super.key,
});
}) : _appStore = appStore;
final TransactionInfo transaction;
final BalanceViewModel balanceViewModel;
final SettingsStore settingsStore;
final AppStore _appStore;
double get price => balanceViewModel.price;
FiatCurrency get fiatCurrency => settingsStore.fiatCurrency;
FiatCurrency get fiatCurrency => _appStore.settingsStore.fiatCurrency;
BalanceDisplayMode get displayMode => balanceViewModel.displayMode;
@@ -49,13 +50,33 @@ class TransactionListItem extends ActionListItem with Keyable {
balanceViewModel.wallet.type == WalletType.tron;
String get formattedCryptoAmount {
return displayMode == BalanceDisplayMode.hiddenBalance ? '---' : transaction.amountFormatted();
if (displayMode == BalanceDisplayMode.hiddenBalance) return '---';
if (balanceViewModel.wallet.type == WalletType.bitcoin) {
final isLightning = (transaction.additionalInfo["isLightning"] as bool?) ?? false;
final crypto = isLightning ? CryptoCurrency.btcln : CryptoCurrency.btc;
final amount = _appStore.amountParsingProxy
.getDisplayCryptoString(transaction.amount, crypto)
.withMaxDecimals(8)
.withLocalSeperator(_appStore.settingsStore.languageCode);
return '$amount ${_appStore.amountParsingProxy.getCryptoSymbol(crypto)}';
}
return transaction.amountFormatted();
}
String get formattedTitle {
if (transaction.additionalInfo['autoShield'] == true) {
return "Autoshield";
}
if (transaction.isPending) {
final status = formattedStatus;
final baseString = transaction.direction == TransactionDirection.incoming
? S.current.receiving
: S.current.sending;
return status.isNotEmpty ? "$baseString $status" : "$baseString...";
}
if (transaction.direction == TransactionDirection.incoming) {
return S.current.received;
}
@@ -63,6 +84,25 @@ class TransactionListItem extends ActionListItem with Keyable {
return S.current.sent;
}
int get neededConfirmations {
switch (balanceViewModel.wallet.type) {
case WalletType.monero:
case WalletType.haven:
case WalletType.zano:
return 10;
case WalletType.wownero:
return 3;
case WalletType.litecoin:
bool isPegOut = (transaction.additionalInfo["isPegOut"] as bool?) ?? false;
bool fromPegOut = (transaction.additionalInfo["fromPegOut"] as bool?) ?? false;
if(isPegOut || fromPegOut)
return 6;
default:
return 0;
}
return 0;
}
String get formattedPendingStatus {
switch (balanceViewModel.wallet.type) {
case WalletType.monero:
@@ -91,10 +131,10 @@ class TransactionListItem extends ActionListItem with Keyable {
str = " (${transaction.confirmations}/6)";
}
if (isPegIn) {
str += " (Peg In)";
str += " (Mask)";
}
if (isPegOut) {
str += " (Peg Out)";
str += " (Unmask)";
}
return str;
default:
@@ -115,7 +155,7 @@ class TransactionListItem extends ActionListItem with Keyable {
return formattedPendingStatus;
}
return transaction.isPending ? S.current.pending : '';
return "";
}
String get formattedType {
@@ -154,21 +194,24 @@ class TransactionListItem extends ActionListItem with Keyable {
switch (balanceViewModel.wallet.type) {
case WalletType.monero:
amount = calculateFiatAmountRaw(
cryptoAmount: monero!.formatterMoneroAmountToDouble(amount: transaction.amount),
price: price);
cryptoAmount: monero!.formatterMoneroAmountToDouble(amount: transaction.amount),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.wownero:
amount = calculateFiatAmountRaw(
cryptoAmount: wownero!.formatterWowneroAmountToDouble(amount: transaction.amount),
price: price);
cryptoAmount: wownero!.formatterWowneroAmountToDouble(amount: transaction.amount),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.bitcoin:
case WalletType.litecoin:
case WalletType.bitcoinCash:
case WalletType.dogecoin:
amount = calculateFiatAmountRaw(
cryptoAmount: bitcoin!.formatterBitcoinAmountToDouble(amount: transaction.amount),
price: price);
cryptoAmount: bitcoin!.formatterBitcoinAmountToDouble(amount: transaction.amount),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.ethereum:
case WalletType.polygon:
@@ -176,34 +219,35 @@ class TransactionListItem extends ActionListItem with Keyable {
case WalletType.arbitrum:
case WalletType.bsc:
final asset = evm!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
final price = balanceViewModel.fiatConversionStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: evm!.formatterEVMAmountToDouble(transaction: transaction),
price: price,
);
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.nano:
amount = calculateFiatAmountRaw(
cryptoAmount: double.parse(nanoUtil!.getRawAsUsableString(
nano!.getTransactionAmountRaw(transaction).toString(), nanoUtil!.rawPerNano)),
price: price);
cryptoAmount: double.parse(nanoUtil!.getRawAsUsableString(
nano!.getTransactionAmountRaw(transaction).toString(), nanoUtil!.rawPerNano)),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.solana:
final asset = solana!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
final price = balanceViewModel.fiatConversionStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: solana!.getTransactionAmountRaw(transaction),
price: price,
);
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.tron:
final asset = tron!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
final price = balanceViewModel.fiatConversionStore.prices[asset];
final cryptoAmount = tron!.getTransactionAmountRaw(transaction);
amount = calculateFiatAmountRaw(
cryptoAmount: cryptoAmount,
price: price,
);
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.zano:
final asset = zano!.assetOfTransaction(balanceViewModel.wallet, transaction);
@@ -211,22 +255,26 @@ class TransactionListItem extends ActionListItem with Keyable {
amount = "0.00";
break;
}
final price = balanceViewModel.fiatConvertationStore.prices[asset];
final price = balanceViewModel.fiatConversionStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: zano!.formatterIntAmountToDouble(
amount: transaction.amount, currency: asset, forFee: false),
price: price);
cryptoAmount: zano!.formatterIntAmountToDouble(
amount: transaction.amount, currency: asset, forFee: false),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.decred:
amount = calculateFiatAmountRaw(
cryptoAmount: decred!.formatterDecredAmountToDouble(amount: transaction.amount),
price: price);
cryptoAmount: decred!.formatterDecredAmountToDouble(amount: transaction.amount),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
break;
case WalletType.zcash:
amount = calculateFiatAmountRaw(
cryptoAmount: zcash!.formatterZcashAmountToDouble(amount: BigInt.from(transaction.amount)),
price: price);
cryptoAmount:
zcash!.formatterZcashAmountToDouble(amount: BigInt.from(transaction.amount)),
price: price,
).withLocalSeperator(_appStore.settingsStore.languageCode);
case WalletType.none:
case WalletType.banano:
case WalletType.haven:
@@ -1,6 +1,6 @@
import 'dart:async';
import 'package:cake_wallet/core/payment_uris.dart';
import 'package:cake_wallet/core/amount_parsing_proxy.dart';
import 'package:cake_wallet/entities/calculate_fiat_amount.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/exchange/exchange_provider_description.dart';
@@ -30,6 +30,7 @@ import 'package:cake_wallet/view_model/send/fees_view_model.dart';
import 'package:cake_wallet/view_model/send/output.dart';
import 'package:cake_wallet/view_model/send/send_view_model.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/payment_uris.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
@@ -50,6 +51,7 @@ abstract class ExchangeTradeViewModelBase with Store {
required this.fiatConversionStore,
}) : trade = tradesStore.trade!,
isSendable = _checkIfCanSend(tradesStore, wallet),
isSwapsXYZCanSendFromExternal = _checkIfSwapsXYZCanSendFromExternal(tradesStore.trade!, wallet),
items = ObservableList<ExchangeTradeItem>() {
setUpOutput();
switch (trade.provider) {
@@ -111,16 +113,16 @@ abstract class ExchangeTradeViewModelBase with Store {
late Output output;
AmountParsingProxy get _amountParsingProxy => sendViewModel.amountParsingProxy;
@observable
Trade trade;
@observable
bool isSendable;
bool get isSwapsXyzSendingEVMTokenSwap =>
(_provider is SwapsXyzExchangeProvider) &&
isEVMCompatibleChain(wallet.type) &&
wallet.currency != trade.from;
bool isSwapsXYZCanSendFromExternal;
/// Providers that should hide the "send from external" button
static const List<Type> _providersThatHideExternalSend = [
@@ -130,24 +132,27 @@ abstract class ExchangeTradeViewModelBase with Store {
/// Returns true if the current provider should hide the external send button
bool get shouldHideExternalSendButton {
if (_provider == null) return false;
if (!isSwapsXYZCanSendFromExternal) return true;
return _providersThatHideExternalSend.any(
(providerType) => _provider.runtimeType == providerType,
);
}
String get extraInfo => trade.extraId != null && trade.extraId!.isNotEmpty
? '\n\n' + S.current.exchange_extra_info
: '';
? "\n\n${S.current.exchange_extra_info}"
: "";
@computed
String get pendingTransactionFiatAmountValueFormatted => sendViewModel.isFiatDisabled
? ''
: sendViewModel.pendingTransactionFiatAmount + ' ' + sendViewModel.fiat.title;
? ""
: "${sendViewModel.pendingTransactionFiatAmount} ${sendViewModel.fiat.title}";
@computed
String get pendingTransactionFeeFiatAmountFormatted => sendViewModel.isFiatDisabled
? ''
: sendViewModel.pendingTransactionFeeFiatAmount + ' ' + sendViewModel.fiat.title;
? ""
: "${sendViewModel.pendingTransactionFeeFiatAmount} ${sendViewModel.fiat.title}";
@observable
ObservableList<ExchangeTradeItem> items;
@@ -204,7 +209,7 @@ abstract class ExchangeTradeViewModelBase with Store {
output = sendViewModel.outputs.first;
output.address = trade.inputAddress ?? '';
output.setCryptoAmount(trade.amount);
if (_provider is ThorChainExchangeProvider) output.memo = trade.memo;
if (_provider is ThorChainExchangeProvider) output.memo = trade.memo ?? "";
if (trade.isSendAll == true) output.sendAll = true;
}
@@ -264,12 +269,12 @@ abstract class ExchangeTradeViewModelBase with Store {
void _updateItems() {
final trade = tradesStore.trade!;
final tradeFrom = trade.fromRaw >= 0 ? trade.from : trade.userCurrencyFrom;
final tradeFrom = trade.fromRaw >= 0 ? trade.from : trade.userCurrencyFrom;
final tradeTo = trade.toRaw >= 0 ? trade.to : trade.userCurrencyTo;
final tagFrom = tradeFrom?.tag != null ? '${tradeFrom!.tag}' + ' ' : '';
final tagTo = tradeTo?.tag != null ? '${tradeTo!.tag}' + ' ' : '';
final tagFrom = tradeFrom?.tag != null ? "${tradeFrom!.tag} " : "";
final tagTo = tradeTo?.tag != null ? "${tradeTo!.tag} " : "";
items.clear();
@@ -277,7 +282,7 @@ abstract class ExchangeTradeViewModelBase with Store {
items.add(
ExchangeTradeItem(
title: "${trade.provider.title} ${S.current.id}",
data: '${trade.id}',
data: "${trade.id}",
isCopied: true,
isReceiveDetail: true,
isExternalSendDetail: false,
@@ -288,26 +293,45 @@ abstract class ExchangeTradeViewModelBase with Store {
items.addAll([
ExchangeTradeItem(
title: S.current.amount,
data: '${trade.amount} ${tradeFrom}',
data:
"${_amountParsingProxy.getDisplayCryptoAmount(trade.amount, tradeFrom!)} ${_amountParsingProxy.getCryptoSymbol(tradeFrom)}",
isCopied: false,
isReceiveDetail: false,
isExternalSendDetail: true,
),
ExchangeTradeItem(
title: S.current.you_will_receive_estimated_amount + ':',
data: '${tradesStore.trade?.receiveAmount} ${tradeTo}',
title: "${S.current.you_will_receive_estimated_amount}:",
data:
"${_amountParsingProxy.getDisplayCryptoAmount(tradesStore.trade?.receiveAmount ?? "0", tradeTo!)} ${_amountParsingProxy.getCryptoSymbol(tradeTo)}",
isCopied: true,
isReceiveDetail: true,
isExternalSendDetail: false,
),
ExchangeTradeItem(
title: S.current.send_to_this_address('${tradeFrom}', tagFrom) + ':',
data: trade.inputAddress ?? '',
title: "${S.current.send_to_this_address("${tradeFrom}", tagFrom)}:",
data: trade.inputAddress ?? "",
isCopied: false,
isReceiveDetail: false,
isExternalSendDetail: true,
),
]);
items.add(
isSwapsXYZCanSendFromExternal
? ExchangeTradeItem(
title: S.current.send_to_this_address('${tradeFrom}', tagFrom) +
':',
data: trade.inputAddress ?? '',
isCopied: false,
isReceiveDetail: false,
isExternalSendDetail: true)
: ExchangeTradeItem(
title: 'Smart contract call (no address required)',
data: 'Wallet will execute a contract call. On-chain transaction',
isCopied: false,
isReceiveDetail: false,
isExternalSendDetail: true),
);
}
final isExtraIdExist = trade.extraId != null && trade.extraId!.isNotEmpty;
@@ -315,24 +339,25 @@ abstract class ExchangeTradeViewModelBase with Store {
if (isExtraIdExist) {
final title = tradeFrom == CryptoCurrency.xrp
? S.current.destination_tag
: tradeFrom == CryptoCurrency.xlm || tradeFrom == CryptoCurrency.ton
: [CryptoCurrency.xlm, CryptoCurrency.ton].contains(tradeFrom)
? S.current.memo
: S.current.extra_id;
items.add(
ExchangeTradeItem(
title: title,
data: trade.extraId ?? '',
isCopied: true,
isReceiveDetail: !isExtraIdExist,
isExternalSendDetail: isExtraIdExist),
title: title,
data: trade.extraId ?? "",
isCopied: true,
isReceiveDetail: !isExtraIdExist,
isExternalSendDetail: isExtraIdExist,
),
);
}
items.add(
ExchangeTradeItem(
title: S.current.arrive_in_this_address('${tradeTo}', tagTo) + ':',
data: trade.payoutAddress ?? '',
title: "${S.current.arrive_in_this_address("${tradeTo}", tagTo)}:",
data: trade.payoutAddress ?? "",
isCopied: true,
isReceiveDetail: true,
isExternalSendDetail: false,
@@ -369,6 +394,7 @@ abstract class ExchangeTradeViewModelBase with Store {
wallet.currency == CryptoCurrency.bnb && tradeFrom?.tag == CryptoCurrency.bnb.tag;
return tradeFrom == wallet.currency ||
tradeFrom == CryptoCurrency.btcln && wallet.currency == CryptoCurrency.btc ||
tradesStore.trade!.provider == ExchangeProviderDescription.xmrto ||
_isEthToken() ||
_isPolygonToken() ||
@@ -379,6 +405,20 @@ abstract class ExchangeTradeViewModelBase with Store {
_isBscToken();
}
static bool _checkIfSwapsXYZCanSendFromExternal(Trade trade, WalletBase wallet) {
final provider = trade.provider;
if (provider == ExchangeProviderDescription.swapsXyz &&
isEVMCompatibleChain(wallet.type)) {
if(trade.routerData != null && trade.routerData != '0x') {
return false;
}
}
return true;
}
Future<void> registerSwapsXyzTransaction() async {
try {
if (!(_provider is SwapsXyzExchangeProvider)) return;
@@ -440,13 +480,11 @@ abstract class ExchangeTradeViewModelBase with Store {
switch (wallet.type) {
case WalletType.bitcoin:
return BitcoinURI(amount: amount, address: inputAddress);
case WalletType.litecoin:
return LitecoinURI(amount: amount, address: inputAddress);
return BitcoinURI(address: inputAddress, amount: amount);
case WalletType.bitcoinCash:
return BitcoinCashURI(amount: amount, address: inputAddress);
return BitcoinCashURI(address: inputAddress, amount: amount);
case WalletType.dogecoin:
return DogeURI(amount: amount, address: inputAddress);
return DogeURI(address: inputAddress, amount: amount);
case WalletType.ethereum:
return _createERC681URI(fromCurrency, inputAddress, amount);
// TODO: Expand ERC681URI support to Polygon(modify decoding flow for QRs, pay anything, and deep link handling)
@@ -463,17 +501,11 @@ abstract class ExchangeTradeViewModelBase with Store {
case WalletType.tron:
return TronURI(amount: amount, address: inputAddress);
case WalletType.monero:
return MoneroURI(amount: amount, address: inputAddress);
return MoneroURI(address: inputAddress, amount: amount);
case WalletType.wownero:
return WowneroURI(amount: amount, address: inputAddress);
case WalletType.zano:
return ZanoURI(amount: amount, address: inputAddress);
case WalletType.decred:
return DecredURI(amount: amount, address: inputAddress);
case WalletType.haven:
return HavenURI(amount: amount, address: inputAddress);
case WalletType.nano:
return NanoURI(amount: amount, address: inputAddress);
return MoneroURI(
address: inputAddress,
amount: amount);
default:
return null;
}
+509 -93
View File
@@ -6,6 +6,7 @@ import 'dart:developer';
import 'package:bitcoin_base/bitcoin_base.dart';
import 'package:cake_wallet/.secrets.g.dart' as secrets;
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/amount_parsing_proxy.dart';
import 'package:cake_wallet/core/create_trade_result.dart';
import 'package:cake_wallet/core/fiat_conversion_service.dart';
import 'package:cake_wallet/core/wallet_change_listener_view_model.dart';
@@ -28,13 +29,18 @@ import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/exolix_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/near_Intents_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/stealth_ex_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/swapsxyz_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/swaptrade_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/xoswap_exchange_provider.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/exchange/trade_request.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/src/screens/exchange/widgets/currency_picker.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/utils/show_pop_up.dart';
import 'package:cw_core/currency.dart';
import "package:cw_core/wallet_info.dart";
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/dashboard/trades_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
@@ -56,8 +62,8 @@ import 'package:cw_core/unspent_coin_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:intl/intl.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -68,27 +74,26 @@ class ExchangeViewModel = ExchangeViewModelBase with _$ExchangeViewModel;
abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with Store {
@override
void onWalletChange(wallet) {
receiveCurrency = wallet.currency;
depositCurrency = wallet.currency;
// FIXME this caused a bug when switching wallet, i can't figure out why it's here?
// receiveCurrency = wallet.currency;
// depositCurrency = wallet.currency;
}
ExchangeViewModelBase(
AppStore appStore,
this._appStore,
this.trades,
this._exchangeTemplateStore,
this.tradesStore,
this._settingsStore,
this.sharedPreferences,
this.contactListViewModel,
this.unspentCoinsListViewModel,
this.feesViewModel,
this.fiatConversionStore,
) : _cryptoNumberFormat = NumberFormat(),
isSendAllEnabled = false,
) : isSendAllEnabled = false,
isFixedRateMode = false,
isReceiveAmountEntered = false,
depositAmount = '',
receiveAmount = '',
_depositAmount = '',
_receiveAmount = '',
receiveAddress = '',
depositAddress = '',
isDepositAddressEnabled = false,
@@ -99,11 +104,11 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
limits = Limits(min: 0, max: 0),
tradeState = ExchangeTradeStateInitial(),
limitsState = LimitsInitialState(),
receiveCurrency = appStore.wallet!.currency,
depositCurrency = appStore.wallet!.currency,
receiveCurrency = _appStore.wallet!.currency,
depositCurrency = _appStore.wallet!.currency,
providerList = [],
selectedProviders = ObservableList<ExchangeProvider>(),
super(appStore: appStore) {
super(appStore: _appStore) {
_useTorOnly = _settingsStore.exchangeStatus == ExchangeApiMode.torOnly;
_setProviders();
const excludeDepositCurrencies = [CryptoCurrency.btt];
@@ -126,9 +131,11 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
/// if the provider is not in the user settings (user's first time or newly added provider)
/// then use its default value decided by us
selectedProviders = ObservableList.of(providerList
.where((element) => exchangeProvidersSelection[element.title] == null
? element.isEnabled
: (exchangeProvidersSelection[element.title] as bool))
.where((element) =>
(!forceDecentralizedExchanges || !element.description.isCentralized) &&
(exchangeProvidersSelection[element.title] == null
? element.isEnabled
: (exchangeProvidersSelection[element.title] as bool)))
.toList());
_setAvailableProviders();
@@ -150,12 +157,18 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
});
isDepositAddressEnabled = !useSameWalletAddress(depositCurrency);
depositAmount = '';
receiveAmount = '';
_depositAmount = '';
_receiveAmount = '';
receiveAddress = '';
depositAddress =
useSameWalletAddress(depositCurrency) ? wallet.walletAddresses.addressForExchange : '';
reaction((_) => receiveAddress, (_) {
if(!(tradeState is TradeIsCreatedSuccessfully)) {
receiveAddressDisplayName = null;
}
});
provider = providerList.firstOrNull;
final initialProvider = provider;
provider!.checkIsAvailable().then((bool isAvailable) {
@@ -165,6 +178,13 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
_onPairChange();
}
});
// providerDisplay is read by ui to display auto-selected provider.
// it's on a delay so it doesn't flicker.
reaction((_)=>bestRateProvider,(val) {
providerDisplay = val;
},delay: 300);
receiveCurrencies = CryptoCurrency.all
.where((cryptoCurrency) => !excludeReceiveCurrencies.contains(cryptoCurrency))
.toList()
@@ -180,28 +200,71 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
_defineIsReceiveAmountEditable();
loadLimits();
reaction((_) => isFixedRateMode, (Object _) {
bestRateProvider = null;
bestRate = 0.0;
loadLimits();
});
reaction((_) => forceDecentralizedExchanges, (val) {
if (val && (bestRateProvider?.description.isCentralized ?? false)) {
bestRateProvider = null;
bestRate = 0.0;
loadLimits();
}
});
if (isElectrumWallet) {
bitcoin!.updateFeeRates(wallet);
}
reaction((_) => wallet.currency, (_) async {
// When currency changes (e.g., EVM chain switch), update currencies
await Future.delayed(const Duration(milliseconds: 100));
receiveCurrency = wallet.currency;
depositCurrency = wallet.currency;
// Only refresh ETH tokens for EVM wallets
if (isEVMCompatibleChain(wallet.type)) {
_injectUserEthTokensIntoCurrencyLists();
fetchFiatPrice(receiveCurrency);
updateDepositAvailableAmount();
}
Future<void> updateDepositAvailableAmount() async {
if (depositCurrency == CryptoCurrency.btcln) {
final currency = depositCurrency;
Future.doWhile(() async {
await Future.delayed(const Duration(milliseconds: 400));
if (depositCurrency != currency) {
return false;
}
final balance = wallet.balance[depositCurrency];
if (balance != null) {
depositAvailableAmount = _appStore.amountParsingProxy
.getDisplayCryptoStringFromBigInt(balance.fullAvailableBalance, depositCurrency);
return false;
}
return true;
});
} else {
final currency = depositCurrency;
final amount = _appStore.amountParsingProxy.getDisplayCryptoString(
(await unspentCoinsListViewModel.getSendingBalance(UnspentCoinType.any)), depositCurrency);
if(depositCurrency == currency) {
depositAvailableAmount = amount;
}
});
}
}
void showFiatCurrencyPicker(BuildContext context) {
showPopUp<void>(
context: context,
builder: (_) => CurrencyPicker(
key: ValueKey('send_page_currency_picker_dialog_button_key'),
selectedAtIndex: FiatCurrency.all.indexOf(fiat),
items: FiatCurrency.all,
hintText: S.of(context).search_currency,
onItemSelected: (Currency cur) async {
_settingsStore.fiatCurrency = (cur as FiatCurrency);
},
),
);
}
bool useSameWalletAddress(CryptoCurrency currency) =>
currency == wallet.currency ||
(currency == CryptoCurrency.btcln && wallet.currency == CryptoCurrency.btc && wallet.isSoftwareWallet) ||
(currency.tag != null && currency.tag == wallet.currency.tag) ||
currency.tag == wallet.currency.title;
@@ -230,8 +293,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
LetsExchangeExchangeProvider(),
StealthExExchangeProvider(),
XOSwapExchangeProvider(),
SwapsXyzExchangeProvider(),
JupiterExchangeProvider(),
// SwapsXyzExchangeProvider(),
NearIntentsExchangeProvider(),
TrocadorExchangeProvider(
useTorOnly: _useTorOnly, providerStates: _settingsStore.trocadorProviderStates),
@@ -240,6 +303,9 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@observable
ExchangeProvider? provider;
@observable
ExchangeProvider? providerDisplay;
/// Maps in dart are not sorted by default
/// SplayTreeMap is a map sorted by keys
/// will use it to sort available providers
@@ -274,10 +340,25 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
ExchangeTradeState tradeState;
@observable
String depositAmount;
String _depositAmount;
@computed
String get depositAmount =>
_depositAmount == "..."? _depositAmount:amountParsingProxy.getDisplayCryptoAmount(_depositAmount, depositCurrency);
@computed
String get depositAmountCanonical => _depositAmount;
@observable
String receiveAmount;
String _receiveAmount;
@computed
String get receiveAmount =>
_receiveAmount == "..." ? _receiveAmount:amountParsingProxy.getDisplayCryptoAmount(_receiveAmount, receiveCurrency);
@action
// only set canonical formated amounts here;
void setCanonicalReceiveAmount(String value) => _receiveAmount = value;
@observable
String depositAddress;
@@ -285,6 +366,9 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@observable
String receiveAddress;
@observable
String? receiveAddressDisplayName;
@observable
bool isDepositAddressEnabled;
@@ -303,6 +387,12 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@observable
Limits limits;
@observable
bool tradeStarted = false;
@observable
bool isSendFromExternal = false;
@computed
SyncStatus get status => wallet.syncStatus;
@@ -314,6 +404,49 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
.where((element) => element.type == receiveCurrency)
.toList();
@computed
List<WalletContact> get refundWalletContactsToShow => contactListViewModel.walletContacts
.where((element) => element.type == depositCurrency)
.toList();
@computed
Future<List<WalletInfo>> get receiveWallets async {
WalletType? type;
type = cryptoCurrencyOrTokenToWalletType(receiveCurrency);
if (type == null) {
type = cryptoCurrencyOrTokenToWalletType(CryptoCurrency.fromString(receiveCurrency.tag ?? ""));
}
return await WalletInfo.selectList("type = ?", [type!.index]);
}
Future<List<WalletInfoAddressInfo>> addressesForWallet(WalletInfo wallet) async {
final List<WalletInfoAddressInfo> ret = [];
final addresses = await wallet.getAddressInfos();
for (var list in addresses.values) {
// we only want the "primary" account addresses - those that contain account names.
ret.addAll(list.where((item) => item.label.split(" ").length > 1));
}
return ret;
}
@computed
Future<List<WalletInfo>> get depositWallets async {
WalletType? type;
type = cryptoCurrencyOrTokenToWalletType(depositCurrency);
if (type == null) {
try {
type = cryptoCurrencyOrTokenToWalletType(CryptoCurrency.fromString(depositCurrency.tag ?? ""));
} catch (_) {}
}
if (type != null) {
return await WalletInfo.selectList("type = ?", [type.index]);
}
return await WalletInfo.getAll();
}
@action
bool checkIfWalletIsAnInternalWallet(String address) {
final walletContactList =
@@ -330,6 +463,13 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
bool get shouldDisplayTOTP2FAForExchangesToExternalWallet =>
_settingsStore.shouldRequireTOTP2FAForExchangesToExternalWallets;
@computed
String? get balanceDisplay {
final bal = wallet.balance[depositCurrency]?.fullAvailableBalance;
if(bal == null) return null;
return amountParsingProxy.getDisplayCryptoStringFromBigInt(bal, depositCurrency);
}
//* Still open to further optimize these checks
//* It works but can be made better
@action
@@ -343,6 +483,14 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
}
}
@computed
bool get decentralizedExchangesPromptDismissed => _settingsStore.decentralizedExchangesPromptDismissed;
@action
void dismissDecentralizedExchangesPrompt() {
_settingsStore.decentralizedExchangesPromptDismissed = true;
}
@computed
TransactionPriority get transactionPriority {
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
@@ -362,7 +510,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
WalletType.bitcoinCash,
WalletType.dogecoin,
].contains(wallet.type) &&
depositCurrency == wallet.currency;
(depositCurrency == wallet.currency);
bool get isMoneroWallet => wallet.type == WalletType.monero;
@@ -372,9 +520,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@observable
ObservableList<CryptoCurrency> depositCurrencies;
final NumberFormat _cryptoNumberFormat;
final SettingsStore _settingsStore;
final AppStore _appStore;
SettingsStore get _settingsStore => _appStore.settingsStore;
final ContactListViewModel contactListViewModel;
@@ -385,6 +532,31 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@observable
double bestRate = 0.0;
@computed
bool get useSatoshiDeposit => _appStore.amountParsingProxy.useSatoshi(depositCurrency);
@computed
bool get useSatoshisReceive => _appStore.amountParsingProxy.useSatoshi(receiveCurrency);
@computed
AmountParsingProxy get amountParsingProxy => _appStore.amountParsingProxy;
@observable
ExchangeProvider? bestRateProvider;
@observable
ExchangeProvider? forcedProvider;
@action
void setForcedProvider(ExchangeProvider? provider) {
forcedProvider = provider;
forcedProviderRate = 0.0;
calculateForcedProviderRate();
}
@observable
double forcedProviderRate = 0.0;
late Timer bestRateSync;
final FiatConversionStore fiatConversionStore;
@@ -411,12 +583,12 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
String get receiveAmountFiatFormatted {
var amount = '0.00';
try {
if (receiveAmount.isNotEmpty) {
if (_receiveAmount.isNotEmpty) {
if (fiatConversionStore.prices[receiveCurrency] == null) return '';
amount = calculateFiatAmount(
price: fiatConversionStore.prices[receiveCurrency]!,
cryptoAmount: receiveAmount,
cryptoAmount: _receiveAmount,
);
}
} catch (_) {
@@ -425,46 +597,143 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
return isFiatDisabled ? '' : '$amount';
}
@computed
String get depositAmountFiatFormatted {
var amount = '0.00';
try {
if (_depositAmount.isNotEmpty) {
if (fiatConversionStore.prices[depositCurrency] == null) return '';
amount = calculateFiatAmount(
price: fiatConversionStore.prices[depositCurrency]!,
cryptoAmount: _depositAmount,
);
}
} catch (_) {
log('Error calculating deposit amount fiat formatted: $_');
}
return isFiatDisabled ? '' : '$amount';
}
@computed
String get receiveAmountFiat {
var amount = '';
try {
if (_receiveAmount.isNotEmpty) {
if (fiatConversionStore.prices[receiveCurrency] == null) return '';
amount = calculateFiatAmount(
price: fiatConversionStore.prices[receiveCurrency]!,
cryptoAmount: _receiveAmount,
raw: true);
}
} catch (_) {
log('Error calculating receive amount fiat formatted: $_');
}
return amount;
}
@computed
String get depositAmountFiat {
var amount = '';
try {
if (_depositAmount.isNotEmpty) {
if (fiatConversionStore.prices[depositCurrency] == null) return '';
amount = calculateFiatAmount(
price: fiatConversionStore.prices[depositCurrency]!,
cryptoAmount: _depositAmount,
raw: true);
}
} catch (_) {
log('Error calculating deposit amount fiat formatted: $_');
}
return amount;
}
String roundedDepositAmount(int digits) {
if (depositAmount.split(".").last.length <= digits) {
return depositAmount;
}
try {
return double.parse(depositAmount).toStringAsPrecision(digits);
} catch(e) {
return "0";
}
}
String roundedReceiveAmount(int digits) {
if (receiveAmount.split(".").last.length <= digits) {
return receiveAmount;
}
try {
return double.parse(receiveAmount).toStringAsPrecision(digits);
} catch(e) {
return "0";
}
}
String roundedReceiveAmountFiat(int digits) {
if (receiveAmountFiat.split(".").last.length <= digits) {
return receiveAmountFiat;
}
return double.parse(receiveAmountFiat).toStringAsPrecision(digits);
}
String roundedDepositAmountFiat(int digits) {
if (depositAmountFiat.split(".").last.length <= digits) {
return depositAmountFiat;
}
return double.parse(depositAmountFiat).toStringAsPrecision(digits);
}
@action
void changeDepositCurrency({required CryptoCurrency currency}) {
depositCurrency = currency;
isFixedRateMode = false;
_onPairChange();
isDepositAddressEnabled = !useSameWalletAddress(depositCurrency);
fetchFiatPrice(currency);
updateDepositAvailableAmount();
}
@action
void changeReceiveCurrency({required CryptoCurrency currency}) {
if (!(currency.tag == receiveCurrency.tag ||
currency.tag == receiveCurrency.title ||
currency.title == receiveCurrency.tag ||
currency == receiveCurrency)) {
receiveAddress = "";
}
receiveCurrency = currency;
isFixedRateMode = false;
_onPairChange();
isDepositAddressEnabled = !useSameWalletAddress(depositCurrency);
fetchFiatPrice(currency);
}
@action
Future<void> changeReceiveAmount({required String amount}) async {
receiveAmount = amount;
amount = amountParsingProxy.getCanonicalCryptoAmount(amount, receiveCurrency);
_receiveAmount = amount;
if (amount.isEmpty) {
depositAmount = '';
receiveAmount = '';
_depositAmount = '';
_receiveAmount = '';
return;
}
final _enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0;
final _enteredAmount = double.tryParse(_receiveAmount.replaceAll(',', '.')) ?? 0;
if (bestRate == 0) {
depositAmount = S.current.fetching;
_depositAmount = "...";
await calculateBestRate();
}
_cryptoNumberFormat.maximumFractionDigits = depositMaxDigits;
depositAmount = _cryptoNumberFormat
.format(_enteredAmount / bestRate)
.toString()
.replaceAll(RegExp('\\,'), '');
final amount_ = _enteredAmount / (forcedProvider == null ? bestRate : forcedProviderRate);
_depositAmount = amount_.toString().withMaxDecimals(depositCurrency.decimals);
}
@action
@@ -474,19 +743,33 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
if (price == null || price == 0.0) return;
final crypto = _enteredAmount / price;
final receiveAmountTmp = _cryptoNumberFormat.format(crypto);
if (receiveAmount != receiveAmountTmp) {
changeReceiveAmount(amount: receiveAmountTmp.withMaxDecimals(receiveCurrency.decimals));
final _receiveAmountTmp = crypto.toString().withMaxDecimals(receiveCurrency.decimals);
if (_receiveAmount != _receiveAmountTmp) {
changeReceiveAmount(amount: _receiveAmountTmp);
}
}
@action
Future<void> changeDepositAmount({required String amount}) async {
depositAmount = amount;
void setDepositAmountFromFiat({required String fiatAmount}) {
final _enteredAmount = double.tryParse(fiatAmount.replaceAll(',', '.')) ?? 0.0;
final price = fiatConversionStore.prices[depositCurrency];
if (price == null || price == 0.0) return;
final crypto = _enteredAmount / price;
final depositAmountTmp = crypto.toString().withMaxDecimals(receiveCurrency.decimals);
if (_depositAmount != depositAmountTmp) {
changeDepositAmount(amount: depositAmountTmp, isCanonical: true);
}
}
@action
Future<void> changeDepositAmount({required String amount, bool isCanonical = false}) async {
_depositAmount = isCanonical ? amount.replaceAll(',', '.') : _appStore.amountParsingProxy
.getCanonicalCryptoAmount(amount.replaceAll(',', '.'), depositCurrency);
if (amount.isEmpty) {
depositAmount = '';
receiveAmount = '';
_depositAmount = '';
_receiveAmount = '';
return;
}
@@ -494,21 +777,17 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
/// as it should remain exactly what the user set
if (isFixedRateMode) return;
final _enteredAmount = double.tryParse(amount.replaceAll(',', '.')) ?? 0;
final _enteredAmount = double.tryParse(_depositAmount) ?? 0;
/// in case the best rate was not calculated yet
if (bestRate == 0) {
receiveAmount = S.current.fetching;
_receiveAmount = "...";
await calculateBestRate();
}
_cryptoNumberFormat.maximumFractionDigits = receiveMaxDigits;
receiveAmount = _cryptoNumberFormat
.format(bestRate * _enteredAmount)
.toString()
.replaceAll(RegExp('\\,'), '');
final amount_ = _enteredAmount * (forcedProvider == null ? bestRate : forcedProviderRate);
_receiveAmount = amount_.toString().withMaxDecimals(receiveCurrency.decimals);
}
bool checkIfInputMeetsMinOrMaxCondition(String input) {
@@ -523,12 +802,30 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
return true;
}
Future<void> calculateForcedProviderRate() async {
if (forcedProvider == null || depositCurrency == receiveCurrency) {
forcedProviderRate = 0.0;
return;
}
final amount = double.tryParse(isFixedRateMode ? _receiveAmount : _depositAmount) ??
initialAmountByAssets(isFixedRateMode ? receiveCurrency : depositCurrency);
forcedProviderRate = await forcedProvider!.fetchRate(
from: depositCurrency,
to: receiveCurrency,
amount: amount,
isFixedRateMode: isFixedRateMode,
isReceiveAmount: isFixedRateMode);
}
Future<void> calculateBestRate() async {
if (depositCurrency == receiveCurrency) {
bestRate = 0.0;
bestRateProvider = null;
return;
}
final amount = double.tryParse(isFixedRateMode ? receiveAmount : depositAmount) ??
final amount = double.tryParse(isFixedRateMode ? _receiveAmount : _depositAmount) ??
initialAmountByAssets(isFixedRateMode ? receiveCurrency : depositCurrency);
final validProvidersForAmount = _tradeAvailableProviders.where((provider) {
@@ -581,7 +878,10 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
_sortedAvailableProviders.clear();
_sortedAvailableProviders.addAll(newSortedProviders);
if (_sortedAvailableProviders.isNotEmpty) bestRate = _sortedAvailableProviders.keys.first;
if (_sortedAvailableProviders.isNotEmpty) {
bestRate = _sortedAvailableProviders.keys.first;
bestRateProvider = _sortedAvailableProviders.values.first;
}
}
@action
@@ -654,7 +954,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
Future<void> createTrade() async {
if (isSendAllEnabled) {
await calculateDepositAllAmount();
final amount = double.tryParse(depositAmount);
final amount = double.tryParse(_depositAmount);
if (limits.min != null && amount != null && amount < limits.min!) {
tradeState = TradeIsCreatedFailure(
@@ -664,11 +964,34 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
}
}
if (depositCurrency == CryptoCurrency.btcln &&
depositAddress == wallet.walletAddresses.addressForExchange) {
final invoice = await bitcoin!.getLightningInvoice(wallet, BigInt.zero);
if (invoice != null) {
depositAddress = invoice;
}
}
if (receiveCurrency == CryptoCurrency.btcln &&
receiveAddress == wallet.walletAddresses.addressForExchange) {
final invoice = await bitcoin!.getLightningInvoice(wallet, BigInt.zero);
if (invoice != null) {
receiveAddress = invoice;
}
}
late final Map<double, ExchangeProvider> providers;
if (forcedProvider != null) {
providers = {forcedProviderRate: forcedProvider!};
} else {
providers = _sortedAvailableProviders;
}
// Ensure we have providers available before attempting to create trade
if (_sortedAvailableProviders.isEmpty) {
if (providers.isEmpty) {
await calculateBestRate();
if (_sortedAvailableProviders.isEmpty) {
if (providers.isEmpty) {
tradeState = TradeIsCreatedFailure(
title: S.current.trade_not_created,
error: S.current.none_of_selected_providers_can_exchange);
@@ -678,8 +1001,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
try {
// snapshot of providers to avoid concurrent modification issues
final providersSnapshot = _sortedAvailableProviders.values.toList();
final ratesSnapshot = _sortedAvailableProviders.keys.toList();
final providersSnapshot = providers.values.toList();
final ratesSnapshot = providers.keys.toList();
for (var i = 0; i < providersSnapshot.length; i++) {
final provider = providersSnapshot[i];
@@ -688,13 +1011,15 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
if (!(await provider.checkIsAvailable())) continue;
bestRate = providerRate;
await changeDepositAmount(amount: depositAmount);
bestRateProvider = provider;
await changeDepositAmount(amount: _depositAmount, isCanonical: true);
final request = TradeRequest(
fromCurrency: depositCurrency,
toCurrency: receiveCurrency,
fromAmount: depositAmount.replaceAll(',', '.'),
toAmount: receiveAmount.replaceAll(',', '.'),
fromAmount: _depositAmount.replaceAll(',', '.'),
toAmount: _receiveAmount.replaceAll(',', '.'),
refundAddress: depositAddress,
toAddress: receiveAddress,
isFixedRate: isFixedRateMode,
@@ -705,7 +1030,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
await wallet.walletAddresses.saveAddressesInBox();
}
var amount = isFixedRateMode ? receiveAmount : depositAmount;
var amount = isFixedRateMode ? _receiveAmount : _depositAmount;
amount = amount.replaceAll(',', '.');
if (limitsState is LimitsLoadedSuccessfully) {
@@ -729,11 +1054,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
final canCreateTrade = await isCanCreateTrade(trade);
if (!canCreateTrade.result) {
tradeState = TradeIsCreatedFailure(
title: S.current.trade_not_created,
error: canCreateTrade.errorMessage ?? '',
);
return;
continue;
}
tradesStore.setTrade(trade);
@@ -767,8 +1088,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
void reset() {
_initialPairBasedOnWallet();
isReceiveAmountEntered = false;
depositAmount = '';
receiveAmount = '';
_depositAmount = '';
_receiveAmount = '';
depositAddress =
depositCurrency == wallet.currency ? wallet.walletAddresses.addressForExchange : '';
receiveAddress =
@@ -801,21 +1122,40 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
].contains(wallet.type)) {
final priority = _settingsStore.getPriority(wallet.type)!;
final amount = await bitcoin!.estimateFakeSendAllTxAmount(
wallet,
priority,
coinTypeToSpendFrom:
wallet.type == WalletType.litecoin ? UnspentCoinType.nonMweb : UnspentCoinType.any,
);
final amount = depositCurrency == CryptoCurrency.btcln
// FIXME amount estimation is broken/impossible for ln, konsti suggested this
? (amountParsingProxy
.parseCryptoString(depositAvailableAmount, depositCurrency).toInt() - 10)
: await bitcoin!.estimateFakeSendAllTxAmount(
wallet,
priority,
coinTypeToSpendFrom: wallet.type == WalletType.litecoin
? UnspentCoinType.nonMweb
: depositCurrency == CryptoCurrency.btcln
? UnspentCoinType.lightning
: UnspentCoinType.any,
);
changeDepositAmount(amount: wallet.formatCryptoAmount(amount.toString()));
changeDepositAmount(amount: wallet.currency.formatAmount(BigInt.from(amount)), isCanonical: true);
} else if (wallet.type == WalletType.monero) {
final amount = await unspentCoinsListViewModel.getSendingBalance(UnspentCoinType.any);
changeDepositAmount(amount: wallet.formatCryptoAmount(amount.toString()));
changeDepositAmount(amount: wallet.currency.formatAmount(BigInt.from(amount)), isCanonical: true);
}
}
@observable
String depositAvailableAmount = "";
@action
void reverseSwapDirection() {
final tmpAmount = _receiveAmount;
final tmpCurrency = depositCurrency;
changeDepositCurrency(currency: receiveCurrency);
changeReceiveCurrency(currency: tmpCurrency);
_depositAmount = tmpAmount;
}
void updateTemplate() => _exchangeTemplateStore.update();
void addTemplate(
@@ -841,9 +1181,10 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
_exchangeTemplateStore.remove(template: template);
void _onPairChange() {
depositAmount = '';
receiveAmount = '';
_depositAmount = '';
_receiveAmount = '';
bestRate = 0.0;
bestRateProvider = null;
loadLimits();
_setAvailableProviders();
}
@@ -953,7 +1294,8 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@action
void addExchangeProvider(ExchangeProvider provider) {
selectedProviders.add(provider);
if (provider.description.isCentralized && forceDecentralizedExchanges) return;
if (!selectedProviders.contains(provider)) selectedProviders.add(provider);
if (providerList.contains(provider)) _tradeAvailableProviders.add(provider);
}
@@ -961,14 +1303,18 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
void removeExchangeProvider(ExchangeProvider provider) {
selectedProviders.remove(provider);
_tradeAvailableProviders.remove(provider);
if (forcedProvider == provider) {
setForcedProvider(null);
}
}
@action
void saveSelectedProviders() {
depositAmount = '';
receiveAmount = '';
_depositAmount = '';
_receiveAmount = '';
isFixedRateMode = false;
_defineIsReceiveAmountEditable();
bestRateProvider = null;
bestRate = 0.0;
loadLimits();
@@ -1002,6 +1348,29 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
.any((element) => element.isAvailable && providerList.contains(element));
}
@computed
bool get forceDecentralizedExchanges => _settingsStore.forceDecentralizedExchanges;
@action
void toggleForceDecentralizedExchanges() {
_settingsStore.forceDecentralizedExchanges = !_settingsStore.forceDecentralizedExchanges;
if(forceDecentralizedExchanges) {
final providers = selectedProviders.toList();
for (final provider in providers) {
if (forceDecentralizedExchanges && provider.description.isCentralized) {
removeExchangeProvider(provider);
}
}
} else {
for(final provider in providerList) {
if(!selectedProviders.contains(provider) && provider.description.isCentralized) {
addExchangeProvider(provider);
}
}
}
}
void _setAvailableProviders() {
_tradeAvailableProviders.clear();
@@ -1021,6 +1390,53 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
int get receiveMaxDigits => receiveCurrency.decimals;
Future<CreateTradeResult> isCanCreateTrade(Trade trade) async {
if (trade.provider == ExchangeProviderDescription.swapsXyz) {
final tradeFrom = trade.fromRaw >= 0 ? trade.from : trade.userCurrencyFrom;
if (tradeFrom == null) {
return CreateTradeResult(
result: false,
errorMessage: 'From currency is null',
);
}
final isNativeSupportedToken = walletTypes.contains(cryptoCurrencyOrTokenToWalletType(tradeFrom));
if (!isNativeSupportedToken) {
bool _isEthToken() =>
wallet.currency == CryptoCurrency.eth && tradeFrom.tag == CryptoCurrency.eth.title;
bool _isPolygonToken() =>
wallet.currency == CryptoCurrency.maticpoly &&
tradeFrom.tag == CryptoCurrency.maticpoly.tag;
bool _isBaseToken() =>
wallet.currency == CryptoCurrency.baseEth && tradeFrom.tag == CryptoCurrency.baseEth.tag;
bool _isTronToken() =>
wallet.currency == CryptoCurrency.trx && tradeFrom.tag == CryptoCurrency.trx.title;
bool _isSplToken() =>
wallet.currency == CryptoCurrency.sol && tradeFrom.tag == CryptoCurrency.sol.title;
bool isArbitrumToken() =>
wallet.currency == CryptoCurrency.arbEth && tradeFrom.tag == CryptoCurrency.arbEth.tag;
bool isBscToken() =>
wallet.currency == CryptoCurrency.bnb && tradeFrom.tag == CryptoCurrency.bnb.tag;
if(!(_isEthToken() || _isPolygonToken() || _isBaseToken() || _isTronToken() || _isSplToken() || isArbitrumToken() || isBscToken())) {
return CreateTradeResult(
result: false,
errorMessage: 'This token isn’t supported on the current wallet/network for Swaps.xyz. Switch to a supported wallet or asset',
);
}
}
}
if (trade.provider == ExchangeProviderDescription.thorChain) {
final payoutAddress = trade.payoutAddress ?? '';
final fromWalletAddress = trade.fromWalletAddress ?? '';
@@ -1,6 +1,11 @@
import 'dart:math';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cw_core/balance_card_style_settings.dart';
import 'package:cw_core/card_design.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/monero/monero.dart';
@@ -33,7 +38,30 @@ abstract class MoneroAccountEditOrCreateViewModelBase with Store {
final AccountListItem? _accountListItem;
final WalletBase _wallet;
Future<List<Gradient>> _getUsableCardGradients() async {
final List<Gradient> ret = List<Gradient>.from(CardDesign.allGradients);
final designs = (await BalanceCardStyleSettings.getAll(_wallet.walletInfo.internalId))
.map((item) => CardDesign.fromStyleSettings(item, _wallet.currency));
for (final design in designs) {
ret.remove(design.gradient);
}
return ret.isNotEmpty ? ret : CardDesign.allGradients;
}
Future<void> _saveRandomCardDesign() async {
final gradients = await _getUsableCardGradients();
await BalanceCardStyleSettings.fromCardDesign(
_wallet.walletInfo.internalId,
_moneroAccountList.accounts.length,
_moneroAccountList.accounts.length,
CardDesign.specialDesignsForCurrencies[_wallet.currency]!
.withGradient(gradients[Random().nextInt(gradients.length)]))
.insert();
}
Future<void> save() async {
await _saveRandomCardDesign();
if (_wallet.type == WalletType.monero) {
await saveMonero();
}
@@ -56,6 +56,12 @@ abstract class MoneroAccountListViewModelBase with Store {
throw Exception('Unexpected wallet type: ${_wallet.type} for monero');
}
@computed
AccountListItem get selected {
final currentId = monero!.getCurrentAccount(_wallet).id;
return accounts.firstWhere((item) => item.id == currentId);
}
final WalletBase _wallet;
void select(AccountListItem item) {
@@ -1,38 +1,79 @@
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/entities/new_ui_entities/list_item/list_item.dart';
import 'package:cake_wallet/entities/qr_scanner.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/permission_handler.dart';
import 'package:collection/collection.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:flutter/cupertino.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:collection/collection.dart';
import 'package:cake_wallet/utils/permission_handler.dart';
import 'package:permission_handler/permission_handler.dart';
part 'node_create_or_edit_view_model.g.dart';
class NodeCreateOrEditViewModel = NodeCreateOrEditViewModelBase with _$NodeCreateOrEditViewModel;
class NodeCreateOrEditViewModel = NodeCreateOrEditViewModelBase
with _$NodeCreateOrEditViewModel;
abstract class NodeCreateOrEditViewModelBase with Store {
NodeCreateOrEditViewModelBase(this._nodeSource, this._walletType, this._settingsStore)
NodeCreateOrEditViewModelBase(
this._nodeSource, this.walletType, this.editingNode, this._settingsStore)
: state = InitialExecutionState(),
connectionState = InitialExecutionState(),
useSSL = false,
address = '',
path = '',
port = '',
login = '',
password = '',
trusted = false,
isEnabledForAutoSwitching = false,
useSocksProxy = false,
socksProxyAddress = '';
label = editingNode?.label ?? '',
address = editingNode?.uri.host.toString() ?? '',
path = editingNode?.path.toString() ?? '',
port = (editingNode != null && editingNode.uri.hasPort)
? editingNode.uri.port.toString()
: '',
login = editingNode?.login ?? '',
password = editingNode?.password ?? '',
socksProxyAddress = editingNode?.socksProxyAddress ?? '',
trusted = editingNode?.trusted ?? false,
isEnabledForAutoSwitching =
editingNode?.isEnabledForAutoSwitching ?? false,
useSocksProxy = editingNode?.socksProxyAddress != null &&
editingNode!.socksProxyAddress!.isNotEmpty,
useSSL = editingNode?.useSSL ?? false {
}
final nodeLabelUIKey = 'node_label_row_key';
final nodeAddressUIKey = 'node_address_row_key';
final nodePathUIKey = 'node_path_row_key';
final nodeUsernameUIKey = 'node_username_row_key';
final nodePasswordUIKey = 'node_password_row_key';
final nodePortUIKey = 'node_port_row_key';
final useSSLUIKey = 'node_use_ssl_row_key';
final nodeTrustedUIKey = 'node_trusted_daemon_row_key';
final nodeEmbeddedTorProxyUIKey = 'node_embedded_tor_proxy_row_key';
final autoSwitchingUIKey = 'node_auto_switching_row_key';
final useSocksProxyUIKey = 'node_use_socks_proxy_row_key';
final socksProxyAddressUIKey = 'node_socks_proxy_address_row_key';
late final textFieldKeys = [
nodeLabelUIKey,
nodeAddressUIKey,
nodePathUIKey,
nodePortUIKey,
nodeUsernameUIKey,
nodePasswordUIKey,
socksProxyAddressUIKey,
];
Map<String, List<ListItem>> nodeFormItems = {};
//TODO: Remove example values when done testing
bool toggleExampleValue = false;
bool checkboxExampleValue = false;
@observable
ExecutionState state;
@observable
String label;
@observable
String address;
@@ -71,13 +112,16 @@ abstract class NodeCreateOrEditViewModelBase with Store {
@computed
bool get isReady =>
(address.isNotEmpty) || _walletType == WalletType.decred; // Allow an empty address.
(address.isNotEmpty) ||
walletType == WalletType.decred; // Allow an empty address.
bool get hasAuthCredentials =>
_walletType == WalletType.monero || _walletType == WalletType.wownero || _walletType == WalletType.haven;
walletType == WalletType.monero ||
walletType == WalletType.wownero ||
walletType == WalletType.haven;
bool get hasPathSupport {
switch (_walletType) {
switch (walletType) {
case WalletType.ethereum:
case WalletType.polygon:
case WalletType.base:
@@ -113,10 +157,48 @@ abstract class NodeCreateOrEditViewModelBase with Store {
return uri;
}
final WalletType _walletType;
final WalletType walletType;
final Node? editingNode;
final Box<Node> _nodeSource;
final SettingsStore _settingsStore;
void updateViewModelFromText(String key, String value) {
if (key == nodeLabelUIKey) setLabel(value);
if (key == nodeAddressUIKey) setAddress(value);
if (key == nodePortUIKey) setPort(value);
if (key == nodePathUIKey) setPath(value);
if (key == nodeUsernameUIKey) setLogin(value);
if (key == nodePasswordUIKey) setPassword(value);
if (key == socksProxyAddressUIKey) setSocksProxyAddress(value);
}
void updateCheckboxValue(String key, bool value) {
if (key == useSSLUIKey) setSSL(value);
if (key == nodeTrustedUIKey) setTrusted(value);
if (key == useSocksProxyUIKey) setSocksProxy(value);
if (key == autoSwitchingUIKey) setIsEnabledForAutoSwitching(value);
}
bool getCheckboxValue(String key) {
if (key == useSSLUIKey) return useSSL;
if (key == nodeTrustedUIKey) return trusted;
if (key == nodeEmbeddedTorProxyUIKey) return usesEmbeddedProxy;
if (key == useSocksProxyUIKey) return useSocksProxy;
if (key == autoSwitchingUIKey) return isEnabledForAutoSwitching;
return false;
}
String getTextValue(String key) {
if (key == nodeLabelUIKey) return label;
if (key == nodeAddressUIKey) return address;
if (key == nodePortUIKey) return port;
if (key == nodePathUIKey) return path;
if (key == nodeUsernameUIKey) return login;
if (key == nodePasswordUIKey) return password;
if (key == socksProxyAddressUIKey) return socksProxyAddress;
return '';
}
@action
void reset() {
address = '';
@@ -131,6 +213,9 @@ abstract class NodeCreateOrEditViewModelBase with Store {
socksProxyAddress = '';
}
@action
void setLabel(String val) => label = val;
@action
void setPort(String val) => port = val;
@@ -153,7 +238,8 @@ abstract class NodeCreateOrEditViewModelBase with Store {
void setTrusted(bool val) => trusted = val;
@action
void setIsEnabledForAutoSwitching(bool val) => isEnabledForAutoSwitching = val;
void setIsEnabledForAutoSwitching(bool val) =>
isEnabledForAutoSwitching = val;
@action
void setSocksProxy(bool val) => useSocksProxy = val;
@@ -164,9 +250,10 @@ abstract class NodeCreateOrEditViewModelBase with Store {
@action
Future<void> save({Node? editingNode, bool saveAsCurrent = false}) async {
final node = Node(
label: label,
uri: uri,
path: path,
type: _walletType,
type: walletType,
login: login,
password: password,
useSSL: useSSL,
@@ -198,7 +285,7 @@ abstract class NodeCreateOrEditViewModelBase with Store {
final node = Node(
uri: uri,
path: path,
type: _walletType,
type: walletType,
login: login,
password: password,
useSSL: useSSL,
@@ -225,7 +312,7 @@ abstract class NodeCreateOrEditViewModelBase with Store {
}
@action
void setAsCurrent(Node node) => _settingsStore.nodes[_walletType] = node;
void setAsCurrent(Node node) => _settingsStore.nodes[walletType] = node;
@action
Future<void> scanQRCodeForNewNode(BuildContext context) async {
@@ -240,7 +327,8 @@ abstract class NodeCreateOrEditViewModelBase with Store {
throw Exception('Unexpected scan QR code value: value is empty');
}
if (code.startsWith("monero_node:")) code = code.replaceFirst("monero_node:", "tcp://");
if (code.startsWith("monero_node:"))
code = code.replaceFirst("monero_node:", "tcp://");
if (!code.contains('://')) code = 'tcp://$code';
final uri = Uri.tryParse(code);
@@ -76,6 +76,12 @@ abstract class PaymentViewModelBase with Store {
final currentWallet = appStore.wallet;
if (currentWallet != null &&
currentWallet.type == detectedWalletType &&
!isEVMCompatibleChain(detectedWalletType!)) {
return PaymentFlowResult.currentWalletCompatible();
}
if (detectedWalletType == WalletType.solana) {
final compatibleWallets = await getWalletsByType(WalletType.solana);
return PaymentFlowResult.solanaTokenSelection(
@@ -98,10 +104,6 @@ abstract class PaymentViewModelBase with Store {
return PaymentFlowResult.evmNetworkSelection(detectionResult);
}
if (currentWallet != null && currentWallet.type == detectedWalletType) {
return PaymentFlowResult.currentWalletCompatible();
}
final compatibleWallets = await getWalletsByType(detectedWalletType!);
switch (compatibleWallets.length) {
+6 -3
View File
@@ -1,4 +1,5 @@
import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart';
import 'package:cake_wallet/core/amount_parsing_proxy.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/dogecoin/dogecoin.dart';
import 'package:cake_wallet/entities/priority_for_wallet_type.dart';
@@ -25,7 +26,7 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
FeesViewModelBase(
AppStore appStore,
this.balanceViewModel,
) : _settingsStore = appStore.settingsStore,
) : _appStore = appStore,
super(appStore: appStore) {
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
@@ -39,6 +40,10 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
}
}
final AppStore _appStore;
SettingsStore get _settingsStore => _appStore.settingsStore;
AmountParsingProxy get amountParsingProxy => _appStore.amountParsingProxy;
@computed
WalletType get walletType => wallet.type;
CryptoCurrency get currency => wallet.currency;
@@ -138,8 +143,6 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
@computed
FiatCurrency get fiatCurrency => _settingsStore.fiatCurrency;
final SettingsStore _settingsStore;
@action
void setTransactionPriority(TransactionPriority priority) =>
_settingsStore.setPriority(wallet.type, priority, chainId: wallet.chainId);
+80 -41
View File
@@ -1,4 +1,4 @@
import 'dart:math';
import 'dart:math' show min;
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/di.dart';
@@ -13,6 +13,7 @@ import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/src/screens/send/widgets/extract_address_from_parsed.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/tron/tron.dart';
@@ -20,7 +21,9 @@ import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/balance.dart';
import 'package:cw_core/crypto_amount_format.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/format_fixed.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
@@ -37,8 +40,7 @@ const String cryptoNumberPattern = '0.0';
class Output = OutputBase with _$Output;
abstract class OutputBase with Store {
OutputBase(
this._wallet, this._settingsStore, this._fiatConversationStore, this.cryptoCurrencyHandler)
OutputBase(this._wallet, this._appStore, this._fiatConversationStore, this.cryptoCurrencyHandler)
: key = UniqueKey(),
sendAll = false,
cryptoAmount = '',
@@ -46,6 +48,7 @@ abstract class OutputBase with Store {
fiatAmount = '',
address = '',
note = '',
memo = "",
extractedAddress = '',
estimatedFee = '0.0',
parsedAddress = ParsedAddress(addresses: []) {
@@ -59,12 +62,21 @@ abstract class OutputBase with Store {
Key key;
bool get useSatoshi => _appStore.amountParsingProxy.useSatoshi(cryptoCurrencyHandler());
@observable
String fiatAmount;
@observable
String cryptoAmount;
@observable
String? displayName;
@computed
String get displayCryptoAmount =>
_appStore.amountParsingProxy.getDisplayCryptoAmount(cryptoAmount, cryptoCurrencyHandler());
@observable
String cryptoFullBalance;
@@ -73,6 +85,9 @@ abstract class OutputBase with Store {
@observable
String note;
@observable
String memo;
@observable
bool sendAll;
@@ -83,12 +98,20 @@ abstract class OutputBase with Store {
@observable
String extractedAddress;
String? memo;
@computed
bool get isParsedAddress =>
parsedAddress.parseFrom != ParseFrom.notParsed && parsedAddress.name.isNotEmpty;
String roundedCryptoAmount(int digits) => displayCryptoAmount.withMaxDecimals(digits);
String roundedFiatAmount(int digits) {
if (fiatAmount.split(".").last.length <= digits) {
return fiatAmount;
}
return double.parse(fiatAmount.replaceAll(",", "")).toStringAsPrecision(digits);
}
@observable
String? stealthAddress;
@@ -108,7 +131,7 @@ abstract class OutputBase with Store {
case WalletType.litecoin:
case WalletType.bitcoinCash:
case WalletType.dogecoin:
_amount = bitcoin!.formatterStringDoubleToBitcoinAmount(_cryptoAmount);
_amount = cryptoCurrencyHandler().parseAmount(_cryptoAmount).toInt();
break;
case WalletType.decred:
_amount = decred!.formatterStringDoubleToDecredAmount(_cryptoAmount);
@@ -171,37 +194,36 @@ abstract class OutputBase with Store {
switch (_wallet.type) {
case WalletType.monero:
estimatedFee = monero!.formatterMoneroAmountToDouble(amount: fee).toString();
case WalletType.wownero:
case WalletType.litecoin:
case WalletType.bitcoinCash:
case WalletType.dogecoin:
case WalletType.decred:
estimatedFee = walletTypeToCryptoCurrency(_wallet.type).formatAmount(BigInt.from(fee));
break;
case WalletType.bitcoin:
if (cryptoCurrencyHandler() == CryptoCurrency.btcln) {
estimatedFee =
_appStore.amountParsingProxy.getDisplayCryptoString(10, cryptoCurrencyHandler());
break;
}
if (_settingsStore.getPriority(_wallet.type) ==
bitcoin!.getBitcoinTransactionPriorityCustom()) {
fee = bitcoin!.getEstimatedFeeWithFeeRate(
_wallet, _settingsStore.customBitcoinFeeRate, formattedCryptoAmount);
}
estimatedFee = bitcoin!.formatterBitcoinAmountToDouble(amount: fee).toString();
break;
case WalletType.litecoin:
case WalletType.bitcoinCash:
case WalletType.dogecoin:
estimatedFee = bitcoin!.formatterBitcoinAmountToDouble(amount: fee).toString();
estimatedFee = _appStore.amountParsingProxy.getDisplayCryptoString(fee, cryptoCurrencyHandler());
break;
case WalletType.solana:
estimatedFee = solana!.getEstimateFees(_wallet).toString();
break;
case WalletType.wownero:
estimatedFee = wownero!.formatterWowneroAmountToDouble(amount: fee).toString();
break;
case WalletType.zano:
estimatedFee = zano!
.formatterIntAmountToDouble(
amount: fee, currency: cryptoCurrencyHandler(), forFee: true)
.toString();
break;
case WalletType.decred:
estimatedFee = decred!.formatterDecredAmountToDouble(amount: fee).toString();
break;
case WalletType.tron:
if (cryptoCurrencyHandler() == CryptoCurrency.trx) {
estimatedFee = tron!.getTronNativeEstimatedFee(_wallet).toString();
@@ -209,7 +231,7 @@ abstract class OutputBase with Store {
estimatedFee = tron!.getTronTRC20EstimatedFee(_wallet).toString();
}
break;
case WalletType.zcash:
estimatedFee = zcash!.formatterZcashAmountToDouble(amount: BigInt.from(fee)).toString();
break;
@@ -253,29 +275,35 @@ abstract class OutputBase with Store {
try {
final currency = (isEVMCompatibleChain(_wallet.type) ||
_wallet.type == WalletType.solana ||
_wallet.type == WalletType.tron)
[WalletType.solana, WalletType.tron].contains(_wallet.type))
? _wallet.currency
: cryptoCurrencyHandler();
final fiat = calculateFiatAmountRaw(
price: _fiatConversationStore.prices[currency]!,
cryptoAmount: double.parse(estimatedFee));
return fiat;
final cryptoAmount =
double.parse(_appStore.amountParsingProxy.getCanonicalCryptoAmount(estimatedFee, currency));
return calculateFiatAmountRaw(
price: _fiatConversationStore.prices[currency]!, cryptoAmount: cryptoAmount);
} catch (_) {
return '0.00';
}
}
WalletType get walletType => _wallet.type;
final CryptoCurrency Function() cryptoCurrencyHandler;
@observable
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> _wallet;
final SettingsStore _settingsStore;
WalletType get walletType => _wallet.type;
final CryptoCurrency Function() cryptoCurrencyHandler;
final FiatConversionStore _fiatConversationStore;
final AppStore _appStore;
SettingsStore get _settingsStore => _appStore.settingsStore;
@action
void setSendAll(String fullBalance) {
cryptoFullBalance = fullBalance;
cryptoFullBalance =
_appStore.amountParsingProxy.getCanonicalCryptoAmount(fullBalance, cryptoCurrencyHandler());
sendAll = true;
_updateFiatAmount();
}
@@ -293,20 +321,20 @@ abstract class OutputBase with Store {
fiatAmount = '';
address = '';
note = '';
memo = null;
memo = "";
resetParsedAddress();
}
void resetParsedAddress() {
displayName = null;
extractedAddress = '';
parsedAddress = ParsedAddress(addresses: []);
}
@action
/// [setCryptoAmount] always takes in the canonical representation eg. Bitcoin and not Sats
void setCryptoAmount(String amount) {
if (amount.toUpperCase() != S.current.all) {
sendAll = false;
}
if (amount.toUpperCase() != S.current.all) sendAll = false;
cryptoAmount = amount;
_updateFiatAmount();
@@ -321,10 +349,15 @@ abstract class OutputBase with Store {
@action
void _updateFiatAmount() {
try {
var cryptoAmount_ =
sendAll ? cryptoFullBalance.replaceAll(",", ".") : cryptoAmount.replaceAll(',', '.');
var cryptoCurrency = cryptoCurrencyHandler() == CryptoCurrency.btcln
? CryptoCurrency.btc
: cryptoCurrencyHandler();
final fiat = calculateFiatAmount(
price: _fiatConversationStore.prices[cryptoCurrencyHandler()]!,
cryptoAmount:
sendAll ? cryptoFullBalance.replaceAll(",", ".") : cryptoAmount.replaceAll(',', '.'));
price: _fiatConversationStore.prices[cryptoCurrency]!, cryptoAmount: cryptoAmount_);
if (fiatAmount != fiat) {
fiatAmount = fiat;
}
@@ -336,15 +369,18 @@ abstract class OutputBase with Store {
@action
void _updateCryptoAmount() {
try {
var cryptoCurrency = cryptoCurrencyHandler() == CryptoCurrency.btcln
? CryptoCurrency.btc
: cryptoCurrencyHandler();
final decimals = min(20, cryptoCurrencyHandler().decimals);
final crypto = (double.parse(fiatAmount.replaceAll(',', '.')) /
_fiatConversationStore.prices[cryptoCurrencyHandler()]!)
_fiatConversationStore.prices[cryptoCurrency]!)
.toStringAsFixed(decimals);
if (cryptoAmount != crypto) {
cryptoAmount = crypto;
}
if (cryptoAmount != crypto) cryptoAmount = crypto;
} catch (e) {
printV(e);
cryptoAmount = '';
}
}
@@ -362,6 +398,9 @@ abstract class OutputBase with Store {
final domain = address;
final currency = cryptoCurrencyHandler();
parsedAddress = await getIt.get<AddressResolver>().resolve(context, domain, currency);
if(parsedAddress.name.isNotEmpty) {
displayName = parsedAddress.name;
}
extractedAddress = await extractAddressFromParsed(context, parsedAddress);
note = parsedAddress.description;
}
@@ -381,7 +420,7 @@ extension OutputCopyWith on Output {
}) {
final clone = Output(
_wallet,
_settingsStore,
_appStore,
_fiatConversationStore,
cryptoCurrencyHandler,
);
@@ -1,5 +1,6 @@
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/view_model/send/template_view_model.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
@@ -12,7 +13,6 @@ import 'package:cake_wallet/core/address_validator.dart';
import 'package:cake_wallet/core/amount_validator.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
part 'send_template_view_model.g.dart';
@@ -20,12 +20,12 @@ class SendTemplateViewModel = SendTemplateViewModelBase with _$SendTemplateViewM
abstract class SendTemplateViewModelBase with Store {
final WalletBase _wallet;
final SettingsStore _settingsStore;
final AppStore _appStore;
final SendTemplateStore _sendTemplateStore;
final FiatConversionStore _fiatConversationStore;
SendTemplateViewModelBase(
this._wallet, this._settingsStore, this._sendTemplateStore, this._fiatConversationStore)
this._wallet, this._appStore, this._sendTemplateStore, this._fiatConversationStore)
: recipients = ObservableList<TemplateViewModel>() {
addRecipient();
}
@@ -36,7 +36,7 @@ abstract class SendTemplateViewModelBase with Store {
void addRecipient() {
recipients.add(TemplateViewModel(
wallet: _wallet,
settingsStore: _settingsStore,
appStore: _appStore,
fiatConversationStore: _fiatConversationStore));
}
@@ -46,10 +46,8 @@ abstract class SendTemplateViewModelBase with Store {
}
AmountValidator get amountValidator => AmountValidator(
currency: walletTypeToCryptoCurrency(
_wallet.type,
chainId: _wallet.chainId,
),
currency: walletTypeToCryptoCurrency(_wallet.type, chainId: _wallet.chainId),
amountParsingProxy: _appStore.amountParsingProxy,
);
AddressValidator get addressValidator =>
@@ -67,10 +65,10 @@ abstract class SendTemplateViewModelBase with Store {
CryptoCurrency get cryptoCurrency => _wallet.currency;
@computed
String get fiatCurrency => _settingsStore.fiatCurrency.title;
String get fiatCurrency => _appStore.settingsStore.fiatCurrency.title;
@computed
int get fiatCurrencyDecimals => _settingsStore.fiatCurrency.decimals;
int get fiatCurrencyDecimals => _appStore.settingsStore.fiatCurrency.decimals;
@computed
ObservableList<Template> get templates => _sendTemplateStore.templates;
+423 -232
View File
@@ -2,8 +2,10 @@ import 'dart:async';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/address_validator.dart';
import 'package:cake_wallet/core/amount_parsing_proxy.dart';
import 'package:cake_wallet/core/amount_validator.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/core/open_crypto_pay/exceptions.dart';
import 'package:cake_wallet/core/open_crypto_pay/models.dart';
import 'package:cake_wallet/core/open_crypto_pay/open_cryptopay_service.dart';
import 'package:cake_wallet/core/validator.dart';
@@ -22,6 +24,7 @@ import 'package:cake_wallet/entities/wallet_contact.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/jupiter_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/near_Intents_exchange_provider.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/exchange/provider/swapsxyz_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/thorchain_exchange.provider.dart';
@@ -49,11 +52,14 @@ import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/erc20_token.dart';
import 'package:cw_core/exceptions.dart';
import 'package:cw_core/lnurl.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/transaction_priority.dart';
import 'package:cw_core/unspent_coin_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
@@ -71,11 +77,10 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@override
void onWalletChange(wallet) {
currencies = wallet.balance.keys.toList();
selectedCryptoCurrency = wallet.currency;
selectedCryptoCurrency =
coinTypeToSpendFrom == UnspentCoinType.lightning ? CryptoCurrency.btcln : wallet.currency;
hasMultipleTokens = isEVMWallet ||
wallet.type == WalletType.solana ||
wallet.type == WalletType.tron ||
wallet.type == WalletType.zano;
[WalletType.solana, WalletType.tron, WalletType.zano].contains(wallet.type);
for (final output in outputs) {
output.updateWallet(wallet);
@@ -91,7 +96,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
UnspentCoinsListViewModel unspentCoinsListViewModel;
SendViewModelBase(
AppStore appStore,
this._appStore,
this.sendTemplateViewModel,
this._fiatConversationStore,
this.balanceViewModel,
@@ -102,23 +107,22 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
this.feesViewModel, {
this.coinTypeToSpendFrom = UnspentCoinType.nonMweb,
}) : state = InitialExecutionState(),
currencies = appStore.wallet!.balance.keys.toList(),
selectedCryptoCurrency = appStore.wallet!.currency,
hasMultipleTokens = isEVMCompatibleChain(appStore.wallet!.type) ||
appStore.wallet!.type == WalletType.solana ||
appStore.wallet!.type == WalletType.tron ||
appStore.wallet!.type == WalletType.zano,
selectedChainId = appStore.wallet!.chainId,
currencies = _appStore.wallet!.balance.keys.toList(),
selectedCryptoCurrency = coinTypeToSpendFrom == UnspentCoinType.lightning
? CryptoCurrency.btcln
: _appStore.wallet!.currency,
hasMultipleTokens = isEVMCompatibleChain(_appStore.wallet!.type) ||
[WalletType.solana, WalletType.tron, WalletType.zano].contains(_appStore.wallet!.type),
selectedChainId = _appStore.wallet!.chainId,
outputs = ObservableList<Output>(),
_settingsStore = appStore.settingsStore,
fiatFromSettings = appStore.settingsStore.fiatCurrency,
super(appStore: appStore) {
outputs
.add(Output(wallet, _settingsStore, _fiatConversationStore, () => selectedCryptoCurrency));
fiatFromSettings = _appStore.settingsStore.fiatCurrency,
fiatCurrencies = FiatCurrency.all,
super(appStore: _appStore) {
outputs.add(Output(wallet, _appStore, _fiatConversationStore, () => selectedCryptoCurrency));
unspentCoinsListViewModel.initialSetup().then((_) {
unspentCoinsListViewModel.resetUnspentCoinsInfoSelections();
});
unspentCoinsListViewModel
.initialSetup()
.then((_) => unspentCoinsListViewModel.resetUnspentCoinsInfoSelections());
reaction((_) {
if (isEVMCompatibleChain(wallet.type)) {
@@ -135,9 +139,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
});
}
PendingTransaction? _pendingApprovalTx;
bool _isSwapsXYZCallDataTx = false;
// Store trade and provider references for post-commit updates (e.g., Jupiter trade ID update)
Trade? _currentTrade;
ExchangeProvider? _currentProvider;
@@ -154,24 +155,20 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
bool get isMwebEnabled => balanceViewModel.mwebEnabled;
bool get isMwebAvailable => wallet.currency == CryptoCurrency.ltc && balanceViewModel.mwebEnabled;
bool get isEVMWallet => isEVMCompatibleChain(walletType);
@action
void setShowAddressBookPopup(bool value) {
_settingsStore.showAddressBookPopupEnabled = value;
}
void setShowAddressBookPopup(bool value) => _settingsStore.showAddressBookPopupEnabled = value;
@action
void addOutput() {
outputs
.add(Output(wallet, _settingsStore, _fiatConversationStore, () => selectedCryptoCurrency));
}
void addOutput() =>
outputs.add(Output(wallet, _appStore, _fiatConversationStore, () => selectedCryptoCurrency));
@action
void removeOutput(Output output) {
if (isBatchSending) {
outputs.remove(output);
}
if (isBatchSending) outputs.remove(output);
}
@action
@@ -204,15 +201,28 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@computed
String get pendingTransactionFiatAmount {
if (pendingTransaction == null) {
if (pendingTransaction == null) return '0.00';
try {
var currency = _fiatConversationStore.prices.keys
.firstWhere((k) => k.titleAndTagEqual(selectedCryptoCurrency));
if (currency == CryptoCurrency.btcln) currency = CryptoCurrency.btc;
final fiat = calculateFiatAmount(
price: _fiatConversationStore.prices[currency],
cryptoAmount: pendingTransaction!.amountFormatted);
return fiat;
} catch (_) {
return '0.00';
}
}
String calculateTransactionFiatAmount(String amountValue) {
try {
final fiat = calculateFiatAmount(
price: _fiatConversationStore.prices[_fiatConversationStore.prices.keys
.firstWhere((k) => k.titleAndTagEqual(selectedCryptoCurrency))],
cryptoAmount: pendingTransaction!.amountFormatted);
cryptoAmount: amountValue);
return fiat;
} catch (_) {
return '0.00';
@@ -246,6 +256,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
case WalletType.bsc:
case WalletType.tron:
case WalletType.solana:
case WalletType.bitcoin:
return wallet.currency;
default:
return selectedCryptoCurrency;
@@ -254,10 +265,14 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
FiatCurrency get fiat => _settingsStore.fiatCurrency;
CryptoCurrency get currency => wallet.currency;
CryptoCurrency get currency =>
selectedCryptoCurrency == CryptoCurrency.btcln ? CryptoCurrency.btcln : wallet.currency;
String get currencySymbol => _appStore.amountParsingProxy.getCryptoSymbol(currency);
Validator<String> amountValidator(Output output) => AmountValidator(
currency: wallet.currency,
amountParsingProxy: _appStore.amountParsingProxy,
minValue: isSendToSilentPayments(output)
?
// TODO: get from server
@@ -286,12 +301,14 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
coinTypeToSpendFrom == UnspentCoinType.nonMweb) {
return balanceViewModel.balances.values.first.availableBalance;
}
// Handle case where balance might not be available yet (e.g., during chain switch)
final balanceForCurrency = wallet.balance[selectedCryptoCurrency];
if (balanceForCurrency == null) {
return wallet.formatCryptoAmount('0');
return _appStore.amountParsingProxy.getDisplayCryptoString(0, selectedCryptoCurrency);
}
return balanceForCurrency.formattedFullAvailableBalance;
return _appStore.amountParsingProxy.getDisplayCryptoStringFromBigInt(
wallet.balance[selectedCryptoCurrency]!.fullAvailableBalance, selectedCryptoCurrency);
}
@action
@@ -318,14 +335,19 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
// only for electrum, monero, wownero, decred wallets atm:
switch (wallet.type) {
case WalletType.bitcoin:
if (coinTypeToSpendFrom == UnspentCoinType.lightning) return balance;
return _appStore.amountParsingProxy.getDisplayCryptoString(
await unspentCoinsListViewModel.getSendingBalance(coinTypeToSpendFrom),
walletTypeToCryptoCurrency(walletType));
case WalletType.litecoin:
case WalletType.bitcoinCash:
case WalletType.dogecoin:
case WalletType.monero:
case WalletType.wownero:
case WalletType.decred:
return wallet.formatCryptoAmount(
(await unspentCoinsListViewModel.getSendingBalance(coinTypeToSpendFrom)).toString());
final sendingBalance =
await unspentCoinsListViewModel.getSendingBalance(coinTypeToSpendFrom);
return walletTypeToCryptoCurrency(walletType).formatAmount(BigInt.from(sendingBalance));
default:
return balance;
}
@@ -336,11 +358,11 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@computed
String get pendingTransactionFiatAmountFormatted =>
isFiatDisabled ? '' : pendingTransactionFiatAmount + ' ' + fiat.title;
isFiatDisabled ? '' : '$pendingTransactionFiatAmount ${fiat.title}';
@computed
String get pendingTransactionFeeFiatAmountFormatted =>
isFiatDisabled ? '' : pendingTransactionFeeFiatAmount + ' ' + fiat.title;
isFiatDisabled ? '' : '$pendingTransactionFeeFiatAmount ${fiat.title}';
@computed
bool get isReadyForSend =>
@@ -363,7 +385,8 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
.toList();
@computed
bool get hasCoinControl => [
bool get hasCoinControl =>
[
WalletType.bitcoin,
WalletType.litecoin,
WalletType.monero,
@@ -371,7 +394,11 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
WalletType.decred,
WalletType.bitcoinCash,
WalletType.dogecoin
].contains(wallet.type);
].contains(wallet.type) &&
coinTypeToSpendFrom != UnspentCoinType.lightning;
@computed
bool get hasFees => feesViewModel.hasFees && coinTypeToSpendFrom != UnspentCoinType.lightning;
@computed
bool get isElectrumWallet => [
@@ -384,10 +411,11 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@observable
CryptoCurrency selectedCryptoCurrency;
List<CryptoCurrency> currencies;
@computed
String get selectedCryptoCurrencySymbol =>
amountParsingProxy.getCryptoSymbol(selectedCryptoCurrency);
bool get hasYat => outputs
.any((out) => out.isParsedAddress && out.parsedAddress.parseFrom == ParseFrom.yatRecord);
List<CryptoCurrency> currencies;
WalletType get walletType => wallet.type;
@@ -396,7 +424,14 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@computed
FiatCurrency get fiatCurrency => _settingsStore.fiatCurrency;
final SettingsStore _settingsStore;
set fiatCurrency(FiatCurrency value) {
_settingsStore.fiatCurrency = value;
}
List<FiatCurrency> fiatCurrencies;
final AppStore _appStore;
SettingsStore get _settingsStore => _appStore.settingsStore;
final SendTemplateViewModel sendTemplateViewModel;
final BalanceViewModel balanceViewModel;
final ContactListViewModel contactListViewModel;
@@ -405,6 +440,16 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
final FiatConversionStore _fiatConversationStore;
final Box<TransactionDescription> transactionDescriptionBox;
@computed
AmountParsingProxy get amountParsingProxy => _appStore.amountParsingProxy;
@computed
bool get hasMultiRecipient =>
sendTemplateViewModel.hasMultiRecipient && coinTypeToSpendFrom != UnspentCoinType.lightning;
@computed
String get languageCode => _appStore.settingsStore.languageCode;
@observable
bool hasMultipleTokens;
@@ -422,19 +467,12 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
.toList();
@action
bool checkIfAddressIsAContact(String address) {
final contactList = contactsToShow.where((element) => element.address == address).toList();
return contactList.isNotEmpty;
}
bool checkIfAddressIsAContact(String address) =>
contactsToShow.where((element) => element.address == address).toList().isNotEmpty;
@action
bool checkIfWalletIsAnInternalWallet(String address) {
final walletContactList =
walletContactsToShow.where((element) => element.address == address).toList();
return walletContactList.isNotEmpty;
}
bool checkIfWalletIsAnInternalWallet(String address) =>
walletContactsToShow.where((element) => element.address == address).toList().isNotEmpty;
@computed
bool get shouldDisplayTOTP2FAForContact => _settingsStore.shouldRequireTOTP2FAForSendsToContact;
@@ -512,11 +550,31 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
outputs.first.note = ocpRequest!.receiverName;
return createTransaction();
} on OpenCryptoPayNotSupportedException catch (e) {
printV(e.message);
if (walletType == WalletType.bitcoin) {
state = InitialExecutionState();
} else {
state = FailureState(translateErrorMessage(e, walletType, currency));
}
} catch (e) {
printV(e);
state = FailureState(translateErrorMessage(e, walletType, currency));
return null;
}
return null;
}
static bool isLightningInvoice(String txt) {
return RegExp(AddressValidator.bolt11InvoiceMatcher, caseSensitive: false).hasMatch(txt);
}
static bool isNonZeroAmountLightningInvoice(String txt) {
return RegExp(AddressValidator.bolt11InvoiceMatcher, caseSensitive: false).hasMatch(txt) &&
!isBolt11ZeroInvoice(txt);
}
static bool isLnurlInvoice(String txt) {
return RegExp(AddressValidator.lnurlMatcher, caseSensitive: false).hasMatch(txt);
}
Timer? _ledgerTxStateTimer;
@@ -525,130 +583,200 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
Future<PendingTransaction?> createTransaction({ExchangeProvider? provider, Trade? trade}) async {
_currentTrade = trade;
_currentProvider = provider;
pendingTransaction = null;
try {
if (!(state is IsExecutingState)) state = IsExecutingState();
if (wallet.isHardwareWallet) {
state = IsAwaitingDeviceResponseState();
if (walletType == WalletType.monero)
if (walletType == WalletType.monero) {
_ledgerTxStateTimer = Timer.periodic(Duration(seconds: 1), (timer) {
if (monero!.getLastLedgerCommand() == "INS_CLSAG") {
timer.cancel();
state = IsDeviceSigningResponseState();
}
});
}
}
// Swaps.xyz (EVM) path
if (isEVMWallet && trade != null && provider is SwapsXyzExchangeProvider) {
final routerTo = trade.inputAddress;
final routerData = trade.routerData;
final routerValueWei =
BigInt.tryParse((trade.routerValue ?? '0').toString()) ?? BigInt.zero;
if (routerTo?.isNotEmpty == true && routerData?.isNotEmpty == true) {
// detect prepared ERC-20 transfer(...) (alt-vm deposit pattern)
String _selector(String s) =>
(s.startsWith('0x') && s.length >= 10) ? s.substring(0, 10) : '';
const _transferSig = '0xa9059cbb';
final _sel = _selector(routerData!);
final _isPreparedTransfer = _sel == _transferSig &&
(trade.sourceTokenAddress ?? '').toLowerCase() == (routerTo ?? '').toLowerCase();
_pendingApprovalTx = null;
// Optionally prebuild approval (SKIP for prepared transfer)
final tokenContract = trade.sourceTokenAddress ?? '';
final requiredAmount = BigInt.tryParse(
(trade.sourceTokenAmountRaw ?? '0').replaceAll('n', ''),
) ??
if (routerData != null && routerData != '0x') {
final tokenContract = (trade.sourceTokenAddress ?? '').toLowerCase();
final priority = _settingsStore.getPriority(
walletType, chainId: selectedChainId);
final routerValueWei = BigInt.tryParse(trade.routerValue ?? '0') ??
BigInt.zero;
// Only do approval when NOT a prepared transfer, and only if the API hinted we might need it
final requiresTokenApproval =
(trade.requiresTokenApproval ?? false) && !_isPreparedTransfer;
if (routerTo == null || routerTo.isEmpty) {
state = FailureState('Invalid router address');
return null;
}
if (requiresTokenApproval && tokenContract.isNotEmpty && requiredAmount > BigInt.zero) {
if (isEVMWallet) {
final priority = _settingsStore.getPriority(walletType, chainId: selectedChainId);
_pendingApprovalTx = await buildApprovalIfNeeded(
spender: routerTo!,
tokenContract: tokenContract,
requiredAmount: requiredAmount,
sourceTokenDecimals: trade.sourceTokenDecimals,
try {
final selector = _decodeMethodSelector(routerData);
const transferSig = '0xa9059cbb';
const swapAndExecuteSig = '0x9be111d1';
// Direct Transfer (Simple routing, no approval needed)
if (selector == transferSig) {
pendingTransaction = await evm!.createRawCallDataTransaction(
wallet,
routerTo,
routerData,
BigInt.zero,
priority,
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
? _settingsStore.useBlinkProtection
: false,
);
state = ExecutedSuccessfullyState();
return pendingTransaction;
}
// Build the callData tx
// Smart Swap (Requires Approval)
if (selector == swapAndExecuteSig) {
final requiredAmount = BigInt.tryParse(
(trade.sourceTokenAmountRaw ?? '0').replaceAll('n', '')) ??
BigInt.zero;
final needsApproval = tokenContract.isNotEmpty &&
requiredAmount > BigInt.zero
? await evm!.isApprovalRequired(
wallet, tokenContract, routerTo, requiredAmount)
: false;
printV(
'[Swaps.xyz sending flow] Approval required: $needsApproval for token ${trade
.from?.title} ${trade.from?.tag ??
''} with amount $requiredAmount');
if (needsApproval) {
// USDT Approval Flow (Special Case). We must reset allowance to 0 first.
final isUSDTMainnet = selectedChainId == 1 &&
tokenContract.toLowerCase() ==
'0xdac17f958d2ee523a2206206994597c13d831ec7';
if (isUSDTMainnet) {
final currentAllowance = await evm!.getAllowance(
wallet, tokenContract, routerTo);
if (currentAllowance != null &&
currentAllowance > BigInt.zero) {
printV(
'[Swaps.xyz sending flow] currentAllowance USDT: $currentAllowance. Resetting to 0 before setting new allowance.');
final resetTx = await buildApprovalNeeded(
spender: routerTo,
tokenContract: tokenContract,
requiredAmount: BigInt.zero,
// Approve 0
sourceTokenDecimals: trade.sourceTokenDecimals,
priority: priority
);
if (resetTx != null) {
await resetTx.commit();
final resetConfirmed = await _waitForApprovalUpdate(
tokenContract: tokenContract,
spender: routerTo,
requiredAmount: BigInt.zero, // Wait until it equals 0
waitForExactMatch: true,
);
if (!resetConfirmed) {
state = FailureState(
'Failed to reset USDT allowance. Please try again.');
return null;
}
printV(
'[Swaps.xyz sending flow] USDT allowance reset to 0 confirmed on-chain.');
}
}
}
// Standard Approval Flow
final approvalTx = await buildApprovalNeeded(
spender: routerTo,
tokenContract: tokenContract,
requiredAmount: requiredAmount,
sourceTokenDecimals: trade.sourceTokenDecimals,
priority: priority
);
if (approvalTx == null) {
state = FailureState('Failed to build approval transaction');
return null;
}
pendingTransaction = null;
try {
printV(
'[Swaps.xyz sending flow] Submitting approval transaction for token ${trade
.from?.title} ${trade.from?.tag ?? ''} ');
await approvalTx.commit();
// Wait for the approval to be mined on-chain
final isApproved = await _waitForApprovalUpdate(
tokenContract: tokenContract,
spender: routerTo,
requiredAmount: requiredAmount,
);
if (!isApproved) {
state = FailureState(
'Approval transaction failed or timed out on-chain. Try again.');
return null;
}
printV(
'[Swaps.xyz sending flow] Approval transaction confirmed on-chain. Proceeding with swap execution.');
} catch (e, s) {
printV(
'[Swaps.xyz sending flow] Approval transaction error: $e\n$s');
state = FailureState(
translateErrorMessage(e, wallet.type, wallet.currency));
return null;
}
}
// Construct Final Swap Transaction
printV('[Swaps.xyz sending flow] Building swap transaction');
pendingTransaction = await evm!.createRawCallDataTransaction(
wallet,
routerTo,
routerData,
routerValueWei,
priority,
sourceTokenAddress: tokenContract,
sourceTokenAmount: requiredAmount,
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
? _settingsStore.useBlinkProtection
: false,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction; // do NOT fall back to regular flow
return pendingTransaction;
}
}
// No approval needed (or prepared transfer): send exactly what backend prepared
if (isEVMWallet) {
final priority = _settingsStore.getPriority(walletType, chainId: selectedChainId);
pendingTransaction = await evm!.createRawCallDataTransaction(
wallet,
routerTo!,
routerData,
routerValueWei,
priority,
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
? _settingsStore.useBlinkProtection
: false,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction;
}
}
}
// Jupiter (Solana) swap path
if (walletType == WalletType.solana && trade != null && provider is JupiterExchangeProvider) {
final swapTransactionBase64 = trade.routerData;
final requestId = trade.routerValue;
if (swapTransactionBase64?.isNotEmpty == true &&
requestId?.isNotEmpty == true &&
solana != null) {
try {
final actualFee = trade.fee ?? 0.0005;
// Fallback to estimate if not available
final fee = actualFee > 0 ? actualFee : 0.0005;
final amount = double.tryParse(trade.amount) ?? 0.0;
pendingTransaction = await solana!.signAndPrepareJupiterSwapTransaction(
wallet,
swapTransactionBase64!,
requestId!,
trade.payoutAddress ?? '',
amount,
fee,
);
state = ExecutedSuccessfullyState();
return pendingTransaction;
state = FailureState('Unsupported Swaps.xyz transaction type');
return null;
} catch (e, s) {
printV('Jupiter swap error: $e\n$s');
throw Exception('Failed to process Jupiter swap: $e');
printV('Swaps.xyz transaction error: $e\n$s');
state = FailureState(
'Failed to create Swaps.xyz transaction - ${translateErrorMessage(
e, wallet.type, wallet.currency)}');
return null;
}
}
}
// END Swaps.xyz path
// Jupiter (Solana) swap path
if (walletType == WalletType.solana && trade != null && provider is JupiterExchangeProvider) {
@@ -686,6 +814,17 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
pendingTransaction = await wallet.createTransaction(_credentials(provider));
if (trade?.isSendAll == true) {
if (provider is NearIntentsExchangeProvider) {
final txAmountDouble = double.tryParse(pendingTransaction?.amountFormatted ?? '0') ?? 0.0;
final tradeAmountDouble = double.tryParse(trade?.amount ?? '0') ?? 0.0;
if (txAmountDouble != tradeAmountDouble) {
throw Exception(
'Transaction amount $txAmountDouble does not match expected trade amount $tradeAmountDouble');
}
}
}
if (provider is ThorChainExchangeProvider) {
final outputCount = pendingTransaction?.outputCount ?? 0;
if (outputCount > 10) {
@@ -770,18 +909,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
);
}
Future<void> _commitApprovalTransaction() async {
if (_pendingApprovalTx != null) {
await _pendingApprovalTx!.commit();
_pendingApprovalTx = null;
// Small pause to ensure allowance is indexed
await Future.delayed(const Duration(milliseconds: 300));
}
await pendingTransaction!.commit();
_isSwapsXYZCallDataTx = false;
}
Future<void> _commitUR(BuildContext context) async {
final urstr = await pendingTransaction!.commitUR();
final result = await Navigator.of(context).pushNamed(Routes.urqrAnimatedPage, arguments: urstr);
@@ -801,9 +928,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
if (ocpRequest != null) {
await _handleOcpRequest();
} else if (_isSwapsXYZCallDataTx) {
// Swaps.xyz approval (if any), then commit the prebuilt router tx
await _commitApprovalTransaction();
} else if (pendingTransaction!.shouldCommitUR()) {
await _commitUR(context);
} else {
@@ -883,7 +1007,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
}
// Immediate transaction update for EVM chains, Tron, and Nano
if (isEVMWallet || [WalletType.tron, WalletType.nano].contains(walletType)) {
if (isEVMWallet || [WalletType.bitcoin, WalletType.solana, WalletType.tron, WalletType.nano].contains(walletType)) {
Future.delayed(Duration(seconds: 4), () async {
try {
await Future.wait([
@@ -926,6 +1050,9 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
}
}
@action
Future<void> updateWalletBalance() async => await wallet.updateBalance();
Future<void> _addTransactionDescription() async {
String address = outputs.fold('', (acc, value) {
return value.isParsedAddress
@@ -965,12 +1092,14 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (priority == null &&
wallet.type != WalletType.nano &&
wallet.type != WalletType.banano &&
wallet.type != WalletType.solana &&
wallet.type != WalletType.tron &&
wallet.type != WalletType.arbitrum &&
wallet.type != WalletType.zcash) {
![
WalletType.nano,
WalletType.banano,
WalletType.solana,
WalletType.tron,
WalletType.arbitrum,
WalletType.zcash,
].contains(wallet.type)) {
throw Exception('Priority is null for wallet type: ${wallet.type}');
}
@@ -1045,7 +1174,10 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
void onClose() => _settingsStore.fiatCurrency = fiatFromSettings;
@action
void setFiatCurrency(FiatCurrency fiat) => _settingsStore.fiatCurrency = fiat;
FiatCurrency setFiatCurrency(FiatCurrency fiat) {
_settingsStore.fiatCurrency = fiat;
return fiat;
}
@action
void setSelectedCryptoCurrency(String cryptoCurrency) {
@@ -1057,34 +1189,124 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
}
}
@computed
bool get hasMemos => [WalletType.zcash].contains(wallet.type);
final Map<WalletType, int> _maxMemoLengths = {
WalletType.zcash: 512,
};
@computed
int get maxMemoLength => _maxMemoLengths[wallet.type] ?? 9999999;
ContactRecord? newContactAddress() {
final Set<String> contactAddresses =
Set.from(contactListViewModel.contacts.map((contact) => contact.address))
..addAll(contactListViewModel.walletContacts.map((contact) => contact.address));
for (var output in outputs) {
String address;
if (output.isParsedAddress) {
address = output.parsedAddress.addresses.first;
} else {
address = output.address;
}
for (final output in outputs) {
final address =
output.isParsedAddress ? output.parsedAddress.addresses.first : output.address;
if (address.isNotEmpty &&
!contactAddresses.contains(address) &&
selectedCryptoCurrency.raw != -1) {
return ContactRecord(
contactListViewModel.contactSource,
Contact(
name: '',
address: address,
type: selectedCryptoCurrency,
));
contactListViewModel.contactSource,
Contact(
name: '',
address: address,
type: selectedCryptoCurrency,
),
);
}
}
return null;
}
// Helper functions for EVM transaction monitoring and approval flow
// Polls the token contract directly to see if allowance is updated.
Future<bool> _waitForApprovalUpdate({
required String tokenContract,
required String spender,
required BigInt requiredAmount,
bool waitForExactMatch = false,
}) async {
if (!isEVMWallet || evm == null) return false;
int attempts = 0;
const int maxAttempts = 30; // ~60 seconds
printV('[Swaps.xyz sending flow] Starting allowance check. Target: $requiredAmount (Exact match: $waitForExactMatch)');
while (attempts < maxAttempts) {
try {
final currentAllowance = await evm!.getAllowance(wallet, tokenContract, spender);
if (currentAllowance != null) {
printV('[Swaps.xyz sending flow] Current Allowance: $currentAllowance / Target: $requiredAmount');
if (waitForExactMatch) {
// For Reset (Target 0): We need it to be exactly 0 (or less, though it can't be negative)
if (currentAllowance <= requiredAmount) {
printV('[Swaps.xyz sending flow] Allowance reset verified!');
return true;
}
} else {
// For Approval: We need it to be at least the required amount
if (currentAllowance >= requiredAmount) {
printV('[Swaps.xyz sending flow] Allowance verified!');
return true;
}
}
}
} catch (e) {
printV('[Swaps.xyz sending flow] Allowance check error: $e');
}
await Future.delayed(const Duration(seconds: 1));
attempts++;
}
printV('[Swaps.xyz sending flow] Allowance check timed out.');
return false;
}
// Builds a token approval transaction
Future<PendingTransaction?> buildApprovalNeeded({
required String spender,
required String tokenContract,
required BigInt requiredAmount,
required TransactionPriority? priority,
int? sourceTokenDecimals,
}) async {
final erc20Token = wallet.balance.keys.whereType<Erc20Token>().firstWhere(
(t) => t.contractAddress.toLowerCase() == tokenContract.toLowerCase(),
orElse: () => Erc20Token(
name: '',
symbol: '',
contractAddress: tokenContract,
decimal: sourceTokenDecimals ?? 18,
enabled: true,
),
);
return await evm!.createTokenApproval(
wallet,
requiredAmount,
spender,
erc20Token,
priority,
useBlinkProtection:
canSupportBlinkProtection(selectedChainId) ? _settingsStore.useBlinkProtection : false,
);
}
// End EVM helper functions
String translateErrorMessage(
Object error,
WalletType walletType,
@@ -1230,6 +1452,9 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
if (error is TransactionNoDustException) {
return S.current.tx_no_dust_exception;
}
if (error is TransactionCommitFailedBIP68Final) {
return S.current.trying_to_spend_locked_funds;
}
if (error is TransactionCommitFailed) {
if (error.errorMessage != null && error.errorMessage!.contains("no peers replied")) {
return S.current.tx_commit_failed_no_peers;
@@ -1261,9 +1486,27 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
return S.current.tx_invalid_input;
}
if(wallet.type == WalletType.bitcoin) {
final lnError = getLightningErrorMessage(error);
if(lnError != null) return lnError;
}
return errorMessage;
}
String? getLightningErrorMessage(Object error) {
// TODO add more patterns
Map<String, String> errorPatterns = {
"insufficient funds": S.current.insufficient_funds_for_tx
};
for(final pattern in errorPatterns.keys) {
if(error.toString().contains(pattern)) return errorPatterns[pattern]!;
}
return null;
}
bool _hasTaprootInput(PendingTransaction? pendingTransaction) {
if (walletType == WalletType.bitcoin && pendingTransaction != null) {
return bitcoin!.hasTaprootInput(pendingTransaction);
@@ -1272,61 +1515,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
return false;
}
Future<PendingTransaction?> buildApprovalIfNeeded({
required String spender,
required String tokenContract,
required BigInt requiredAmount,
int? sourceTokenDecimals,
}) async {
// Only EVM chains support ERC20 approvals
if (!isEVMWallet) return null;
const zero = '0x0000000000000000000000000000000000000000';
const evmNative = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
final tokenLc = tokenContract.toLowerCase();
if (tokenLc == zero || tokenLc == evmNative.toLowerCase()) return null;
if (requiredAmount <= BigInt.zero) return null;
bool needsApproval = false;
if (isEVMWallet) {
needsApproval = await evm!.isApprovalRequired(
wallet,
tokenContract,
spender,
requiredAmount,
);
}
if (!needsApproval) return null;
final erc20Token = wallet.balance.keys.whereType<Erc20Token>().firstWhere(
(t) => t.contractAddress.toLowerCase() == tokenLc,
orElse: () => Erc20Token(
name: '',
symbol: '',
contractAddress: tokenContract,
decimal: sourceTokenDecimals ?? 18,
enabled: true,
),
);
if (isEVMWallet) {
final priority = _settingsStore.getPriority(walletType, chainId: selectedChainId);
return await evm!.createTokenApproval(
wallet,
requiredAmount,
spender,
erc20Token,
priority,
useBlinkProtection:
canSupportBlinkProtection(selectedChainId) ? _settingsStore.useBlinkProtection : false,
);
}
return null;
}
@computed
bool get usePayjoin => _settingsStore.usePayjoin;
@@ -1344,4 +1532,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
selectedCryptoCurrency = token;
}
}
String _decodeMethodSelector(String s) =>
(s.startsWith('0x') && s.length >= 10) ? s.substring(0, 10) : '';
}
+6 -6
View File
@@ -1,10 +1,10 @@
import 'package:cake_wallet/entities/template.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/view_model/send/output.dart';
import 'package:mobx/mobx.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
part 'template_view_model.g.dart';
@@ -12,19 +12,19 @@ class TemplateViewModel = TemplateViewModelBase with _$TemplateViewModel;
abstract class TemplateViewModelBase with Store {
final WalletBase _wallet;
final SettingsStore _settingsStore;
final AppStore _appStore;
final FiatConversionStore _fiatConversationStore;
TemplateViewModelBase({
required WalletBase wallet,
required SettingsStore settingsStore,
required AppStore appStore,
required FiatConversionStore fiatConversationStore,
}) : _wallet = wallet,
_settingsStore = settingsStore,
_appStore = appStore,
_fiatConversationStore = fiatConversationStore,
_currency = wallet.currency,
output = Output(wallet, settingsStore, fiatConversationStore, () => wallet.currency) {
output = Output(_wallet, _settingsStore, _fiatConversationStore, () => _currency);
output = Output(wallet, appStore, fiatConversationStore, () => wallet.currency) {
output = Output(_wallet, _appStore, _fiatConversationStore, () => _currency);
}
@observable
@@ -1,10 +1,13 @@
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/entities/bitcoin_amount_display_mode.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/entities/sync_status_display_mode.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/themes/core/material_base_theme.dart';
import 'package:cake_wallet/themes/theme_classes/black_theme.dart';
import 'package:cake_wallet/themes/utils/theme_list.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/themes/core/theme_store.dart';
@@ -15,9 +18,10 @@ part 'display_settings_view_model.g.dart';
class DisplaySettingsViewModel = DisplaySettingsViewModelBase with _$DisplaySettingsViewModel;
abstract class DisplaySettingsViewModelBase with Store {
DisplaySettingsViewModelBase(this._settingsStore, this._themeStore);
DisplaySettingsViewModelBase(this._appStore, this._themeStore);
final SettingsStore _settingsStore;
final AppStore _appStore;
SettingsStore get _settingsStore => _appStore.settingsStore;
final ThemeStore _themeStore;
@computed
@@ -35,6 +39,9 @@ abstract class DisplaySettingsViewModelBase with Store {
@computed
bool get shouldShowMarketPlaceInDashboard => _settingsStore.shouldShowMarketPlaceInDashboard;
@computed
BitcoinAmountDisplayMode get displayAmountsInSatoshi => _settingsStore.displayAmountsInSatoshi;
@computed
MaterialThemeBase get currentTheme => _themeStore.currentTheme;
@@ -106,6 +113,15 @@ abstract class DisplaySettingsViewModelBase with Store {
@action
void setBalanceDisplayMode(BalanceDisplayMode value) => _settingsStore.balanceDisplayMode = value;
@computed
bool get showDisplayAmountsInSatoshiSetting => _appStore.wallet?.type == WalletType.bitcoin;
@computed
bool get showZcashCardSetting => _appStore.wallet?.type == WalletType.zcash;
@action
void setDisplayAmountsInSatoshi(BitcoinAmountDisplayMode value) => _settingsStore.displayAmountsInSatoshi = value;
@action
void setShowZcashCard(bool value) => _settingsStore.showZcashMissingFundsCard = value;
@@ -1,11 +1,13 @@
import 'dart:io';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/priority_for_wallet_type.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/package_info.dart';
import 'package:cake_wallet/view_model/send/send_view_model.dart';
import 'package:collection/collection.dart';
import 'package:cw_core/balance.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/transaction_priority.dart';
@@ -138,4 +140,20 @@ abstract class OtherSettingsViewModelBase with Store {
}
return null;
}
Future<File?> getLightningLog() async {
final path = await pathForWalletDir(name: _wallet.name, type: walletType);
final logFile = File("$path/lightning.log");
if (await logFile.exists()) return logFile;
return null;
}
Future<File?> getPayjoinLog() async {
final path = await pathForWalletDir(name: _wallet.name, type: walletType);
final logFile = File("$path/payjoin.log");
if (await logFile.exists()) return logFile;
return null;
}
}
@@ -48,6 +48,18 @@ abstract class PrivacySettingsViewModelBase with Store {
WalletType.decred
].contains(_wallet.type);
@computed
bool get hasCoinControl =>
[
WalletType.bitcoin,
WalletType.litecoin,
WalletType.monero,
WalletType.wownero,
WalletType.decred,
WalletType.bitcoinCash,
WalletType.dogecoin
].contains(_wallet.type);
bool get isMoneroWallet => _wallet.type == WalletType.monero;
@computed
@@ -122,6 +134,9 @@ abstract class PrivacySettingsViewModelBase with Store {
@computed
bool get usePayjoin => _settingsStore.usePayjoin;
@computed
bool get useLightning => _wallet.type == WalletType.bitcoin && bitcoin!.useLightning(_wallet);
bool get canUseEtherscan => _wallet.chainId == 1;
bool get canUsePolygonScan => _wallet.chainId == 137;
@@ -138,6 +153,8 @@ abstract class PrivacySettingsViewModelBase with Store {
bool get canUsePayjoin => _wallet.type == WalletType.bitcoin && DeviceInfo.instance.isMobile;
bool get canUseLightning => _wallet.type == WalletType.bitcoin;
@action
void setShouldSaveRecipientAddress(bool value) =>
_settingsStore.shouldSaveRecipientAddress = value;
@@ -232,4 +249,7 @@ abstract class PrivacySettingsViewModelBase with Store {
_settingsStore.usePayjoin = value;
bitcoin!.updatePayjoinState(_wallet, value);
}
@action
void setUseLightning(bool value) => bitcoin!.updateUseLightning(_wallet, value);
}
@@ -31,7 +31,7 @@ abstract class SilentPaymentsSettingsViewModelBase with Store {
@action
void setSilentPaymentsAlwaysScan(bool value) {
bitcoin!.setIsAlwaysScanningSP(_wallet, value);
if (value) bitcoin!.setScanningActive(_wallet, true);
bitcoin!.setScanningActive(_wallet, value);
}
Future<String> getAbbreviatedLogs() async {
+2 -1
View File
@@ -29,7 +29,6 @@ import 'package:cake_wallet/utils/show_bar.dart';
import 'package:collection/collection.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
@@ -123,6 +122,8 @@ abstract class TradeDetailsViewModelBase with Store {
return 'https://scan.chainflip.io/channels/${trade.id}';
case ExchangeProviderDescription.xoSwap:
return 'https://orders.xoswap.com/${trade.id}';
case ExchangeProviderDescription.swapsXyz:
return 'https://scan.swaps.xyz/transactions/${trade.id}';
case ExchangeProviderDescription.jupiter:
return 'https://solscan.io/tx/${trade.txId}';
case ExchangeProviderDescription.nearIntents:
@@ -1,6 +1,8 @@
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/core/address_validator.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/transaction_info.dart';
@@ -17,7 +19,6 @@ import 'package:cake_wallet/src/screens/transaction_details/standart_list_item.d
import 'package:cake_wallet/src/screens/transaction_details/textfield_list_item.dart';
import 'package:cake_wallet/src/screens/transaction_details/transaction_details_list_item.dart';
import 'package:cake_wallet/src/screens/transaction_details/transaction_expandable_list_item.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/date_formatter.dart';
import 'package:cake_wallet/view_model/send/send_view_model.dart';
import 'package:collection/collection.dart';
@@ -35,18 +36,19 @@ class TransactionDetailsViewModel = TransactionDetailsViewModelBase
with _$TransactionDetailsViewModel;
abstract class TransactionDetailsViewModelBase with Store {
TransactionDetailsViewModelBase(
{required this.transactionInfo,
required this.transactionDescriptionBox,
required this.wallet,
required this.settingsStore,
required this.sendViewModel,
this.canReplaceByFee = false})
: items = [],
TransactionDetailsViewModelBase({
required this.transactionInfo,
required this.transactionDescriptionBox,
required this.wallet,
required AppStore appStore,
required this.sendViewModel,
this.canReplaceByFee = false,
}) : items = [],
RBFListItems = [],
newFee = 0,
isRecipientAddressShown = false,
showRecipientAddress = settingsStore.shouldSaveRecipientAddress {
_appStore = appStore,
showRecipientAddress = appStore.settingsStore.shouldSaveRecipientAddress {
final dateFormat = DateFormatter.withCurrentLocal();
final tx = transactionInfo;
@@ -56,13 +58,13 @@ abstract class TransactionDetailsViewModelBase with Store {
_addMoneroListItems(tx, dateFormat);
break;
case WalletType.bitcoin:
_addElectrumListItems(tx, dateFormat);
_addElectrumListItems(tx, dateFormat, CryptoCurrency.btc);
if (!canReplaceByFee) _checkForRBF(tx);
break;
case WalletType.litecoin:
_addLitecoinListItems(tx, dateFormat);
case WalletType.bitcoinCash:
_addElectrumListItems(tx, dateFormat);
_addElectrumListItems(tx, dateFormat, CryptoCurrency.bch);
break;
case WalletType.haven:
_addHavenListItems(tx, dateFormat);
@@ -123,19 +125,24 @@ abstract class TransactionDetailsViewModelBase with Store {
final type = wallet.type;
items.add(
BlockExplorerListItem(
title: S.current.view_in_block_explorer,
value: _explorerDescription(type, wallet.chainId),
onTap: () async {
try {
final uri = Uri.parse(_explorerUrl(type, tx.txHash, wallet.chainId));
if (await canLaunchUrl(uri)) await launchUrl(uri, mode: LaunchMode.externalApplication);
} catch (e) {}
},
key: ValueKey('block_explorer_list_item_${type.name}_wallet_type_key'),
),
);
final isLightning = tx.additionalInfo["isLightning"] as bool? ?? false;
if (!isLightning) {
items.add(
BlockExplorerListItem(
title: S.current.view_in_block_explorer,
value: _explorerDescription(type, wallet.chainId),
onTap: () async {
try {
final uri = Uri.parse(_explorerUrl(type, tx.txHash, wallet.chainId));
if (await canLaunchUrl(uri)) await launchUrl(
uri, mode: LaunchMode.externalApplication);
} catch (e) {}
},
key: ValueKey('block_explorer_list_item_${type.name}_wallet_type_key'),
),
);
}
items.add(
TextFieldListItem(
@@ -157,9 +164,9 @@ abstract class TransactionDetailsViewModelBase with Store {
final TransactionInfo transactionInfo;
final Box<TransactionDescription> transactionDescriptionBox;
final SettingsStore settingsStore;
final WalletBase wallet;
final SendViewModel sendViewModel;
final AppStore _appStore;
final List<TransactionDetailsListItem> items;
final List<TransactionDetailsListItem> RBFListItems;
@@ -347,7 +354,18 @@ abstract class TransactionDetailsViewModelBase with Store {
items.addAll(_items);
}
void _addElectrumListItems(TransactionInfo tx, DateFormat dateFormat) {
void _addElectrumListItems(
TransactionInfo tx, DateFormat dateFormat, CryptoCurrency cryptoCurrency) {
final isLightning = (tx.additionalInfo["isLightning"] as bool?) ?? false;
final currency = isLightning ? CryptoCurrency.btcln : cryptoCurrency;
final symbol = _appStore.amountParsingProxy.getCryptoSymbol(currency);
final amountFormatted = _appStore.amountParsingProxy.getDisplayCryptoString(
tx.amount, currency);
final feeFormatted = (tx.fee != null)
? _appStore.amountParsingProxy.getDisplayCryptoString(tx.fee!, currency)
: "";
final _items = [
StandartListItem(
title: S.current.transaction_details_transaction_id,
@@ -359,25 +377,27 @@ abstract class TransactionDetailsViewModelBase with Store {
value: dateFormat.format(tx.date),
key: ValueKey('standard_list_item_transaction_details_date_key'),
),
StandartListItem(
title: S.current.confirmations,
value: tx.confirmations.toString(),
key: ValueKey('standard_list_item_transaction_confirmations_key'),
),
StandartListItem(
title: S.current.transaction_details_height,
value: '${tx.height}',
key: ValueKey('standard_list_item_transaction_details_height_key'),
),
if (!isLightning) ...[
StandartListItem(
title: S.current.confirmations,
value: tx.confirmations.toString(),
key: ValueKey('standard_list_item_transaction_confirmations_key'),
),
StandartListItem(
title: S.current.transaction_details_height,
value: '${tx.height}',
key: ValueKey('standard_list_item_transaction_details_height_key'),
),
],
StandartListItem(
title: S.current.transaction_details_amount,
value: tx.amountFormatted(),
value: '$amountFormatted $symbol',
key: ValueKey('standard_list_item_transaction_details_amount_key'),
),
if (tx.feeFormatted()?.isNotEmpty ?? false)
StandartListItem(
title: S.current.transaction_details_fee,
value: tx.feeFormatted()!,
value: '$feeFormatted $symbol',
key: ValueKey('standard_list_item_transaction_details_fee_key'),
),
];
@@ -407,7 +427,7 @@ abstract class TransactionDetailsViewModelBase with Store {
}
void _addLitecoinListItems(TransactionInfo tx, DateFormat dateFormat) {
_addElectrumListItems(tx, dateFormat);
_addElectrumListItems(tx, dateFormat, CryptoCurrency.ltc);
bool isMweb = bitcoin!.txIsMweb(tx);
@@ -636,7 +656,7 @@ abstract class TransactionDetailsViewModelBase with Store {
title: S.current.estimated_new_fee,
value: bitcoin!.formatterBitcoinAmountToString(amount: newFee) + ' ${wallet.currency}',
items: priorityForWalletType(wallet.type),
customValue: settingsStore.customBitcoinFeeRate.toDouble(),
customValue: _appStore.settingsStore.customBitcoinFeeRate.toDouble(),
maxValue: maxCustomFeeRate,
selectedIdx: selectedItem,
customItemIndex: customItemIndex ?? 0,
@@ -1,5 +1,4 @@
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart';
import 'package:cake_wallet/src/screens/transaction_details/blockexplorer_list_item.dart';
import 'package:cake_wallet/src/screens/transaction_details/standart_list_item.dart';
import 'package:cake_wallet/src/screens/transaction_details/textfield_list_item.dart';
@@ -42,9 +41,7 @@ abstract class UnspentCoinsDetailsViewModelBase with Store {
onSwitchValueChange: (value) async {
isFrozen = value;
unspentCoinsItem.isFrozen = value;
if (value) {
unspentCoinsItem.isSending = !value;
}
if (value) unspentCoinsItem.isSending = !value;
await unspentCoinsListViewModel.saveUnspentCoinInfo(unspentCoinsItem);
})
];
@@ -81,13 +78,13 @@ abstract class UnspentCoinsDetailsViewModelBase with Store {
String _explorerDescription(WalletType type) {
switch (type) {
case WalletType.bitcoin:
return S.current.view_transaction_on + 'Ordinals.com';
return '${S.current.view_transaction_on}Ordinals.com';
case WalletType.litecoin:
return S.current.view_transaction_on + 'Earlyordies.com';
return '${S.current.view_transaction_on}Earlyordies.com';
case WalletType.bitcoinCash:
return S.current.view_transaction_on + 'Blockchair.com';
return '${S.current.view_transaction_on}Blockchair.com';
case WalletType.dogecoin:
return S.current.view_transaction_on + 'Dogechain.info';
return '${S.current.view_transaction_on}Dogechain.info';
default:
return '';
}
@@ -18,6 +18,7 @@ abstract class UnspentCoinsItemBase with Store, UnspentComparable {
required this.vout,
required this.keyImage,
required this.isSilentPayment,
this.isBeingSaved = false
});
@observable
@@ -52,4 +53,8 @@ abstract class UnspentCoinsItemBase with Store, UnspentComparable {
@observable
bool isSilentPayment;
@observable
bool isBeingSaved;
}
@@ -1,10 +1,9 @@
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/calculate_fiat_amount_raw.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/exception_handler.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/view_model/unspent_coins/unspent_coins_item.dart';
@@ -33,10 +32,10 @@ abstract class UnspentCoinsListViewModelBase with Store {
required Box<UnspentCoinsInfo> unspentCoinsInfo,
this.coinTypeToSpendFrom = UnspentCoinType.any,
required FiatConversionStore fiatConversationStore,
required SettingsStore settingsStore,
required AppStore appStore,
}) : _unspentCoinsInfo = unspentCoinsInfo,
_fiatConversationStore = fiatConversationStore,
_settingsStore = settingsStore,
_appStore = appStore,
items = ObservableList<UnspentCoinsItem>(),
_originalState = {};
@@ -44,25 +43,34 @@ abstract class UnspentCoinsListViewModelBase with Store {
WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> wallet;
final Box<UnspentCoinsInfo> _unspentCoinsInfo;
final FiatConversionStore _fiatConversationStore;
final SettingsStore _settingsStore;
final UnspentCoinType coinTypeToSpendFrom;
final AppStore _appStore;
@observable
ObservableList<UnspentCoinsItem> items;
@computed
List<UnspentCoinsItem> get nonFrozenItems => items.where((e)=>!e.isFrozen).toList();
@computed
List<UnspentCoinsItem> get frozenItems => items.where((e)=>e.isFrozen).toList();
final Map<String, Map<String, dynamic>> _originalState;
@observable
bool isDisposing = false;
@observable
bool isSavingItems = false;
@computed
bool get isAllSelected => items.every((element) => element.isFrozen || element.isSending);
@computed
FiatCurrency get fiatCurrency => _settingsStore.fiatCurrency;
FiatCurrency get fiatCurrency => _appStore.settingsStore.fiatCurrency;
@computed
bool get isFiatDisabled => _settingsStore.fiatApiMode == FiatApiMode.disabled;
bool get isFiatDisabled => _appStore.settingsStore.fiatApiMode == FiatApiMode.disabled;
@computed
Map<String, String> get fiatAmounts {
@@ -76,7 +84,7 @@ abstract class UnspentCoinsListViewModelBase with Store {
final formatted = formatAmountToString(item.value);
final cryptoAmount = double.tryParse(formatted.replaceAll(',', '')) ?? 0.0;
final fiatValue = price * cryptoAmount;
result[item.amount] = fiatCurrency.title + ' ' + fiatValue.toStringAsFixed(2);
result[item.amount] = '${fiatCurrency.title} ${fiatValue.toStringAsFixed(2)}';
}
return result;
@@ -110,6 +118,8 @@ abstract class UnspentCoinsListViewModelBase with Store {
Future<void> saveUnspentCoinInfo(UnspentCoinsItem item) async {
try {
item.isBeingSaved = true;
isSavingItems = true;
final existingInfo = _unspentCoinsInfo.values
.firstWhereOrNull((element) => element.walletId == wallet.id && element == item);
if (existingInfo == null) return;
@@ -119,23 +129,18 @@ abstract class UnspentCoinsListViewModelBase with Store {
existingInfo.note = item.note;
await existingInfo.save();
item.isBeingSaved = false;
isSavingItems = false;
_updateUnspentCoinsInfo();
} catch (e) {
printV('Error saving coin info: $e');
item.isBeingSaved = false;
isSavingItems = false;
}
}
String formatAmountToString(int fullBalance) {
if (wallet.type == WalletType.monero)
return monero!.formatterMoneroAmountToString(amount: fullBalance);
if (wallet.type == WalletType.wownero)
return wownero!.formatterWowneroAmountToString(amount: fullBalance);
if ([WalletType.bitcoin, WalletType.litecoin, WalletType.bitcoinCash, WalletType.dogecoin].contains(wallet.type))
return bitcoin!.formatterBitcoinAmountToString(amount: fullBalance);
if (wallet.type == WalletType.decred)
return decred!.formatterDecredAmountToString(amount: fullBalance);
return '';
}
String formatAmountToString(int fullBalance) =>
wallet.currency.formatAmount(BigInt.from(fullBalance));
Future<void> _updateUnspents() async {
if (wallet.type == WalletType.monero) {
@@ -211,13 +216,16 @@ abstract class UnspentCoinsListViewModelBase with Store {
.map((elem) {
try {
final existingItem = _unspentCoinsInfo.values
.firstWhereOrNull((item) => item.walletId == wallet.id && item == elem);;
.firstWhereOrNull((item) => item.walletId == wallet.id && item == elem);
if (existingItem == null) return null;
final symbol = _appStore.amountParsingProxy.getCryptoSymbol(wallet.currency);
return UnspentCoinsItem(
address: elem.address,
amount: '${formatAmountToString(elem.value)} ${wallet.currency.title}',
amount:
'${_appStore.amountParsingProxy.getDisplayCryptoString(elem.value, wallet.currency)} $symbol',
hash: elem.hash,
isFrozen: existingItem.isFrozen,
note: existingItem.note,
@@ -268,9 +276,7 @@ abstract class UnspentCoinsListViewModelBase with Store {
void setIsDisposing(bool value) => isDisposing = value;
@action
void updateWallet(WalletBase newWallet) {
wallet = newWallet;
}
void updateWallet(WalletBase newWallet) => wallet = newWallet;
@action
Future<void> dispose() async {
@@ -1,10 +1,10 @@
import 'dart:developer' as dev;
import 'dart:core';
import 'dart:developer' as dev;
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/fiat_conversion_service.dart';
import 'package:cake_wallet/core/payment_uris.dart';
import 'package:cake_wallet/core/wallet_change_listener_view_model.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
@@ -14,26 +14,26 @@ import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/reactions/wallet_utils.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/store/yat/yat_store.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/utils/qr_util.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/utils/list_item.dart';
import 'package:cake_wallet/utils/qr_util.dart';
import 'package:cake_wallet/view_model/wallet_address_list/wallet_account_list_header.dart';
import 'package:cake_wallet/view_model/wallet_address_list/wallet_address_hidden_list_header.dart';
import 'package:cake_wallet/view_model/wallet_address_list/wallet_address_list_header.dart';
import 'package:cake_wallet/view_model/wallet_address_list/wallet_address_list_item.dart';
import 'package:cake_wallet/view_model/wallet_address_list/wallet_address_util.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/amount_converter.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/erc20_token.dart';
import 'package:cw_core/payment_uris.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:intl/intl.dart';
import 'package:mobx/mobx.dart';
part 'wallet_address_list_view_model.g.dart';
@@ -47,11 +47,9 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
required this.fiatConversionStore,
}) : _baseItems = <ListItem>[],
selectedCurrency = appStore.wallet!.currency,
_cryptoNumberFormat = NumberFormat(_cryptoNumberPattern),
hasAccounts = [WalletType.monero, WalletType.wownero, WalletType.haven]
.contains(appStore.wallet!.type),
amount = '',
_settingsStore = appStore.settingsStore,
hasAccounts = [WalletType.monero, WalletType.wownero].contains(appStore.wallet!.type),
_appStore = appStore,
receivePageOption = appStore.wallet!.walletAddresses.walletInfo.addressPageType ?? '',
super(appStore: appStore) {
_init();
}
@@ -67,17 +65,35 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
hasAccounts = [WalletType.monero, WalletType.wownero, WalletType.haven].contains(wallet.type);
}
static const String _cryptoNumberPattern = '0.00000000';
final NumberFormat _cryptoNumberFormat;
final FiatConversionStore fiatConversionStore;
final SettingsStore _settingsStore;
final AppStore _appStore;
double? _fiatRate;
String _rawAmount = '';
List<Currency> get currencies => [wallet.currency, ...FiatCurrency.all];
List<Currency> get currencies =>
[tokenCurrency ?? wallet.currency, ...FiatCurrency.all];
List<Currency> get tokenCurrencies => wallet.balance.keys.toList();
@observable
CryptoCurrency? tokenCurrency;
@computed
String get cryptoCurrencySymbol =>
_appStore.amountParsingProxy.getCryptoSymbol(tokenCurrency ?? wallet.currency);
void setTokenCurrency(Currency curr) {
if(curr == wallet.currency || curr == CryptoCurrency.btcln) {
tokenCurrency = null;
selectedCurrency = wallet.currency;
return;
}
tokenCurrency = curr as CryptoCurrency;
if (selectedCurrency is CryptoCurrency) {
selectedCurrency = curr;
}
}
String get buttonTitle {
if (isElectrumWallet) {
@@ -90,14 +106,70 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
@observable
Currency selectedCurrency;
@computed
String get selectedCurrencySymbol => selectedCurrency is CryptoCurrency
? _appStore.amountParsingProxy.getCryptoSymbol(selectedCurrency as CryptoCurrency)
: selectedCurrency.name.toUpperCase();
@computed
int get selectedCurrencyDecimals => useSatoshi ? 0 : selectedCurrency.decimals;
@computed
bool get useSatoshi =>
selectedCurrency is CryptoCurrency &&
_appStore.amountParsingProxy.useSatoshi(selectedCurrency as CryptoCurrency);
@observable
String searchText = '';
@computed
int get selectedCurrencyIndex => currencies.indexOf(selectedCurrency);
@computed
int get tokenCurrencyIndex => tokenCurrency == null ? 0 : tokenCurrencies.indexOf(tokenCurrency!);
@observable
String amount;
String _amount = '';
@computed
String get displayAmount => _appStore.amountParsingProxy
.getDisplayCryptoAmount(_amount, tokenCurrency ?? wallet.currency);
// NOT PRECISE! just for display purposes.
@computed
String get fiatAmount {
if (_amount.isEmpty) return "";
var cryptoCurrency = tokenCurrency ?? wallet.currency;
if (cryptoCurrency == CryptoCurrency.btcln) cryptoCurrency = CryptoCurrency.btc;
if(selectedCurrency is FiatCurrency && _fiatRate != null) {
return selectedCurrencyFiatAmount;
}
if (!fiatConversionStore.prices.containsKey(cryptoCurrency)) return "";
return (double.parse(_amount) * fiatConversionStore.prices[cryptoCurrency]!).toStringAsFixed(2);
}
@computed
String get selectedCurrencyFiatAmount {
if (_fiatRate == null) return "";
return (double.parse(_amount) * _fiatRate!).toStringAsFixed(2);
}
@action
Future<void> dismissInfobox() async {
wallet.walletInfo.receiveInfoboxDismissed = true;
await wallet.walletInfo.save();
}
// payjoinEndpoint getter is broken, but uri works
bool get hasPayjoin =>
wallet.type == WalletType.bitcoin && !isLightning && !isSilentPayments && uri.toString().contains("payjo.in");
@computed
FiatCurrency get fiatCurrency => _appStore.settingsStore.fiatCurrency;
@computed
bool get isFiatDisabled => _appStore.settingsStore.fiatApiMode == FiatApiMode.disabled;
@computed
WalletType get type => wallet.type;
@@ -111,72 +183,26 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
wallet.type == WalletType.bitcoin ? bitcoin!.getPayjoinEndpoint(wallet) : "";
@computed
bool get isPayjoinUnavailable =>
wallet.type == WalletType.bitcoin && _settingsStore.usePayjoin && payjoinEndpoint.isEmpty;
bool get isPayjoinUnavailable => payjoinEndpoint.isEmpty;
@observable
PaymentURI? _lnPaymentRequest;
@computed
PaymentURI get uri {
if (isEVMCompatibleChain(wallet.type) && selectedChainId != null) {
switch (selectedChainId) {
case 1:
return EthereumURI(amount: amount, address: address.address);
case 137:
return PolygonURI(amount: amount, address: address.address);
case 8453:
return BaseURI(amount: amount, address: address.address);
case 42161:
return ArbitrumURI(amount: amount, address: address.address);
case 56:
return BSCURI(amount: amount, address: address.address);
default:
return EthereumURI(amount: amount, address: address.address);
}
}
switch (wallet.type) {
case WalletType.monero:
return MoneroURI(amount: amount, address: address.address);
case WalletType.haven:
return HavenURI(amount: amount, address: address.address);
case WalletType.bitcoin:
return BitcoinURI(amount: amount, address: address.address, pjUri: payjoinEndpoint);
case WalletType.litecoin:
return LitecoinURI(amount: amount, address: address.address);
case WalletType.ethereum:
return EthereumURI(amount: amount, address: address.address);
case WalletType.bitcoinCash:
return BitcoinCashURI(amount: amount, address: address.address);
case WalletType.banano:
return NanoURI(amount: amount, address: address.address);
case WalletType.nano:
return NanoURI(amount: amount, address: address.address);
case WalletType.polygon:
return PolygonURI(amount: amount, address: address.address);
case WalletType.solana:
return SolanaURI(amount: amount, address: address.address);
case WalletType.tron:
return TronURI(amount: amount, address: address.address);
case WalletType.wownero:
return WowneroURI(amount: amount, address: address.address);
case WalletType.zano:
return ZanoURI(amount: amount, address: address.address);
case WalletType.decred:
return DecredURI(amount: amount, address: address.address);
case WalletType.dogecoin:
return DogeURI(amount: amount, address: address.address);
case WalletType.base:
return BaseURI(amount: amount, address: address.address);
case WalletType.arbitrum:
return ArbitrumURI(amount: amount, address: address.address);
case WalletType.bsc:
return BSCURI(amount: amount, address: address.address);
case WalletType.zcash:
return ZcashURI(amount: amount, address: address.address);
case WalletType.none:
throw Exception('Unexpected type: ${type.toString()}');
if (tokenCurrency != null && isEVMCompatibleChain(wallet.type)) {
return ERC681URI(
chainId: wallet.chainId ?? 1,
address: wallet.walletAddresses.address,
amount: _amount,
contractAddress: (tokenCurrency as Erc20Token).contractAddress);
}
if (_lnPaymentRequest != null) return _lnPaymentRequest!;
return wallet.walletAddresses.getPaymentUri(_amount);
}
bool get isPayjoinAvailable => !isPayjoinUnavailable && !isSilentPayments && !isLightning;
@computed
ObservableList<ListItem> get items => ObservableList<ListItem>()
..addAll(_baseItems)
@@ -227,10 +253,8 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
name: address.name,
address: address.address,
txCount: address.txCount,
balance: AmountConverter.amountIntToString(
walletTypeToCryptoCurrency(type),
address.balance,
),
balance: _appStore.amountParsingProxy
.getDisplayCryptoString(address.balance, walletTypeToCryptoCurrency(type)),
isChange: address.isChange,
);
});
@@ -245,10 +269,8 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
name: address.name,
address: address.address,
txCount: address.txCount,
balance: AmountConverter.amountIntToString(
walletTypeToCryptoCurrency(type),
address.balance,
),
balance: _appStore.amountParsingProxy
.getDisplayCryptoString(address.balance, walletTypeToCryptoCurrency(type)),
isChange: address.isChange,
isOneTimeReceiveAddress: true,
);
@@ -264,10 +286,8 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
name: subaddress.name,
address: subaddress.address,
txCount: subaddress.txCount,
balance: AmountConverter.amountIntToString(
walletTypeToCryptoCurrency(type),
subaddress.balance,
),
balance: _appStore.amountParsingProxy
.getDisplayCryptoString(subaddress.balance, walletTypeToCryptoCurrency(type)),
isChange: subaddress.isChange);
});
@@ -424,8 +444,11 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
WalletType.litecoin,
WalletType.decred,
WalletType.dogecoin,
WalletType.zcash,
].contains(wallet.type);
WalletType.zcash
].contains(wallet.type) && !isLightning && isZCashTransparent;
@computed
bool get hasAddressRotation => hasAddressList && wallet.type != WalletType.zcash;
@computed
bool get isElectrumWallet => [
@@ -508,7 +531,10 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
}
@computed
String get qrImage => getQrImage(type);
String get qrImage {
if (isLightning) return 'assets/images/btc_chain_qr_lightning.svg';
return getQrImage(type);
}
@computed
String get monoImage => getChainMonoImage(type);
@@ -523,6 +549,21 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
bool get isSilentPayments =>
wallet.type == WalletType.bitcoin && bitcoin!.hasSelectedSilentPayments(wallet);
@computed
bool get isLightning => wallet.type == WalletType.bitcoin && (uri is LightningPaymentRequest);
@computed
bool get isZCashTransparent {
if(wallet.type != WalletType.zcash) {
return true;
}
receivePageOption;
return wallet.type == WalletType.zcash && zcash!.hasSelectedTransparentAddress(wallet);
}
@observable
String receivePageOption;
@computed
bool get isBitcoinViewOnly =>
wallet.type == WalletType.bitcoin &&
@@ -530,7 +571,8 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
@computed
bool get isAutoGenerateSubaddressEnabled =>
_settingsStore.autoGenerateSubaddressStatus != AutoGenerateSubaddressStatus.disabled &&
_appStore.settingsStore.autoGenerateSubaddressStatus !=
AutoGenerateSubaddressStatus.disabled &&
!isSilentPayments;
@computed
@@ -546,8 +588,17 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
void setAddress(WalletAddressListItem address) =>
wallet.walletAddresses.address = address.address;
@action
Future<void> rotateAddress() async {
await createNewAddress(wallet, "");
if (isElectrumWallet) {
wallet.walletAddresses.address = addressList.whereType<WalletAddressListItem>().last.address;
}
}
@action
Future<void> setAddressType(dynamic option) async {
receivePageOption = option.toString();
if ([WalletType.bitcoin, WalletType.litecoin].contains(wallet.type)) {
await bitcoin!.setAddressType(wallet, option);
}
@@ -577,20 +628,23 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
if (wallet.isEnabledAutoGenerateSubaddress) {
wallet.walletAddresses.address = wallet.walletAddresses.latestAddress;
}
// reaction((_) => amount, (_) => refreshUri());
// reaction((_) => address, (_) => refreshUri());
}
@action
void selectCurrency(Currency currency) {
selectedCurrency = currency;
if (currency is FiatCurrency && _settingsStore.fiatCurrency != currency) {
if (currency is FiatCurrency && _appStore.settingsStore.fiatCurrency != currency) {
final cryptoCurrency = wallet.currency;
dev.log("Requesting Fiat rate for $cryptoCurrency-$currency");
FiatConversionService.fetchPrice(
crypto: cryptoCurrency,
fiat: currency,
torOnly: _settingsStore.fiatApiMode == FiatApiMode.torOnly,
torOnly: _appStore.settingsStore.fiatApiMode == FiatApiMode.torOnly,
).then((value) {
dev.log("Received Fiat rate 1 $cryptoCurrency = $value $currency");
_fiatRate = value;
@@ -601,10 +655,17 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
@action
void changeAmount(String amount) {
this.amount = amount;
this._rawAmount = amount;
if (selectedCurrency is FiatCurrency) {
this._amount = amount;
_convertAmountToCrypto();
} else if (selectedCurrency is CryptoCurrency) {
this._amount = _appStore.amountParsingProxy
.getCanonicalCryptoAmount(amount, selectedCurrency as CryptoCurrency);
}
if (isLightning) {
wallet.walletAddresses
.getPaymentRequestUri(this._amount)
.then((uri) => _lnPaymentRequest = uri);
}
}
@@ -615,23 +676,23 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
@action
void _convertAmountToCrypto() {
final cryptoCurrency = wallet.currency;
var cryptoCurrency = tokenCurrency ?? wallet.currency;
if (cryptoCurrency == CryptoCurrency.btcln) cryptoCurrency = CryptoCurrency.btc;
final fiatRate = _fiatRate ?? (fiatConversionStore.prices[cryptoCurrency] ?? 0.0);
if (fiatRate <= 0.0) {
dev.log("Invalid Fiat Rate $fiatRate");
amount = '';
_amount = '';
return;
}
try {
final crypto = double.parse(_rawAmount.replaceAll(',', '.')) / fiatRate;
final cryptoAmountTmp = _cryptoNumberFormat.format(crypto);
if (amount != cryptoAmountTmp) {
amount = cryptoAmountTmp;
final crypto = (double.parse(_amount.replaceAll(',', '.')) / fiatRate).toStringAsFixed(8);
if (_amount != crypto) {
_amount = crypto;
}
} catch (e) {
amount = '';
_amount = '';
}
}
@@ -0,0 +1,49 @@
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
Future<void> createNewAddress(WalletBase wallet, String label) async {
final isElectrum = wallet.type == WalletType.bitcoin ||
wallet.type == WalletType.bitcoinCash ||
wallet.type == WalletType.litecoin ||
wallet.type == WalletType.dogecoin;
if (isElectrum) {
await bitcoin!.generateNewAddress(wallet, label);
await wallet.save();
}
if (wallet.type == WalletType.decred) {
await decred!.generateNewAddress(wallet, label);
await wallet.save();
}
if (wallet.type == WalletType.monero) {
await monero!
.getSubaddressList(wallet)
.addSubaddress(wallet, accountIndex: monero!.getCurrentAccount(wallet).id, label: label);
final addr = await monero!
.getSubaddressList(wallet)
.subaddresses
.first
.address; // first because the order is reversed
wallet.walletAddresses.manualAddresses.add(addr);
await wallet.save();
}
if (wallet.type == WalletType.wownero) {
await wownero!
.getSubaddressList(wallet)
.addSubaddress(wallet, accountIndex: wownero!.getCurrentAccount(wallet).id, label: label);
final addr = await wownero!
.getSubaddressList(wallet)
.subaddresses
.first
.address; // first because the order is reversed
wallet.walletAddresses.manualAddresses.add(addr);
await wallet.save();
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/entities/generate_name.dart';
import 'package:cw_core/generate_name.dart';
import 'package:cake_wallet/entities/hash_wallet_identifier.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/nano/nano.dart';
+34 -13
View File
@@ -9,6 +9,7 @@ import 'package:cake_wallet/zcash/zcash.dart';
import 'package:cw_core/transaction_direction.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_monero/monero_wallet.dart';
import 'package:flutter/foundation.dart';
@@ -53,16 +54,36 @@ abstract class WalletKeysViewModelBase with Store {
}
static String _getInitialTitle(WalletBase wallet) {
if (isEVMCompatibleChain(wallet.type)) {
final currentChain = evm!.getCurrentChain(wallet);
return '${currentChain?.name ?? walletTypeToString(wallet.type)} ${S.current.wallet_keys}';
}
final baseName = walletTypeToString(wallet.type);
final keysLabel = S.current.wallet_keys;
return '${walletTypeToString(wallet.type)} ${S.current.wallet_keys}';
final hwSuffix =
wallet.isHardwareWallet ? ' (${_hardwareWalletTypeLabel(wallet.hardwareWalletType!)})' : '';
return '$baseName $keysLabel $hwSuffix';
}
static String _hardwareWalletTypeLabel(HardwareWalletType type) {
switch (type) {
case HardwareWalletType.ledger:
return 'Ledger';
case HardwareWalletType.bitbox:
return 'BitBox';
case HardwareWalletType.trezor:
return 'Trezor';
case HardwareWalletType.cupcake:
return 'Cupcake';
case HardwareWalletType.coldcard:
return 'Coldcard';
case HardwareWalletType.seedsigner:
return 'SeedSigner';
case HardwareWalletType.keystone:
return 'Keystone';
}
}
bool get isBitcoin => _wallet.type == WalletType.bitcoin;
// this is incomplete, needs legacy seed toggle for XMR
bool get shouldShowHeightBox => [WalletType.bitcoin, WalletType.zcash].contains(_wallet.type);
final ObservableList<StandartListItem> items;
@@ -213,42 +234,42 @@ abstract class WalletKeysViewModelBase with Store {
if (keys != null) {
items.addAll([
if ((keys['primaryAddress']??'').isNotEmpty)
if ((keys['primaryAddress'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_primary_address_item_key'),
title: S.current.primary_address,
value: keys['primaryAddress']!),
if ((keys['publicSpendKey']??'').isNotEmpty)
if ((keys['publicSpendKey'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_public_spend_key_item_key'),
title: S.current.spend_key_public,
value: keys['publicSpendKey']!,
),
if ((keys['privateSpendKey']??'').isNotEmpty)
if ((keys['privateSpendKey'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_private_spend_key_item_key'),
title: S.current.spend_key_private,
value: keys['privateSpendKey']!,
),
if ((keys['publicViewKey']??'').isNotEmpty)
if ((keys['publicViewKey'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_public_view_key_item_key'),
title: S.current.view_key_public,
value: keys['publicViewKey']!,
),
if ((keys['privateViewKey']??'').isNotEmpty)
if ((keys['privateViewKey'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_private_view_key_item_key'),
title: S.current.view_key_private,
value: keys['privateViewKey']!,
),
if ((keys['tsk']??'').isNotEmpty)
if ((keys['tsk'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_transparent_secret_key_item_key'),
title: S.current.transparent_secret_key,
value: keys['tsk']!,
),
if ((keys['uvk']??'').isNotEmpty)
if ((keys['uvk'] ?? '').isNotEmpty)
StandartListItem(
key: ValueKey('${_walletName}_wallet_unified_view_key_item_key'),
title: S.current.unified_view_key,
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cake_wallet/entities/wallet_group.dart';
import 'package:cake_wallet/entities/wallet_list_order_types.dart';
@@ -7,7 +9,6 @@ import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/view_model/wallet_list/wallet_list_item.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cake_wallet/wallet_types.g.dart';
part 'wallet_list_view_model.g.dart';
@@ -25,6 +26,9 @@ abstract class WalletListViewModelBase with Store {
expansionTileStateTrack = ObservableMap<int, bool>() {
setOrderType(_appStore.settingsStore.walletListOrder);
updateList();
reaction((_) => _appStore.wallet, (_) {
updateList();
});
}
@observable
@@ -85,14 +89,19 @@ abstract class WalletListViewModelBase with Store {
bool get ascending => _appStore.settingsStore.walletListAscending;
bool isUpdating = false;
/// Serializes updateList() calls: each caller waits for the previous one to finish, then runs.
///
/// This basically ensures that all calls to updateList() are executed.
Future<void> _lastUpdate = Future.value();
@action
Future<void> updateList() async {
if (isUpdating) {
return;
}
isUpdating = true;
final waitFor = _lastUpdate;
final done = Completer<void>();
_lastUpdate = done.future;
await waitFor;
try {
wallets.clear();
multiWalletGroups.clear();
@@ -104,7 +113,6 @@ abstract class WalletListViewModelBase with Store {
wallets.add(convertWalletInfoToWalletListItem(info));
}
//========== Split into shared seed groups and single wallets list
await _walletManager.updateWalletGroups();
final walletGroupsFromManager = _walletManager.walletGroups;
@@ -118,7 +126,7 @@ abstract class WalletListViewModelBase with Store {
multiWalletGroups.add(group);
}
} finally {
isUpdating = false;
done.complete();
}
}
@@ -151,7 +159,7 @@ abstract class WalletListViewModelBase with Store {
for (WalletInfo walletInfo in group.wallets) {
for (int i = 0; i < wiList.length; i++) {
if (wiList[i].name == walletInfo.name) {
wiList[i].sortOrder = i+oldI;
wiList[i].sortOrder = i + oldI;
await wiList[i].save();
wiList.removeAt(i);
break;
@@ -240,8 +248,7 @@ abstract class WalletListViewModelBase with Store {
name: info.name,
type: info.type,
key: info.id,
isCurrent: info.name == _appStore.wallet?.name &&
info.type == _appStore.wallet?.type,
isCurrent: info.name == _appStore.wallet?.name && info.type == _appStore.wallet?.type,
isEnabled: availableWalletTypes.contains(info.type),
isTestnet: info.network?.toLowerCase().contains('testnet') ?? false,
isHardware: info.isHardwareWallet,
+3 -13
View File
@@ -6,8 +6,6 @@ import 'package:flutter/foundation.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:mobx/mobx.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
part 'wallet_seed_view_model.g.dart';
@@ -17,20 +15,12 @@ abstract class WalletSeedViewModelBase with Store {
WalletSeedViewModelBase(WalletBase wallet)
: name = wallet.name,
seed = wallet.seed!,
walletType = _getWalletTypeName(wallet),
walletType = wallet.type,
currentOptions = ObservableList<String>(),
verificationIndices = ObservableList<int>() {
setupSeedVerification();
}
static String _getWalletTypeName(WalletBase wallet) {
if (isEVMCompatibleChain(wallet.type)) {
final currentChain = evm!.getCurrentChain(wallet);
return currentChain?.name ?? walletTypeToString(wallet.type);
} else {
return walletTypeToString(wallet.type);
}
}
@observable
String name;
@@ -39,7 +29,7 @@ abstract class WalletSeedViewModelBase with Store {
String seed;
@observable
String walletType;
WalletType walletType;
/// The Regex split the words based on any whitespace character.
///
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_core/utils/print_verbose.dart';