mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-10-22 06:28:39 +02:00
+4








084fd6bb1e
* 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>
1539 lines
54 KiB
Dart
1539 lines
54 KiB
Dart
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';
|
|
import 'package:cake_wallet/core/wallet_change_listener_view_model.dart';
|
|
import 'package:cake_wallet/decred/decred.dart';
|
|
import 'package:cake_wallet/entities/calculate_fiat_amount.dart';
|
|
import 'package:cake_wallet/entities/contact.dart';
|
|
import 'package:cake_wallet/entities/contact_record.dart';
|
|
import 'package:cake_wallet/entities/evm_transaction_error_fees_handler.dart';
|
|
import 'package:cake_wallet/entities/fiat_currency.dart';
|
|
import 'package:cake_wallet/entities/parsed_address.dart';
|
|
import 'package:cake_wallet/entities/preferences_key.dart';
|
|
import 'package:cake_wallet/entities/template.dart';
|
|
import 'package:cake_wallet/entities/transaction_description.dart';
|
|
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';
|
|
import 'package:cake_wallet/exchange/trade.dart';
|
|
import 'package:cake_wallet/exchange/trade_state.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/reactions/wallet_connect.dart';
|
|
import 'package:cake_wallet/routes.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';
|
|
import 'package:cake_wallet/utils/payment_request.dart';
|
|
import 'package:cake_wallet/view_model/contact_list/contact_list_view_model.dart';
|
|
import 'package:cake_wallet/view_model/dashboard/balance_view_model.dart';
|
|
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
|
|
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_template_view_model.dart';
|
|
import 'package:cake_wallet/view_model/send/send_view_model_state.dart';
|
|
import 'package:cake_wallet/view_model/unspent_coins/unspent_coins_list_view_model.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_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';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:hive/hive.dart';
|
|
import 'package:mobx/mobx.dart';
|
|
import 'package:cake_wallet/utils/token_utilities.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
part 'send_view_model.g.dart';
|
|
|
|
class SendViewModel = SendViewModelBase with _$SendViewModel;
|
|
|
|
abstract class SendViewModelBase extends WalletChangeListenerViewModel with Store {
|
|
@override
|
|
void onWalletChange(wallet) {
|
|
currencies = wallet.balance.keys.toList();
|
|
selectedCryptoCurrency =
|
|
coinTypeToSpendFrom == UnspentCoinType.lightning ? CryptoCurrency.btcln : wallet.currency;
|
|
hasMultipleTokens = isEVMWallet ||
|
|
[WalletType.solana, WalletType.tron, WalletType.zano].contains(wallet.type);
|
|
|
|
for (final output in outputs) {
|
|
output.updateWallet(wallet);
|
|
}
|
|
|
|
// Update unspent coins list view model with the new wallet reference
|
|
unspentCoinsListViewModel.updateWallet(wallet);
|
|
|
|
// Update sending balance to reflect the new wallet's balance
|
|
updateSendingBalance();
|
|
}
|
|
|
|
UnspentCoinsListViewModel unspentCoinsListViewModel;
|
|
|
|
SendViewModelBase(
|
|
this._appStore,
|
|
this.sendTemplateViewModel,
|
|
this._fiatConversationStore,
|
|
this.balanceViewModel,
|
|
this.contactListViewModel,
|
|
this.transactionDescriptionBox,
|
|
this.hardwareWalletViewModel,
|
|
this.unspentCoinsListViewModel,
|
|
this.feesViewModel, {
|
|
this.coinTypeToSpendFrom = UnspentCoinType.nonMweb,
|
|
}) : state = InitialExecutionState(),
|
|
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>(),
|
|
fiatFromSettings = _appStore.settingsStore.fiatCurrency,
|
|
fiatCurrencies = FiatCurrency.all,
|
|
super(appStore: _appStore) {
|
|
outputs.add(Output(wallet, _appStore, _fiatConversationStore, () => selectedCryptoCurrency));
|
|
|
|
unspentCoinsListViewModel
|
|
.initialSetup()
|
|
.then((_) => unspentCoinsListViewModel.resetUnspentCoinsInfoSelections());
|
|
|
|
reaction((_) {
|
|
if (isEVMCompatibleChain(wallet.type)) {
|
|
// Access currency which depends on selectedChainId, so MobX tracks the change
|
|
return wallet.currency;
|
|
}
|
|
return null;
|
|
}, (_) async {
|
|
// When chain changes, update currencies and selected currency
|
|
await Future.delayed(const Duration(milliseconds: 100));
|
|
currencies = wallet.balance.keys.toList();
|
|
selectedCryptoCurrency = wallet.currency;
|
|
updateSendingBalance();
|
|
});
|
|
}
|
|
|
|
// Store trade and provider references for post-commit updates (e.g., Jupiter trade ID update)
|
|
Trade? _currentTrade;
|
|
ExchangeProvider? _currentProvider;
|
|
|
|
@observable
|
|
ExecutionState state;
|
|
|
|
ObservableList<Output> outputs;
|
|
|
|
@observable
|
|
UnspentCoinType coinTypeToSpendFrom;
|
|
|
|
bool get showAddressBookPopup => _settingsStore.showAddressBookPopupEnabled;
|
|
|
|
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;
|
|
|
|
@action
|
|
void addOutput() =>
|
|
outputs.add(Output(wallet, _appStore, _fiatConversationStore, () => selectedCryptoCurrency));
|
|
|
|
@action
|
|
void removeOutput(Output output) {
|
|
if (isBatchSending) outputs.remove(output);
|
|
}
|
|
|
|
@action
|
|
void clearOutputs() {
|
|
outputs.clear();
|
|
addOutput();
|
|
}
|
|
|
|
@action
|
|
void setAllowMwebCoins(bool allow) {
|
|
if (wallet.type == WalletType.litecoin) {
|
|
coinTypeToSpendFrom = allow ? UnspentCoinType.any : UnspentCoinType.nonMweb;
|
|
}
|
|
}
|
|
|
|
@computed
|
|
bool get isBatchSending => outputs.length > 1;
|
|
|
|
bool get shouldDisplaySendALL {
|
|
if (walletType == WalletType.solana) return false;
|
|
|
|
// if (walletType == WalletType.ethereum && selectedCryptoCurrency == CryptoCurrency.eth)
|
|
// return false;
|
|
|
|
// if (walletType == WalletType.polygon && selectedCryptoCurrency == CryptoCurrency.maticpoly)
|
|
// return false;
|
|
|
|
return true;
|
|
}
|
|
|
|
@computed
|
|
String get pendingTransactionFiatAmount {
|
|
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: amountValue);
|
|
return fiat;
|
|
} catch (_) {
|
|
return '0.00';
|
|
}
|
|
}
|
|
|
|
@computed
|
|
String get pendingTransactionFeeFiatAmount {
|
|
try {
|
|
if (pendingTransaction != null) {
|
|
final currency = pendingTransactionFeeCurrency(walletType);
|
|
final fiat = calculateFiatAmount(
|
|
price: _fiatConversationStore.prices[currency]!,
|
|
cryptoAmount: pendingTransaction!.feeFormattedValue,
|
|
);
|
|
return fiat;
|
|
} else {
|
|
return '0.00';
|
|
}
|
|
} catch (_) {
|
|
return '0.00';
|
|
}
|
|
}
|
|
|
|
CryptoCurrency pendingTransactionFeeCurrency(WalletType type) {
|
|
switch (type) {
|
|
case WalletType.ethereum:
|
|
case WalletType.polygon:
|
|
case WalletType.base:
|
|
case WalletType.arbitrum:
|
|
case WalletType.bsc:
|
|
case WalletType.tron:
|
|
case WalletType.solana:
|
|
case WalletType.bitcoin:
|
|
return wallet.currency;
|
|
default:
|
|
return selectedCryptoCurrency;
|
|
}
|
|
}
|
|
|
|
FiatCurrency get fiat => _settingsStore.fiatCurrency;
|
|
|
|
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
|
|
// bitcoin!.silentPaymentsMinAmount
|
|
'0.00001'
|
|
: null,
|
|
);
|
|
|
|
Validator<String> get allAmountValidator => AllAmountValidator();
|
|
|
|
Validator<String> get addressValidator =>
|
|
AddressValidator(type: selectedCryptoCurrency, isTestnet: wallet.isTestnet);
|
|
|
|
Validator<String> get textValidator => TextValidator();
|
|
|
|
final FiatCurrency fiatFromSettings;
|
|
|
|
@observable
|
|
PendingTransaction? pendingTransaction;
|
|
|
|
@computed
|
|
String get balance {
|
|
if (walletType == WalletType.litecoin && coinTypeToSpendFrom == UnspentCoinType.mweb) {
|
|
return balanceViewModel.balances.values.first.secondAvailableBalance;
|
|
} else if (walletType == WalletType.litecoin &&
|
|
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 _appStore.amountParsingProxy.getDisplayCryptoString(0, selectedCryptoCurrency);
|
|
}
|
|
return _appStore.amountParsingProxy.getDisplayCryptoStringFromBigInt(
|
|
wallet.balance[selectedCryptoCurrency]!.fullAvailableBalance, selectedCryptoCurrency);
|
|
}
|
|
|
|
@action
|
|
Future<void> updateSendingBalance() async {
|
|
// force the sendingBalance to recompute since unspent coins aren't observable
|
|
// or at least mobx can't detect the changes
|
|
|
|
final currentType = coinTypeToSpendFrom;
|
|
|
|
if (currentType == UnspentCoinType.any) {
|
|
coinTypeToSpendFrom = UnspentCoinType.nonMweb;
|
|
} else if (currentType == UnspentCoinType.nonMweb) {
|
|
coinTypeToSpendFrom = UnspentCoinType.any;
|
|
} else if (currentType == UnspentCoinType.mweb) {
|
|
coinTypeToSpendFrom = UnspentCoinType.nonMweb;
|
|
}
|
|
|
|
// set it back to the original value:
|
|
coinTypeToSpendFrom = currentType;
|
|
}
|
|
|
|
@computed
|
|
Future<String> get sendingBalance async {
|
|
// 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:
|
|
final sendingBalance =
|
|
await unspentCoinsListViewModel.getSendingBalance(coinTypeToSpendFrom);
|
|
return walletTypeToCryptoCurrency(walletType).formatAmount(BigInt.from(sendingBalance));
|
|
default:
|
|
return balance;
|
|
}
|
|
}
|
|
|
|
@computed
|
|
bool get isFiatDisabled => balanceViewModel.isFiatDisabled;
|
|
|
|
@computed
|
|
String get pendingTransactionFiatAmountFormatted =>
|
|
isFiatDisabled ? '' : '$pendingTransactionFiatAmount ${fiat.title}';
|
|
|
|
@computed
|
|
String get pendingTransactionFeeFiatAmountFormatted =>
|
|
isFiatDisabled ? '' : '$pendingTransactionFeeFiatAmount ${fiat.title}';
|
|
|
|
@computed
|
|
bool get isReadyForSend =>
|
|
wallet.syncStatus is SyncedSyncStatus ||
|
|
// If silent payments scanning, can still send payments
|
|
(wallet.type == WalletType.bitcoin && wallet.syncStatus is SyncingSyncStatus);
|
|
|
|
bool isSendToSilentPayments(Output output) =>
|
|
wallet.type == WalletType.bitcoin &&
|
|
(RegExp(AddressValidator.silentPaymentAddressPatternMainnet).hasMatch(output.address) ||
|
|
RegExp(AddressValidator.silentPaymentAddressPatternMainnet)
|
|
.hasMatch(output.extractedAddress) ||
|
|
(output.parsedAddress.addresses.isNotEmpty &&
|
|
RegExp(AddressValidator.silentPaymentAddressPatternMainnet)
|
|
.hasMatch(output.parsedAddress.addresses[0])));
|
|
|
|
@computed
|
|
List<Template> get templates => sendTemplateViewModel.templates
|
|
.where((template) => _isEqualCurrency(template.cryptoCurrency))
|
|
.toList();
|
|
|
|
@computed
|
|
bool get hasCoinControl =>
|
|
[
|
|
WalletType.bitcoin,
|
|
WalletType.litecoin,
|
|
WalletType.monero,
|
|
WalletType.wownero,
|
|
WalletType.decred,
|
|
WalletType.bitcoinCash,
|
|
WalletType.dogecoin
|
|
].contains(wallet.type) &&
|
|
coinTypeToSpendFrom != UnspentCoinType.lightning;
|
|
|
|
@computed
|
|
bool get hasFees => feesViewModel.hasFees && coinTypeToSpendFrom != UnspentCoinType.lightning;
|
|
|
|
@computed
|
|
bool get isElectrumWallet => [
|
|
WalletType.bitcoin,
|
|
WalletType.litecoin,
|
|
WalletType.bitcoinCash,
|
|
WalletType.dogecoin
|
|
].contains(wallet.type);
|
|
|
|
@observable
|
|
CryptoCurrency selectedCryptoCurrency;
|
|
|
|
@computed
|
|
String get selectedCryptoCurrencySymbol =>
|
|
amountParsingProxy.getCryptoSymbol(selectedCryptoCurrency);
|
|
|
|
List<CryptoCurrency> currencies;
|
|
|
|
WalletType get walletType => wallet.type;
|
|
|
|
String? get walletCurrencyName => wallet.currency.fullName?.toLowerCase() ?? wallet.currency.name;
|
|
|
|
@computed
|
|
FiatCurrency get fiatCurrency => _settingsStore.fiatCurrency;
|
|
|
|
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;
|
|
final HardwareWalletViewModel? hardwareWalletViewModel;
|
|
final FeesViewModel feesViewModel;
|
|
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;
|
|
|
|
@observable
|
|
int? selectedChainId;
|
|
|
|
@computed
|
|
List<ContactRecord> get contactsToShow => contactListViewModel.contacts
|
|
.where((element) => element.type == selectedCryptoCurrency)
|
|
.toList();
|
|
|
|
@computed
|
|
List<WalletContact> get walletContactsToShow => contactListViewModel.walletContacts
|
|
.where((element) => element.type == selectedCryptoCurrency)
|
|
.toList();
|
|
|
|
@action
|
|
bool checkIfAddressIsAContact(String address) =>
|
|
contactsToShow.where((element) => element.address == address).toList().isNotEmpty;
|
|
|
|
@action
|
|
bool checkIfWalletIsAnInternalWallet(String address) =>
|
|
walletContactsToShow.where((element) => element.address == address).toList().isNotEmpty;
|
|
|
|
@computed
|
|
bool get shouldDisplayTOTP2FAForContact => _settingsStore.shouldRequireTOTP2FAForSendsToContact;
|
|
|
|
@computed
|
|
bool get shouldDisplayTOTP2FAForNonContact =>
|
|
_settingsStore.shouldRequireTOTP2FAForSendsToNonContact;
|
|
|
|
@computed
|
|
bool get shouldDisplayTOTP2FAForSendsToInternalWallet =>
|
|
_settingsStore.shouldRequireTOTP2FAForSendsToInternalWallets;
|
|
|
|
//* Still open to further optimize these checks
|
|
//* It works but can be made better
|
|
@action
|
|
bool checkThroughChecksToDisplayTOTP(String address) {
|
|
final isContact = checkIfAddressIsAContact(address);
|
|
final isInternalWallet = checkIfWalletIsAnInternalWallet(address);
|
|
|
|
if (isContact) {
|
|
return shouldDisplayTOTP2FAForContact;
|
|
} else if (isInternalWallet) {
|
|
return shouldDisplayTOTP2FAForSendsToInternalWallet;
|
|
} else {
|
|
return shouldDisplayTOTP2FAForNonContact;
|
|
}
|
|
}
|
|
|
|
bool shouldDisplayTotp() {
|
|
List<bool> conditionsList = [];
|
|
|
|
for (var output in outputs) {
|
|
final show = checkThroughChecksToDisplayTOTP(output.extractedAddress);
|
|
conditionsList.add(show);
|
|
}
|
|
|
|
return conditionsList.contains(true);
|
|
}
|
|
|
|
final _ocpService = OpenCryptoPayService();
|
|
|
|
@observable
|
|
OpenCryptoPayRequest? ocpRequest;
|
|
|
|
@action
|
|
Future<void> dismissTransaction() async {
|
|
state = InitialExecutionState();
|
|
if (ocpRequest != null) {
|
|
clearOutputs();
|
|
_ocpService.cancelOpenCryptoPayRequest(ocpRequest!);
|
|
ocpRequest = null;
|
|
}
|
|
}
|
|
|
|
@action
|
|
Future<PendingTransaction?> createOpenCryptoPayTransaction(String uri) async {
|
|
state = IsExecutingState();
|
|
|
|
try {
|
|
final originalOCPRequest = await _ocpService.getOpenCryptoPayInvoice(uri.toString());
|
|
final paymentUri = await _ocpService.getOpenCryptoPayAddress(
|
|
originalOCPRequest,
|
|
selectedCryptoCurrency,
|
|
);
|
|
|
|
ocpRequest = originalOCPRequest;
|
|
|
|
final paymentRequest = PaymentRequest.fromUri(paymentUri);
|
|
clearOutputs();
|
|
|
|
outputs.first.address = paymentRequest.address;
|
|
outputs.first.parsedAddress =
|
|
ParsedAddress(addresses: [paymentRequest.address], name: ocpRequest!.receiverName);
|
|
outputs.first.setCryptoAmount(paymentRequest.amount);
|
|
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;
|
|
}
|
|
|
|
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;
|
|
|
|
@action
|
|
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) {
|
|
_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;
|
|
|
|
|
|
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;
|
|
|
|
if (routerTo == null || routerTo.isEmpty) {
|
|
state = FailureState('Invalid router address');
|
|
return null;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
// 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,
|
|
);
|
|
|
|
state = ExecutedSuccessfullyState();
|
|
return pendingTransaction;
|
|
}
|
|
|
|
state = FailureState('Unsupported Swaps.xyz transaction type');
|
|
return null;
|
|
} catch (e, s) {
|
|
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) {
|
|
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;
|
|
} catch (e, s) {
|
|
printV('Jupiter swap error: $e\n$s');
|
|
throw Exception('Failed to process Jupiter swap: $e');
|
|
}
|
|
}
|
|
}
|
|
|
|
// Regular flow
|
|
|
|
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) {
|
|
throw Exception("THORChain does not support more than 10 outputs");
|
|
}
|
|
|
|
if (_hasTaprootInput(pendingTransaction)) {
|
|
throw Exception("THORChain does not support Taproot addresses");
|
|
}
|
|
}
|
|
|
|
if (wallet.type == WalletType.bitcoin) {
|
|
final updatedOutputs = bitcoin!.updateOutputs(pendingTransaction!, outputs);
|
|
|
|
if (outputs.length == updatedOutputs.length) {
|
|
outputs.replaceRange(0, outputs.length, updatedOutputs);
|
|
}
|
|
}
|
|
|
|
state = ExecutedSuccessfullyState();
|
|
return pendingTransaction;
|
|
} catch (e) {
|
|
_ledgerTxStateTimer?.cancel();
|
|
// if (e is LedgerException) {
|
|
// final errorCode = e.errorCode.toRadixString(16);
|
|
// final fallbackMsg =
|
|
// e.message.isNotEmpty ? e.message : "Unexpected Ledger Error Code: $errorCode";
|
|
// final errorMsg = ledgerViewModel!.interpretErrorCode(errorCode) ?? fallbackMsg;
|
|
//
|
|
// state = FailureState(errorMsg);
|
|
// } else {
|
|
state = FailureState(translateErrorMessage(e, wallet.type, wallet.currency));
|
|
// }
|
|
}
|
|
return null;
|
|
}
|
|
|
|
@action
|
|
Future<void> replaceByFee(TransactionInfo tx, String newFee) async {
|
|
state = IsExecutingState();
|
|
|
|
try {
|
|
final isSufficient = await bitcoin!.isChangeSufficientForFee(wallet, tx.id, newFee);
|
|
|
|
if (!isSufficient) {
|
|
state = AwaitingConfirmationState(
|
|
title: S.current.confirm_fee_deduction,
|
|
message: S.current.confirm_fee_deduction_content,
|
|
onConfirm: () async => await _executeReplaceByFee(tx, newFee),
|
|
onCancel: () => state = FailureState('Insufficient change for fee'));
|
|
} else {
|
|
await _executeReplaceByFee(tx, newFee);
|
|
}
|
|
} catch (e) {
|
|
state = FailureState(e.toString());
|
|
}
|
|
}
|
|
|
|
Future<void> _executeReplaceByFee(TransactionInfo tx, String newFee) async {
|
|
clearOutputs();
|
|
final output = outputs.first;
|
|
output.address = tx.outputAddresses?.first ?? '';
|
|
|
|
try {
|
|
pendingTransaction = await bitcoin!.replaceByFee(wallet, tx.id, newFee);
|
|
state = ExecutedSuccessfullyState();
|
|
} catch (e) {
|
|
state = FailureState(e.toString());
|
|
}
|
|
}
|
|
|
|
Future<void> _handleOcpRequest() async {
|
|
if (OpenCryptoPayService.requiresClientCommit(selectedCryptoCurrency)) {
|
|
await pendingTransaction!.commit();
|
|
}
|
|
|
|
await _ocpService.commitOpenCryptoPayRequest(
|
|
pendingTransaction!.hex,
|
|
txId: pendingTransaction!.id,
|
|
request: ocpRequest!,
|
|
asset: selectedCryptoCurrency,
|
|
);
|
|
}
|
|
|
|
Future<void> _commitUR(BuildContext context) async {
|
|
final urstr = await pendingTransaction!.commitUR();
|
|
final result = await Navigator.of(context).pushNamed(Routes.urqrAnimatedPage, arguments: urstr);
|
|
if (result == null) {
|
|
throw "Canceled by user";
|
|
}
|
|
}
|
|
|
|
@action
|
|
Future<void> commitTransaction(BuildContext context) async {
|
|
if (pendingTransaction == null) {
|
|
throw Exception("Pending transaction doesn't exist. It should not be happened.");
|
|
}
|
|
|
|
try {
|
|
state = TransactionCommitting();
|
|
|
|
if (ocpRequest != null) {
|
|
await _handleOcpRequest();
|
|
} else if (pendingTransaction!.shouldCommitUR()) {
|
|
await _commitUR(context);
|
|
} else {
|
|
await pendingTransaction!.commit();
|
|
}
|
|
|
|
state = TransactionCommitted();
|
|
|
|
await _updateSolanaTrade(signature: pendingTransaction!.id, isSuccess: true);
|
|
|
|
if (walletType == WalletType.solana) {
|
|
Future.delayed(Duration(seconds: 1), () async {
|
|
try {
|
|
await solana!.pollForTransaction(
|
|
wallet,
|
|
pendingTransaction!.id,
|
|
initialDelay: const Duration(seconds: 1),
|
|
maxRetries: 5,
|
|
);
|
|
} catch (e) {
|
|
printV('Failed to poll for transaction: $e');
|
|
}
|
|
});
|
|
|
|
// Update balances for currencies involved in swap
|
|
if (_currentTrade != null) {
|
|
Future.delayed(Duration(seconds: 2), () async {
|
|
try {
|
|
final tokenMints = <String>[];
|
|
|
|
// Extract from currency mint (skip native SOL)
|
|
if (_currentTrade!.from != null && _currentTrade!.from != CryptoCurrency.sol) {
|
|
try {
|
|
final fromMint = solana!.getTokenAddress(_currentTrade!.from!);
|
|
tokenMints.add(fromMint);
|
|
} catch (e) {
|
|
printV('Error getting from currency mint: $e');
|
|
}
|
|
}
|
|
|
|
// Extract to currency mint (skip native SOL)
|
|
if (_currentTrade!.to != null && _currentTrade!.to != CryptoCurrency.sol) {
|
|
try {
|
|
final toMint = solana!.getTokenAddress(_currentTrade!.to!);
|
|
tokenMints.add(toMint);
|
|
} catch (e) {
|
|
printV('Error getting to currency mint: $e');
|
|
}
|
|
}
|
|
|
|
if (tokenMints.isNotEmpty) {
|
|
solana!.updateTokenBalances(
|
|
wallet,
|
|
tokenMints: tokenMints,
|
|
);
|
|
|
|
// Retry after a bit more time to ensure balance is updated
|
|
Future.delayed(Duration(seconds: 2), () async {
|
|
try {
|
|
await solana!.updateTokenBalances(
|
|
wallet,
|
|
tokenMints: tokenMints,
|
|
);
|
|
} catch (e) {
|
|
printV('Error retrying balance update: $e');
|
|
}
|
|
});
|
|
}
|
|
} catch (e) {
|
|
printV('Failed to update balances after send: $e');
|
|
} finally {
|
|
_currentTrade = null;
|
|
_currentProvider = null;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// Immediate transaction update for EVM chains, Tron, and Nano
|
|
if (isEVMWallet || [WalletType.bitcoin, WalletType.solana, WalletType.tron, WalletType.nano].contains(walletType)) {
|
|
Future.delayed(Duration(seconds: 4), () async {
|
|
try {
|
|
await Future.wait([
|
|
wallet.updateTransactionsHistory(),
|
|
wallet.updateBalance() as Future<void>,
|
|
]);
|
|
} catch (e) {
|
|
printV('Failed to update transactions after send: $e');
|
|
}
|
|
});
|
|
}
|
|
|
|
if (pendingTransaction!.id.isNotEmpty) {
|
|
_addTransactionDescription();
|
|
}
|
|
final sharedPreferences = await SharedPreferences.getInstance();
|
|
await sharedPreferences.setString(PreferencesKey.backgroundSyncLastTrigger(wallet.name),
|
|
DateTime.now().add(Duration(minutes: 1)).toIso8601String());
|
|
} catch (e) {
|
|
if (e is JupiterSwapFailedException) {
|
|
await _updateSolanaTrade(signature: e.signature, isSuccess: false);
|
|
}
|
|
state = FailureState(translateErrorMessage(e, wallet.type, wallet.currency));
|
|
await _updateSolanaTrade(signature: '', isSuccess: false);
|
|
}
|
|
}
|
|
|
|
/// Update Jupiter trade with relevant details after transaction is committed
|
|
Future<void> _updateSolanaTrade({required String signature, required bool isSuccess}) async {
|
|
if (_currentTrade == null ||
|
|
_currentProvider?.title != 'Jupiter' ||
|
|
walletType != WalletType.solana) return;
|
|
|
|
_currentTrade!.txId = signature;
|
|
|
|
_currentTrade!.stateRaw = isSuccess ? TradeState.completed.raw : TradeState.failed.raw;
|
|
|
|
if (_currentTrade!.isInBox) {
|
|
await _currentTrade!.save();
|
|
}
|
|
}
|
|
|
|
@action
|
|
Future<void> updateWalletBalance() async => await wallet.updateBalance();
|
|
|
|
Future<void> _addTransactionDescription() async {
|
|
String address = outputs.fold('', (acc, value) {
|
|
return value.isParsedAddress
|
|
? '$acc${value.address}\n${value.extractedAddress}\n\n'
|
|
: '$acc${value.address}\n\n';
|
|
});
|
|
|
|
address = address.trim();
|
|
|
|
String note = outputs.fold('', (acc, value) => '$acc${value.note}\n');
|
|
|
|
note = note.trim();
|
|
|
|
TransactionInfo? tx;
|
|
if (walletType == WalletType.monero) {
|
|
await Future.delayed(Duration(milliseconds: 450));
|
|
await wallet.fetchTransactions();
|
|
final txhistory = monero!.getTransactionHistory(wallet);
|
|
tx = txhistory.transactions.values.last;
|
|
}
|
|
final descriptionKey = '${pendingTransaction!.id}_${wallet.walletAddresses.primaryAddress}';
|
|
_settingsStore.shouldSaveRecipientAddress
|
|
? await transactionDescriptionBox.add(TransactionDescription(
|
|
id: descriptionKey,
|
|
recipientAddress: address,
|
|
transactionNote: note,
|
|
transactionKey: tx?.additionalInfo["key"] as String?,
|
|
))
|
|
: await transactionDescriptionBox.add(TransactionDescription(
|
|
id: descriptionKey,
|
|
transactionNote: note,
|
|
transactionKey: tx?.additionalInfo["key"] as String?,
|
|
));
|
|
}
|
|
|
|
Object _credentials([ExchangeProvider? provider]) {
|
|
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
|
|
|
|
if (priority == null &&
|
|
![
|
|
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}');
|
|
}
|
|
|
|
switch (wallet.type) {
|
|
case WalletType.bitcoin:
|
|
case WalletType.bitcoinCash:
|
|
case WalletType.dogecoin:
|
|
return bitcoin!.createBitcoinTransactionCredentials(
|
|
outputs,
|
|
priority: priority!,
|
|
feeRate: feesViewModel.customBitcoinFeeRate,
|
|
coinTypeToSpendFrom: coinTypeToSpendFrom,
|
|
payjoinUri: _settingsStore.usePayjoin ? payjoinUri : null,
|
|
);
|
|
case WalletType.litecoin:
|
|
return bitcoin!.createBitcoinTransactionCredentials(
|
|
outputs,
|
|
priority: priority!,
|
|
feeRate: feesViewModel.customBitcoinFeeRate,
|
|
// if it's an exchange flow then disable sending from mweb coins
|
|
coinTypeToSpendFrom: provider != null ? UnspentCoinType.nonMweb : coinTypeToSpendFrom,
|
|
);
|
|
|
|
case WalletType.monero:
|
|
return monero!
|
|
.createMoneroTransactionCreationCredentials(outputs: outputs, priority: priority!);
|
|
|
|
case WalletType.wownero:
|
|
return wownero!
|
|
.createWowneroTransactionCreationCredentials(outputs: outputs, priority: priority!);
|
|
|
|
case WalletType.ethereum:
|
|
case WalletType.polygon:
|
|
case WalletType.base:
|
|
case WalletType.arbitrum:
|
|
case WalletType.bsc:
|
|
return evm!.createEVMTransactionCredentials(
|
|
outputs,
|
|
priority: priority,
|
|
currency: selectedCryptoCurrency,
|
|
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
|
|
? _settingsStore.useBlinkProtection
|
|
: false,
|
|
);
|
|
case WalletType.nano:
|
|
return nano!.createNanoTransactionCredentials(outputs);
|
|
case WalletType.solana:
|
|
return solana!
|
|
.createSolanaTransactionCredentials(outputs, currency: selectedCryptoCurrency);
|
|
case WalletType.tron:
|
|
return tron!.createTronTransactionCredentials(outputs, currency: selectedCryptoCurrency);
|
|
case WalletType.zano:
|
|
return zano!.createZanoTransactionCredentials(
|
|
outputs: outputs, priority: priority!, currency: selectedCryptoCurrency);
|
|
case WalletType.decred:
|
|
this.coinTypeToSpendFrom = UnspentCoinType.any;
|
|
return decred!.createDecredTransactionCredentials(outputs, priority!);
|
|
case WalletType.zcash:
|
|
return zcash!.createZcashTransactionCredentials(
|
|
outputs,
|
|
currency: selectedCryptoCurrency,
|
|
// priority: priority,
|
|
);
|
|
default:
|
|
throw Exception('Unexpected wallet type: ${wallet.type} for send');
|
|
}
|
|
}
|
|
|
|
bool _isEqualCurrency(String currency) =>
|
|
wallet.balance.keys.any((e) => currency.toLowerCase() == e.title.toLowerCase());
|
|
|
|
void onClose() => _settingsStore.fiatCurrency = fiatFromSettings;
|
|
|
|
@action
|
|
FiatCurrency setFiatCurrency(FiatCurrency fiat) {
|
|
_settingsStore.fiatCurrency = fiat;
|
|
return fiat;
|
|
}
|
|
|
|
@action
|
|
void setSelectedCryptoCurrency(String cryptoCurrency) {
|
|
try {
|
|
selectedCryptoCurrency = wallet.balance.keys
|
|
.firstWhere((e) => cryptoCurrency.toLowerCase() == e.title.toLowerCase());
|
|
} catch (e) {
|
|
selectedCryptoCurrency = wallet.currency;
|
|
}
|
|
}
|
|
|
|
@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 (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,
|
|
),
|
|
);
|
|
}
|
|
}
|
|
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,
|
|
CryptoCurrency currency,
|
|
) {
|
|
String errorMessage = error.toString();
|
|
|
|
if (walletType == WalletType.solana) {
|
|
if (errorMessage.contains('insufficient lamports')) {
|
|
double solValueNeeded = 0.0;
|
|
|
|
// Regular expression to match the number after "need". This shows the exact lamports the user needs to perform the transaction.
|
|
RegExp regExp = RegExp(r'need (\d+)');
|
|
|
|
// Find the match
|
|
Match? match = regExp.firstMatch(errorMessage);
|
|
|
|
if (match != null) {
|
|
String neededAmount = match.group(1)!;
|
|
final lamportsNeeded = int.tryParse(neededAmount);
|
|
|
|
// 5000 lamport used here is the constant for sending a transaction on solana
|
|
int lamportsPerSol = 1000000000;
|
|
|
|
solValueNeeded =
|
|
lamportsNeeded != null ? ((lamportsNeeded + 5000) / lamportsPerSol) : 0.0;
|
|
return S.current.insufficient_lamports(solValueNeeded.toString());
|
|
} else {
|
|
return S.current.insufficient_lamport_for_tx;
|
|
}
|
|
}
|
|
|
|
if (error is SignNativeTokenTransactionRentException) {
|
|
return S.current.solana_sign_native_transaction_rent_exception;
|
|
}
|
|
|
|
if (error is CreateAssociatedTokenAccountException) {
|
|
return "${S.current.solana_create_associated_token_account_exception} ${S.current.added_message_for_ata_error}";
|
|
}
|
|
|
|
if (error is SignSPLTokenTransactionRentException) {
|
|
return S.current.solana_sign_spl_token_transaction_rent_exception;
|
|
}
|
|
|
|
if (error is NoAssociatedTokenAccountException) {
|
|
return S.current.solana_no_associated_token_account_exception;
|
|
}
|
|
|
|
if (errorMessage.contains('found no record of a prior credit')) {
|
|
return S.current.insufficient_funds_for_tx;
|
|
}
|
|
|
|
if (errorMessage.contains('insufficient funds for rent') &&
|
|
errorMessage.contains('Transaction simulation failed') &&
|
|
errorMessage.contains('account_index')) {
|
|
final accountIndexMatch = RegExp(r'account_index: (\d+)').firstMatch(errorMessage);
|
|
if (accountIndexMatch != null) {
|
|
return int.parse(accountIndexMatch.group(1)!) == 0
|
|
? S.current.insufficientFundsForRentError
|
|
: S.current.insufficientFundsForRentErrorReceiver;
|
|
}
|
|
}
|
|
|
|
if (errorMessage.contains('invalid account data')) {
|
|
return S.current.solana_invalid_data_message;
|
|
}
|
|
|
|
if (errorMessage.contains('Blockhash not found') ||
|
|
errorMessage.contains('BlockhashNotFound') ||
|
|
errorMessage.contains('BlockhashMNotFound')) {
|
|
return 'Transaction failed because its recent blockhash expired. '
|
|
'Please retry your send; if this keeps happening, try again in '
|
|
'a few seconds or switch to a different Solana node.';
|
|
}
|
|
|
|
return errorMessage;
|
|
}
|
|
if (isEVMWallet || walletType == WalletType.haven) {
|
|
if (errorMessage.contains('gas required exceeds allowance')) {
|
|
return S.current.gas_exceeds_allowance;
|
|
}
|
|
|
|
if (errorMessage.contains('insufficient funds')) {
|
|
final feeCurrency = switch (walletType) {
|
|
WalletType.bsc => "BNB",
|
|
WalletType.polygon => "POL",
|
|
_ => "ETH",
|
|
};
|
|
|
|
final parsedErrorMessageResult =
|
|
EVMTransactionErrorFeesHandler.parseEthereumFeesErrorMessage(
|
|
errorMessage,
|
|
_fiatConversationStore.prices[currency] ?? 0.0,
|
|
);
|
|
|
|
// Handle generic insufficient funds error (no specific values available)
|
|
if (parsedErrorMessageResult.error == 'generic_insufficient_funds') {
|
|
return S.current.insufficient_funds_for_tx;
|
|
}
|
|
|
|
// Handle parsing errors (couldn't parse the error message)
|
|
if (parsedErrorMessageResult.error != null) {
|
|
return S.current.insufficient_funds_for_tx;
|
|
}
|
|
|
|
// Handle successfully parsed errors with specific values
|
|
return '''${S.current.insufficient_funds_for_tx} \n\n'''
|
|
'''${S.current.balance}: ${parsedErrorMessageResult.balanceEth} ${feeCurrency} (${parsedErrorMessageResult.balanceUsd} ${fiatFromSettings.name})\n\n'''
|
|
'''${S.current.transaction_cost}: ${parsedErrorMessageResult.txCostEth} ${feeCurrency} (${parsedErrorMessageResult.txCostUsd} ${fiatFromSettings.name})\n\n'''
|
|
'''${S.current.overshot}: ${parsedErrorMessageResult.overshotEth} ${feeCurrency} (${parsedErrorMessageResult.overshotUsd} ${fiatFromSettings.name})''';
|
|
}
|
|
|
|
if (errorMessage.contains('max fee per gas less than block base fee')) {
|
|
return S.current.tx_retry_message;
|
|
}
|
|
|
|
return errorMessage;
|
|
}
|
|
|
|
if (walletType == WalletType.tron) {
|
|
if (errorMessage.contains('balance is not sufficient')) {
|
|
return S.current.do_not_have_enough_gas_asset(currency.toString());
|
|
}
|
|
|
|
if (errorMessage.contains('Transaction expired')) {
|
|
return S.current.tx_retry_message;
|
|
}
|
|
}
|
|
|
|
if (error is TransactionWrongBalanceException) {
|
|
if (error.amount != null)
|
|
return S.current
|
|
.tx_wrong_balance_with_amount_exception(currency.toString(), error.amount.toString());
|
|
|
|
return S.current.tx_wrong_balance_exception(currency.toString());
|
|
}
|
|
if (error is TransactionNoInputsException) {
|
|
return S.current.tx_not_enough_inputs_exception;
|
|
}
|
|
if (error is TransactionNoFeeException) {
|
|
return S.current.tx_zero_fee_exception;
|
|
}
|
|
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;
|
|
}
|
|
return "${S.current.tx_commit_failed}\nsupport@cakewallet.com${error.errorMessage != null ? "\n\n${error.errorMessage}" : ""}";
|
|
}
|
|
if (error is TransactionCommitFailedDustChange) {
|
|
return S.current.tx_rejected_dust_change;
|
|
}
|
|
if (error is TransactionCommitFailedDustOutput) {
|
|
return S.current.tx_rejected_dust_output;
|
|
}
|
|
if (error is TransactionCommitFailedDustOutputSendAll) {
|
|
return S.current.tx_rejected_dust_output_send_all;
|
|
}
|
|
if (error is TransactionCommitFailedVoutNegative) {
|
|
return S.current.tx_rejected_vout_negative;
|
|
}
|
|
if (error is TransactionCommitFailedBIP68Final) {
|
|
return S.current.tx_rejected_bip68_final;
|
|
}
|
|
if (error is TransactionCommitFailedLessThanMin) {
|
|
return S.current.fee_less_than_min;
|
|
}
|
|
if (error is TransactionNoDustOnChangeException) {
|
|
return S.current.tx_commit_exception_no_dust_on_change(error.min, error.max);
|
|
}
|
|
if (error is TransactionInputNotSupported) {
|
|
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);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
@computed
|
|
bool get usePayjoin => _settingsStore.usePayjoin;
|
|
|
|
@observable
|
|
String? payjoinUri;
|
|
|
|
@action
|
|
Future<void> fetchTokenForContractAddress(String contractAddress) async {
|
|
final token = await TokenUtilities.findTokenByAddress(
|
|
walletType: wallet.type,
|
|
address: contractAddress,
|
|
);
|
|
|
|
if (token != null) {
|
|
selectedCryptoCurrency = token;
|
|
}
|
|
}
|
|
|
|
String _decodeMethodSelector(String s) =>
|
|
(s.startsWith('0x') && s.length >= 10) ? s.substring(0, 10) : '';
|
|
}
|