CW-1250: Refactor L2 Chains Code (#2677)

* feat(evm): add ChainConfig model and related classes

- Add ChainConfig class for immutable EVM chain configuration
- Add ChainCapabilities class for chain feature flags
- Add FeeType enum and FeeModel class for fee configuration

* feat(evm): add EvmChainRegistry for centralized chain management

- Add singleton EvmChainRegistry class with chain configuration storage
- Initialize with Ethereum, Polygon, Base, and Arbitrum chains
- Add mappings for WalletType, tag, and CAIP-2 to chainId lookups
- Provide lookup methods for chain configurations by various identifiers
- Support for querying available chains and registered chain IDs

* feat(evm): add EVMChainClientFactory and consolidate chain clients

- Create EVMChainClientFactory for creating chain-specific clients based on chainId
- Move all chain clients (EthereumClient, PolygonClient, BaseClient, ArbitrumClient) into cw_evm/lib/clients/ folder
- Refactor EVMChainClient from abstract to concrete class with default implementations
- Add default implementations for fetchTransactions, fetchInternalTransactions, and prepareSignedTransactionForSending
- Update all client classes to use super(chainId: X) constructor pattern
- Factory returns EVMChainClient directly for unregistered chains instead of throwing
- Remove dependencies on cw_ethereum, cw_polygon, cw_base, cw_arbitrum packages from pubspec.yaml
- Consolidate all EVM chain client implementations in one location for easier maintenance

* add ui for evm switcher on eth

* add inputs for evm network list edit switches

* refactor(evm): Make EVMChainWallet concrete and unify transaction classes
- Make EVMChainWallet and EVMChainWalletBase concrete classes (removed abstract)
- Implement all previously abstract methods in EVMChainWallet
- Make EVMChainTransactionInfo and EVMChainTransactionHistory concrete
- Reorganize default tokens into tokens/ folder:
- Refactor EVMChainDefaultTokens to import and use token classes from tokens/ folder
- Move clients to clients/ folder:
- Move evm_chain_formatter.dart to utils
- Update chain-specific transaction history classes to pass walletType to fromJson
- Update old wallet classes (EthereumWallet, PolygonWallet, etc.) to pass walletType
- Maintain compatibility with existing per-chain wallet classes

This refactoring enables the unified EVMChainWallet architecture while maintaining
full backward compatibility with existing per-chain wallet implementations.

* feat(evm): Add chain selection capability to EVMChainWallet
- Add selectedChainId observable field to track currently selected chain
- Add selectChain(chainId) action method to switch between EVM chains
- Add selectedChainConfig computed getter for accessing chain configuration
- Initialize selectedChainId from client.chainId in constructor
- Add _getClientForCurrentChain() helper method for future use

This enables chain switching functionality while maintaining full backward compatibility. The selectedChainId is initialized from the existing client, and all existing methods continue to work unchanged. Future increments will update methods to use selectedChainId internally.

* refactor(evm): Update client immediately on chain selection

- Update selectChain() to immediately create new client for selected chain
- Remove _getClientForCurrentChain() helper method
- Simplify all methods to use _client directly instead of helper calls
- Client is now always in sync with selectedChainId

This improves code simplicity and performance by eliminating repeated
client checks. The client is updated synchronously when selectChain()
is called, ensuring state consistency.

* featr(evm): Add unified evm proxy setup and fix chain initialization

- Add unified Evm proxy
- Add evm.dart to .gitignore for generated proxy
- Add generateEVM() to configure.dart for proxy generation
- Fix selectedChainId to initialize from registry based on walletInfo.type

Ensures selectedChainId always matches wallet type on initialization
and adds unified proxy infrastructure.

* refactor(evm): Update backward compat helpers to use registry via proxy

- Add registry helper methods to unified EVM proxy
- Update all lib/ files to use proxy instead of direct cw_evm imports
- Enforce proxy pattern: no direct imports from cw_evm in main app
- Update configure.dart to include registry methods in generated proxy

Maintains backward compatibility while centralizing chain data access
through the unified proxy pattern.

* feat(evm): Add chain selection UI to dashboard

- Add chain selection methods to DashboardViewModel (isEVMWallet,
  availableChains, currentChain, selectChain)
- Add chain dropdown widget to balance page for EVM wallets
- Dropdown shows current chain and allows switching between all
  registered EVM chains
- Only visible for EVM-compatible wallets
- Add chain selection methods to EVM proxy (getAllChains,
  getCurrentChain, selectChain)

Users can now switch between EVM chains (Ethereum, Polygon, Base,
Arbitrum) directly from the dashboard without creating separate wallets. All chain-related code follows the established proxy pattern.

* feat(evm): Add persistence for selected chain ID

- Add initialChainId parameter to EVMChainWallet constructor
- Save selectedChainId to wallet JSON in toJSON() method
- Load selectedChainId from JSON in open() method
- Handle backward compatibility: wallets without saved chain ID use
  wallet type's default chain ID
- Client is created with saved chain ID when opening wallet

Selected chain preference is now persisted across app sessions. Users will see their previously selected chain when reopening wallets.

* chore: Minor cleanup

* refactor(evm): Remove old per-chain packages, consolidate to unified cw_evm

- Delete cw_ethereum, cw_polygon, cw_base, cw_arbitrum packages
- Remove old proxy files (lib/ethereum/, lib/polygon/, lib/base/, lib/arbitrum/)
- Update all view models to use unified evm! proxy
- Move DEuro functionality to cw_evm/lib/deuro/
- Remove dependencies from pubspec.yaml and configure.dart
- Remove walletType parameter from EVM proxy methods

All EVM chains now use unified cw_evm package through single proxy interface. lib/ only depends on cw_evm, simplifying architecture and enabling easy addition of new L2 chains.

BREAKING CHANGE: Old per-chain packages removed

* refactor(evm): Update wallet handling to use unified EVM proxy

- Replace individual chain imports (Ethereum, Polygon, Base, Arbitrum) with a single EVM proxy import.
- Refactor wallet-related methods across various view models to utilize the new evm proxy for various usecases.

This change enhances code maintainability and prepares the codebase for the addition of new EVM chains.

* refactor(evm): Update model generator and enhance EVM classes

- Modify model_generator.sh to remove previous chain folders from the loop.
- Change EVMChainTransactionHistoryBase and EVMChainWalletBase classes to be abstract.
- Update import paths in configure.dart to reflect the new structure of the cw_evm package.

* add evm switcher icons to pubspec_base

* change evm switcher to sliding animation

* formatting fix

* dpi agnostic width

* feat(evm): Enhance chain handling and transaction history management

- Introduce getCurrentChainId function to EVMChainTransactionHistoryBase for dynamic transaction history file naming based on the current chain ID.
- Update EVMChainTransactionInfo to include chainId, ensuring accurate transaction data representation.
- Refactor EVMChainWalletBase to support automatic node connection and transaction history loading upon chain selection.
- Implement saveBackup and restoreWalletFilesFromBackup methods in EVMChainWalletService to manage wallet backups based on wallet type.
- Update various methods across the codebase to accommodate the new chain handling logic, improving overall functionality and user experience.

* chore: Cleanups and updates

* feat: add WalletType.evm and deprecate individual EVM chain types

Add unified WalletType.evm enum value for all EVM-compatible chains.
Deprecate old individual EVM types (ethereum, polygon, base, arbitrum)
with guidance to use WalletType.evm for new code.

Update serialization/deserialization functions to support WalletType.evm:
- serializeToInt() returns 18 for WalletType.evm
- deserializeFromInt() handles case 18
- walletTypeToString() and walletTypeToDisplayName() return 'EVM'
- cryptoCurrencyToWalletType() maps all EVM currencies to WalletType.evm

Old EVM types remain functional for backward compatibility with existing
wallets. This is the foundation for unifying EVM chain management.

* feat: update EVM detection functions to support WalletType.evm

Update all EVM detection and chain helper functions to support the unified WalletType.evm while maintaining backward compatibility with old EVM types.

All functions require chainId parameter when used with WalletType.evm, ensuring proper chain-specific behavior. Old EVM types continue to work without changes for backward compatibility.

* feat: add currency mapping support for unified EVM wallet type

- Update currency mapping to support WalletType.evm with chainId-based currency resolution.
- Override EVMChainWallet.currency getter to use selectedChainId from registry.
- Replace walletTypeToCryptoCurrency calls with wallet.currency in view models.
- Add WalletType.evm cases to switch statements and consolidate EVM transaction list item methods.
- Add explorer URL method to EVM interface

* feat: Update wallet operations with unified WalletType.evm

- Update wallet service to always create new wallets and restores with WalletType.evm, defaulting to Ethereum.
- Preserve old wallet types when opening existing wallets. Update wallet instance creation and opening logic to handle unified EVM type with chainId-based config lookup.

* Add WalletType.evm support across all switch statements
- Update all switch statements and conditionals to include WalletType.evm alongside existing EVM types.
- Add chainId-based node selection support for unified EVM wallets. - Fix redundant code in exchange view model.
- Ensure backward compatibility with old EVM wallet types.

* feat(evm): Implement chainId-based node management for WalletType.evm

- Add chainId-based node storage for unified EVM wallets, enabling separate node preferences per chain.
- Replace unsafe dynamic casts with type-safe getSelectedChainId method. Update all node retrieval and switching logic to support chainId-based selection.

* feat: Update UI components to show unified EVM wallet option

- Filter out old EVM wallet types (ethereum, polygon, base, arbitrum) from wallet creation and restore UI, showing only unified WalletType.evm option.
- Update wallet type generation to include WalletType.evm instead of individual
chain types.
- Update configure.dart to generate WalletType.evm in availableWalletTypes
- Add filtering checks to prevent old EVM types from appearing

* fix: Fix WalletType.evm support and complete remaining edge cases

Add missing WalletType.evm cases to switch statements to resolve compilation
errors. Complete remaining unification items:

- Add WalletType.evm support to node, wallet utils, and view models
- Update EVMChainDefaultTokens and EVMChainUtils to support chainId
- Fix token initialization and priority fee calculations for WalletType.evm
- Update payment view model to handle WalletType.evm with chainId

All identified edge cases from the unification plan are now complete.

* fix: Fix network switching issues for EVM wallets
- Fix null check errors when creating and restoring an EVM wallet
- Fix null check errors for balance getter when switching networks
- Fix fiat amount display for native currencies in transaction history

* refactor: Simplify EVM wallet chain selection in CryptoBalanceWidget

- Removed the old dropdown for chain selection and replaced it with a more integrated EvmSwitcher dialog.
- Updated EvmSwitcher to accept a list of available chains and handle chain selection more efficiently.
- Enhanced EvmSwitcherDataItem to include chainId for better identification of chains.
- Improved the overall UI flow for EVM wallet interactions.

* refactor: Enhance EVM wallet handling and chainId integration

- Simplified chainId checks across various components to ensure consistent handling for WalletType.evm.
- Updated EVMChainDefaultTokens and EVMChainUtils checks to allow all EVM wallets for chainId operations
- Handled backward compatibility for older wallet types in transaction info

* refactor: More enhancement and backward compatibility fixes for EVM Wallet

- Introduced a new method to retrieve cryptocurrency by chainId, improving the handling of WalletType.evm.
- Updated transaction history management to filter transactions based on the current chainId
- Refactored EVMChainTransactionInfo to accept chainId directly
- Modified utility functions in EVMChainUtils and TokenUtilities for better chainId handling

* refactor: Streamline EVM token retrieval and enhance chainId handling

* feat: Introduce comprehensive guide for adding new EVM L2 networks

- Added a detailed documentation file outlining the steps to integrate new EVM-compatible L2 networks into Cake Wallet.
- Included prerequisites, architecture overview, and a step-by-step guide covering chain configuration, native currency addition, default tokens, and node setup.
- Emphasized the unified architecture for EVM chains and backward compatibility considerations.
- Removed the outdated guide on adding new L2 networks to streamline documentation.

* feat: Reposition EVM switcher button on dashboard page

* just adding reminders for the refactoring [skip ci]

* more todos [skip ci]

* feat: enhance wallet functionality with chainId support

- Added chainId to `WalletBase` and updated currency method to use it.
- Modified EvmChainRegistry to initialize registry on call.
- Updated various components to pass chainId where necessary for currency conversions.
- Improved handling of chain IDs in wallet-related view models and UI components for better compatibility with EVM networks.

* fix: remove default chainId fallback in payment confirmation widget

* feat: Adapt anypay to new unified flow WIP

* fix: Issues with handling non evm swaps for anypay

* fixes to flow structure

* Add persistence to hidden chains on switcher

* refactor: simplify equality operator in Erc20Token class

* feat: add excluded arbutrum tokens for chainflip

* chore: Remove print statement [skip ci]

* refactor: dispaly QR image display for evm based on selected chain ID

* feat: enhance EVM wallet compatibility check for raw address input

* chore: Update doc to reflect changes [skip ci]

* feat: Integrate Blink for EVM wallets for anti-sandwich attacks.

- Add toggle in privacy settings to enable/disable
- When enabled, route all evm broadcast rpc calls via Blink

* feat: Integrate Blink for EVM wallets for anti-sandwich attacks.

- Add toggle in privacy settings to enable/disable
- When enabled, route all evm broadcast rpc calls via Blink

* feat: Integrate Blink for EVM wallets for anti-sandwich attacks.

- Add toggle in privacy settings to enable/disable
- When enabled, route all evm broadcast rpc calls via Blink

* feat: Handle same chainId scenario for pasted evm addresses

* feat: Add Blink Setting to Advanced Settings Page

* fix: Handle Blink supported chains

* fix: Fixes to evm swap

* fix: Add fallback for currency fetch

* fix: Add evm to supported list

* fix: Better handle balance errors

* fix: Update token check to use contract address comparison, resolves the usdt/usdt0 issue

* refactor: Simplify checks by cearing all tokens on chain switch, removing unnecessary currency checks

* fix: Simplify checks based from feedback on review

* fix: Exclude arbitrum from tx priority using chainId

* refactor: Handle chains not having transaction priority within refactor

* fix: Unified evm wallet fixes
- Handle switching networks while on tx history page
- Update NFTs when network is switching on listing page
- Fix arbitrum tx priority error on swap screen
- Switch check to display deuro from wallet type to chainId
- Add fallback check for getting token info for evm
- Better error message for max fee per gas less than block base fee error

* refactor: Update wallet checks from type to chainId for EVM compatibility checks

* refactor: Update eth chain utils and remove verified contract criteria in scam detection checks

* refactor: Enhance validation for deuro calls

* fix : Remove unneeded validation check for savings edit

* feat: Hide EVM chain switcher behind feature flag

* refactor: Remove EVM wallet type references and update related logic

* chore: Clean up wallet type references and remove repeated imports

* feat: Add fallback for derivation path and add arbitrum support to app scripts

* fix: NFT popup error

* fix: Transaction details fee regression

* fix: Fixes and improvements
- Add nonce parameter to transaction methods in EVM clients
- Remove brackets for create swaps
- Display contacts for selected wallettype alone
- Remove tx priorty switching for arb

* feat: Enhance Arbitrum support across swap providers

* fix: Add missing secret keys

* fix: display sending currency icon in send from external page

* refactor: Handle arbitrum edgecase for wallet list display image

* fix: Handle more cases of arbitrum image display for contact book

* exploring possible issues with tx history

* chore: switch to printV

* fix: Add an extra check for keys

* fix: Filter out eth spam transaction and modify parsing format

* fix: Handle contract decimals for sending tokens

* fix: Display proper balance error

* Update cw_evm/lib/utils/evm_chain_formatter.dart [skip ci]

---------

Co-authored-by: Robert Malikowski <malikowskirobert@gmail.com>
Co-authored-by: Omar Hatem <omarh.ismail1@gmail.com>
This commit is contained in:
David Adegoke
2026-01-16 02:45:49 +01:00
committed by GitHub
co-authored by Robert Malikowski Omar Hatem
parent 0e4855132c
commit 2a77d359f1
251 changed files with 7333 additions and 7788 deletions
@@ -2,6 +2,8 @@ import 'package:cake_wallet/entities/exchange_api_mode.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/seed_phrase_length.dart';
import 'package:cake_wallet/entities/seed_type.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:mobx/mobx.dart';
@@ -23,6 +25,18 @@ abstract class AdvancedPrivacySettingsViewModelBase with Store {
@computed
bool get disableBulletin => _settingsStore.disableBulletin;
@computed
bool get useBlinkProtection => _settingsStore.useBlinkProtection;
bool get canUseBlinkProtection {
if (!isEVMCompatibleChain(type)) return false;
// Get the chainId from the wallet type
final chainId = evm!.getChainIdByWalletType(type);
return canSupportBlinkProtection(chainId);
}
@observable
bool _addCustomNode = false;
@@ -109,6 +123,9 @@ abstract class AdvancedPrivacySettingsViewModelBase with Store {
@action
void setDisableBulletin(bool value) => _settingsStore.disableBulletin = value;
@action
void setUseBlinkProtection(bool value) => _settingsStore.useBlinkProtection = value;
@action
void toggleAddCustomNode() => _addCustomNode = !_addCustomNode;
@@ -11,7 +11,6 @@ import 'package:cake_wallet/store/settings_store.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/currency.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -34,13 +33,13 @@ abstract class AnonInvoicePageViewModelBase with Store {
description = '',
amount = '',
state = InitialExecutionState(),
selectedCurrency = walletTypeToCryptoCurrency(_wallet.type),
cryptoCurrency = walletTypeToCryptoCurrency(_wallet.type) {
selectedCurrency = _wallet.currency,
cryptoCurrency = _wallet.currency {
_getPreviousDonationLink();
_fetchLimits();
}
List<Currency> get currencies => [walletTypeToCryptoCurrency(_wallet.type), ...FiatCurrency.all];
List<Currency> get currencies => [_wallet.currency, ...FiatCurrency.all];
final AnonPayApi anonPayApi;
final String address;
final SettingsStore settingsStore;
@@ -85,7 +84,7 @@ abstract class AnonInvoicePageViewModelBase with Store {
if (currency is CryptoCurrency) {
cryptoCurrency = currency;
} else {
cryptoCurrency = walletTypeToCryptoCurrency(_wallet.type);
cryptoCurrency = _wallet.currency;
}
_fetchLimits();
@@ -118,7 +117,7 @@ abstract class AnonInvoicePageViewModelBase with Store {
email: receipientEmail,
name: receipientName,
fiatEquivalent:
selectedCurrency is FiatCurrency ? (selectedCurrency as FiatCurrency).raw : null,
selectedCurrency is FiatCurrency ? (selectedCurrency as FiatCurrency).raw : null,
));
_anonpayInvoiceInfoSource.add(result);
@@ -178,12 +177,12 @@ abstract class AnonInvoicePageViewModelBase with Store {
String get currentWalletName => _wallet.name;
@computed
String get qrImage => getQrImage(_wallet.type);
String get qrImage => getQrImage(_wallet.type, selectedChainId: _wallet.chainId);
@action
void reset() {
selectedCurrency = walletTypeToCryptoCurrency(_wallet.type);
cryptoCurrency = walletTypeToCryptoCurrency(_wallet.type);
selectedCurrency = _wallet.currency;
cryptoCurrency = _wallet.currency;
receipientEmail = '';
receipientName = '';
description = '';
+11 -13
View File
@@ -1,9 +1,7 @@
import 'package:cake_wallet/buy/buy_provider.dart';
import 'package:cake_wallet/buy/moonpay/moonpay_provider.dart';
import 'package:cake_wallet/buy/wyre/wyre_buy_provider.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cake_wallet/store/settings_store.dart';
@@ -20,12 +18,12 @@ part 'buy_view_model.g.dart';
class BuyViewModel = BuyViewModelBase with _$BuyViewModel;
abstract class BuyViewModelBase with Store {
BuyViewModelBase(this.ordersSource, this.ordersStore, this.settingsStore,
this.buyAmountViewModel, {required this.wallet})
: isRunning = false,
isDisabled = true,
isShowProviderButtons = false,
items = <BuyItem>[] {
BuyViewModelBase(this.ordersSource, this.ordersStore, this.settingsStore, this.buyAmountViewModel,
{required this.wallet})
: isRunning = false,
isDisabled = true,
isShowProviderButtons = false,
items = <BuyItem>[] {
_fetchBuyItems();
}
@@ -57,9 +55,9 @@ abstract class BuyViewModelBase with Store {
@computed
FiatCurrency get fiatCurrency => buyAmountViewModel.fiatCurrency;
CryptoCurrency get cryptoCurrency => walletTypeToCryptoCurrency(type);
CryptoCurrency get cryptoCurrency => wallet.currency;
Future <String> fetchUrl() async {
Future<String> fetchUrl() async {
String _url = '';
try {
@@ -95,8 +93,8 @@ abstract class BuyViewModelBase with Store {
_providerList.add(WyreBuyProvider(wallet: wallet));
}
items = _providerList.map((provider) =>
BuyItem(provider: provider, buyAmountViewModel: buyAmountViewModel))
items = _providerList
.map((provider) => BuyItem(provider: provider, buyAmountViewModel: buyAmountViewModel))
.toList();
}
}
}
@@ -7,9 +7,12 @@ import 'package:cake_wallet/entities/contact_record.dart';
import 'package:cake_wallet/entities/wallet_contact.dart';
import 'package:cake_wallet/entities/wallet_list_order_types.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/utils/mobx.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/erc20_token.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
@@ -44,7 +47,10 @@ abstract class ContactListViewModelBase with Store {
walletContacts.add(WalletContact(
address.address,
name,
walletTypeToCryptoCurrency(info.type),
getCryptoCurrencyForWalletListItem(
info.type,
),
walletType: info.type,
));
}
}
@@ -56,7 +62,10 @@ abstract class ContactListViewModelBase with Store {
walletContacts.add(WalletContact(
address,
name,
walletTypeToCryptoCurrency(info.type),
getCryptoCurrencyForWalletListItem(
info.type,
),
walletType: info.type,
));
} else {
addresses.forEach((address, label) {
@@ -67,10 +76,12 @@ abstract class ContactListViewModelBase with Store {
walletContacts.add(WalletContact(
address,
name,
walletTypeToCryptoCurrency(info.type,
isTestnet: info.network == null
? false
: info.network!.toLowerCase().contains("testnet")),
getCryptoCurrencyForWalletListItem(
info.type,
isTestnet:
info.network == null ? false : info.network!.toLowerCase().contains("testnet"),
),
walletType: info.type,
));
});
}
@@ -81,7 +92,10 @@ abstract class ContactListViewModelBase with Store {
key: [WalletType.monero, WalletType.wownero, WalletType.haven].contains(info.type)
? 0
: null),
walletTypeToCryptoCurrency(info.type),
getCryptoCurrencyForWalletListItem(
info.type,
),
walletType: info.type,
));
}
}
@@ -203,7 +217,6 @@ abstract class ContactListViewModelBase with Store {
await sortGroupByType();
break;
case FilterListOrderType.Custom:
default:
reorderAccordingToContactList();
break;
}
@@ -2,6 +2,7 @@ import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/sort_balance_types.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cw_core/transaction_history.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/balance.dart';
@@ -20,8 +21,7 @@ part 'balance_view_model.g.dart';
class BalanceRecord {
const BalanceRecord(
{
required this.availableBalance,
{required this.availableBalance,
required this.additionalBalance,
required this.secondAvailableBalance,
required this.secondAdditionalBalance,
@@ -114,6 +114,9 @@ abstract class BalanceViewModelBase with Store {
wallet.type == WalletType.tron ||
wallet.type == WalletType.zano;
@computed
bool get isEVMCompatible => isEVMCompatibleChain(wallet.type);
@computed
bool get hasAccounts => wallet.type == WalletType.monero || wallet.type == WalletType.wownero;
@@ -125,7 +128,16 @@ abstract class BalanceViewModelBase with Store {
@computed
String get asset {
final typeFormatted = walletTypeToString(appStore.wallet!.type);
if (isEVMCompatibleChain(wallet.type)) {
final currentChain = evm!.getCurrentChain(wallet);
if (currentChain != null) {
return currentChain.name;
}
return walletTypeToString(wallet.type);
}
final typeFormatted = walletTypeToString(wallet.type);
switch (wallet.type) {
case WalletType.haven:
@@ -150,18 +162,15 @@ abstract class BalanceViewModelBase with Store {
@computed
String get availableBalanceLabel {
if (displayMode == BalanceDisplayMode.hiddenBalance) {
return S.current.show_balance;
}
else {
} else {
return S.current.xmr_available_balance;
}
}
@computed
String get additionalBalanceLabel {
switch (wallet.type) {
case WalletType.haven:
case WalletType.ethereum:
@@ -225,8 +234,10 @@ abstract class BalanceViewModelBase with Store {
fiatAdditionalBalance: isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
fiatAvailableBalance: isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
fiatFrozenBalance: isFiatDisabled ? '' : '',
fiatSecondAvailableBalance: isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
fiatSecondAdditionalBalance: isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
fiatSecondAvailableBalance:
isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
fiatSecondAdditionalBalance:
isFiatDisabled ? '' : '${fiatCurrency.toString()} ●●●●●',
asset: key,
formattedAssetTitle: _formatterAsset(key)));
}
@@ -395,7 +406,6 @@ abstract class BalanceViewModelBase with Store {
return balance;
}
@observable
bool isShowCard;
@@ -44,7 +44,6 @@ import 'package:cake_wallet/view_model/dashboard/transaction_list_item.dart';
import 'package:cake_wallet/view_model/settings/sync_mode.dart';
import 'package:cryptography/cryptography.dart';
import 'package:cw_core/balance.dart';
import 'package:cw_core/cake_hive.dart';
import 'package:cw_core/pathForWallet.dart';
import 'package:cw_core/sync_status.dart';
import 'package:cw_core/transaction_history.dart';
@@ -63,6 +62,8 @@ import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cake_wallet/core/trade_monitor.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/evm/evm.dart';
part 'dashboard_view_model.g.dart';
@@ -336,6 +337,26 @@ abstract class DashboardViewModelBase with Store {
bool _isTransactionDisposerCallbackRunning = false;
@action
void _reloadTransactions() {
if (wallet.type == WalletType.monero || wallet.type == WalletType.wownero) {
return; // Monero/Wownero transactions are handled separately
}
transactions.clear();
transactions.addAll(
wallet.transactionHistory.transactions.values.map(
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
key: ValueKey('${wallet.type.name}_transaction_history_item_${transaction.id}_key'),
),
),
);
}
void _transactionDisposerCallback(int _) async {
// Simple check to prevent the callback from being called multiple times in the same frame
if (_isTransactionDisposerCallbackRunning) return;
@@ -443,7 +464,10 @@ abstract class DashboardViewModelBase with Store {
@computed
List<TradeListItem> get trades =>
tradesStore.trades.where((trade) => trade.trade.walletId == wallet.id).toList();
tradesStore.trades.where((trade) {
final isSameChain = trade.trade.chainId != null ? trade.trade.chainId == wallet.chainId : true; // returning default as true here so it falls back to the default checks if there's no chainId
return trade.trade.walletId == wallet.id && isSameChain;
}).toList();
@computed
List<OrderListItem> get orders =>
@@ -566,6 +590,30 @@ abstract class DashboardViewModelBase with Store {
@computed
bool get showSilentPaymentsCard => hasSilentPayments && settingsStore.silentPaymentsCardDisplay;
@computed
bool get isEVMWallet => isEVMCompatibleChain(wallet.type);
@computed
List<ChainInfo> get availableChains {
if (!isEVMWallet) return [];
return evm!.getAllChains();
}
@computed
ChainInfo? get currentChain {
if (!isEVMWallet) return null;
return evm!.getCurrentChain(wallet);
}
@action
Future<void> selectChain(int chainId) async {
if (!isEVMWallet) return;
final node = appStore.settingsStore.getCurrentNode(wallet.type, chainId: chainId);
await evm!.selectChain(wallet, chainId, node: node);
}
final KeyService keyService;
final SharedPreferences sharedPreferences;
@@ -880,6 +928,8 @@ abstract class DashboardViewModelBase with Store {
ReactionDisposer? _transactionDisposer;
ReactionDisposer? _chainChangeDisposer;
@computed
bool get hasPowNodes => [WalletType.nano, WalletType.banano].contains(wallet.type);
@@ -925,7 +975,12 @@ abstract class DashboardViewModelBase with Store {
}
Future<void> reconnect() async {
final node = appStore.settingsStore.getCurrentNode(wallet.type);
int? chainId;
if (isEVMWallet) {
chainId = evm!.getSelectedChainId(wallet);
}
final node = appStore.settingsStore.getCurrentNode(wallet.type, chainId: chainId);
await wallet.connectToNode(node: node);
if (hasPowNodes) {
final powNode = settingsStore.getCurrentPowNode(wallet.type);
@@ -983,22 +1038,25 @@ abstract class DashboardViewModelBase with Store {
// subname = null;
subname = '';
transactions.clear();
transactions.addAll(
wallet.transactionHistory.transactions.values.map(
(transaction) => TransactionListItem(
transaction: transaction,
balanceViewModel: balanceViewModel,
settingsStore: appStore.settingsStore,
key: ValueKey('${wallet.type.name}_transaction_history_item_${transaction.id}_key'),
),
),
);
_reloadTransactions();
}
_transactionDisposer?.reaction.dispose();
if (isEVMCompatibleChain(wallet.type)) {
_chainChangeDisposer?.reaction.dispose();
_chainChangeDisposer = reaction((_) {
// Access selectedChainId through proxy to track chain changes
return evm!.getSelectedChainId(wallet);
}, (_) {
// When chain switches, reload transactions for the new chain
_reloadTransactions();
});
} else {
_chainChangeDisposer?.reaction.dispose();
_chainChangeDisposer = null;
}
_transactionDisposer = reaction((_) {
final length = appStore.wallet!.transactionHistory.transactions.length;
if (length == 0) {
@@ -1085,10 +1143,11 @@ abstract class DashboardViewModelBase with Store {
@action
void setBuiltinTor(bool value, BuildContext context) {
if (value) {
unawaited(showPopUp<bool>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
unawaited(
showPopUp<bool>(
context: context,
builder: (BuildContext context) {
return AlertWithOneAction(
alertTitle: S.of(context).tor_connection,
alertContent: S.of(context).tor_experimental,
buttonText: S.of(context).ok,
@@ -1101,13 +1160,25 @@ abstract class DashboardViewModelBase with Store {
settingsStore.currentBuiltinTor = value;
if (value) {
unawaited(ensureTorStarted(context: context).then((_) async {
if (settingsStore.currentBuiltinTor == false) return; // return when tor got disabled in the meantime;
await wallet.connectToNode(node: appStore.settingsStore.getCurrentNode(wallet.type));
if (settingsStore.currentBuiltinTor == false)
return; // return when tor got disabled in the meantime;
int? chainId;
if (isEVMWallet) {
chainId = evm!.getSelectedChainId(wallet);
}
await wallet.connectToNode(
node: appStore.settingsStore.getCurrentNode(wallet.type, chainId: chainId));
}));
} else {
unawaited(ensureTorStopped(context: context).then((_) async {
if (settingsStore.currentBuiltinTor == true) return; // return when tor got enabled in the meantime;
await wallet.connectToNode(node: appStore.settingsStore.getCurrentNode(wallet.type));
if (settingsStore.currentBuiltinTor == true)
return; // return when tor got enabled in the meantime;
int? chainId;
if (isEVMWallet) {
chainId = evm!.getSelectedChainId(wallet);
}
await wallet.connectToNode(
node: appStore.settingsStore.getCurrentNode(wallet.type, chainId: chainId));
}));
}
}
@@ -1211,7 +1282,7 @@ abstract class DashboardViewModelBase with Store {
if (tx.isReplaced == true) return ' (replaced)';
}
if (wallet.type == WalletType.ethereum && tx.evmSignatureName == 'approval')
if (wallet.chainId == 1 && tx.evmSignatureName == 'approval')
return ' (${tx.evmSignatureName})';
return '';
}
@@ -1,13 +1,10 @@
import 'dart:convert';
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/core/fiat_conversion_service.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/erc20_token_info_moralis.dart';
import 'package:cake_wallet/entities/sort_balance_types.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/store/settings_store.dart';
@@ -33,6 +30,23 @@ abstract class HomeSettingsViewModelBase with Store {
isDeletingToken = false,
isValidatingContractAddress = false {
_updateTokensList();
// React to wallet changes
reaction((_) => _balanceViewModel.wallet, (_) {
_updateTokensList();
});
reaction((_) {
final wallet = _balanceViewModel.wallet;
if (isEVMCompatibleChain(wallet.type)) {
final selectedChainId = evm!.getSelectedChainId(wallet);
final erc20Currencies = evm!.getERC20Currencies(wallet);
return '${wallet.currency.title}_${selectedChainId}_${erc20Currencies.length}';
}
return null;
}, (_) async {
await Future.delayed(const Duration(milliseconds: 200));
_updateTokensList();
});
}
final SettingsStore _settingsStore;
@@ -76,21 +90,9 @@ abstract class HomeSettingsViewModelBase with Store {
}) async {
try {
isAddingToken = true;
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
final erc20token = Erc20Token(
name: token.name,
symbol: token.title,
decimal: token.decimals,
contractAddress: contractAddress.toLowerCase(),
iconPath: token.iconPath,
isPotentialScam: token.isPotentialScam,
);
await ethereum!.addErc20Token(_balanceViewModel.wallet, erc20token);
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
final polygonToken = Erc20Token(
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
final evmToken = Erc20Token(
name: token.name,
symbol: token.title,
decimal: token.decimals,
@@ -98,30 +100,7 @@ abstract class HomeSettingsViewModelBase with Store {
iconPath: token.iconPath,
isPotentialScam: token.isPotentialScam,
);
await polygon!.addErc20Token(_balanceViewModel.wallet, polygonToken);
}
if (_balanceViewModel.wallet.type == WalletType.base) {
final baseToken = Erc20Token(
name: token.name,
symbol: token.title,
decimal: token.decimals,
contractAddress: contractAddress.toLowerCase(),
iconPath: token.iconPath,
isPotentialScam: token.isPotentialScam,
);
await base!.addErc20Token(_balanceViewModel.wallet, baseToken);
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
final arbitrumToken = Erc20Token(
name: token.name,
symbol: token.title,
decimal: token.decimals,
contractAddress: contractAddress.toLowerCase(),
iconPath: token.iconPath,
isPotentialScam: token.isPotentialScam,
);
await arbitrum!.addErc20Token(_balanceViewModel.wallet, arbitrumToken);
await evm!.addErc20Token(_balanceViewModel.wallet, evmToken);
}
if (_balanceViewModel.wallet.type == WalletType.solana) {
@@ -153,20 +132,8 @@ abstract class HomeSettingsViewModelBase with Store {
@action
bool checkIfTokenIsAlreadyAdded(String contractAddress) {
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
return ethereum!.isTokenAlreadyAdded(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
return polygon!.isTokenAlreadyAdded(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.base) {
return base!.isTokenAlreadyAdded(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
return arbitrum!.isTokenAlreadyAdded(_balanceViewModel.wallet, contractAddress);
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
return evm!.isTokenAlreadyAdded(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.solana) {
@@ -188,20 +155,8 @@ abstract class HomeSettingsViewModelBase with Store {
Future<void> deleteToken(CryptoCurrency token) async {
try {
isDeletingToken = true;
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
await ethereum!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token);
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
await polygon!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token);
}
if (_balanceViewModel.wallet.type == WalletType.base) {
await base!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token);
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
await arbitrum!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token);
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
await evm!.deleteErc20Token(_balanceViewModel.wallet, token as Erc20Token);
}
if (_balanceViewModel.wallet.type == WalletType.solana) {
@@ -237,7 +192,7 @@ abstract class HomeSettingsViewModelBase with Store {
bool isUnverifiedContract = await _isContractUnverified(
contractAddress,
chainId: getChainIdBasedOnWalletType(_balanceViewModel.wallet.type).toString(),
chainId: evm!.getSelectedChainId(_balanceViewModel.wallet).toString(),
);
final showWarningForContractAddress = isPotentialScamViaMoralis || isUnverifiedContract;
@@ -253,16 +208,10 @@ abstract class HomeSettingsViewModelBase with Store {
List<String> defaultTokenAddresses = [];
switch (_balanceViewModel.wallet.type) {
case WalletType.ethereum:
defaultTokenAddresses = ethereum!.getDefaultTokenContractAddresses();
break;
case WalletType.polygon:
defaultTokenAddresses = polygon!.getDefaultTokenContractAddresses();
break;
case WalletType.base:
defaultTokenAddresses = base!.getDefaultTokenContractAddresses();
break;
case WalletType.arbitrum:
defaultTokenAddresses = arbitrum!.getDefaultTokenContractAddresses();
defaultTokenAddresses = evm!.getDefaultTokenContractAddresses(_balanceViewModel.wallet);
break;
case WalletType.solana:
defaultTokenAddresses = solana!.getDefaultTokenContractAddresses();
@@ -323,9 +272,9 @@ abstract class HomeSettingsViewModelBase with Store {
}
// Tokens whose contract have not been verified are potentially risky tokens.
if (tokenInfo.verifiedContract == false) {
return true;
}
// if (tokenInfo.verifiedContract == false) {
// return true;
// }
// Tokens with a security score less than 40 are potentially risky, requiring caution when dealing with them.
if (tokenInfo.securityScore != null && tokenInfo.securityScore! < 40) {
@@ -391,20 +340,8 @@ abstract class HomeSettingsViewModelBase with Store {
}
Future<CryptoCurrency?> getToken(String contractAddress) async {
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
return await ethereum!.getErc20Token(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
return await polygon!.getErc20Token(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.base) {
return await base!.getErc20Token(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
return await arbitrum!.getErc20Token(_balanceViewModel.wallet, contractAddress);
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
return await evm!.getErc20Token(_balanceViewModel.wallet, contractAddress);
}
if (_balanceViewModel.wallet.type == WalletType.solana) {
@@ -438,24 +375,9 @@ abstract class HomeSettingsViewModelBase with Store {
void changeTokenAvailability(CryptoCurrency token, bool value) async {
token.enabled = value;
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
ethereum!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token);
if (!value) ethereum!.removeTokenTransactionsInHistory(_balanceViewModel.wallet, token);
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
polygon!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token);
if (!value) polygon!.removeTokenTransactionsInHistory(_balanceViewModel.wallet, token);
}
if (_balanceViewModel.wallet.type == WalletType.base) {
base!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token);
if (!value) base!.removeTokenTransactionsInHistory(_balanceViewModel.wallet, token);
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
arbitrum!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token);
if (!value) arbitrum!.removeTokenTransactionsInHistory(_balanceViewModel.wallet, token);
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
evm!.addErc20Token(_balanceViewModel.wallet, token as Erc20Token);
if (!value) evm!.removeTokenTransactionsInHistory(_balanceViewModel.wallet, token);
}
if (_balanceViewModel.wallet.type == WalletType.solana) {
@@ -495,32 +417,8 @@ abstract class HomeSettingsViewModelBase with Store {
tokens.clear();
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
tokens.addAll(ethereum!
.getERC20Currencies(_balanceViewModel.wallet)
.where((element) => _matchesSearchText(element))
.toList()
..sort(_sortFunc));
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
tokens.addAll(polygon!
.getERC20Currencies(_balanceViewModel.wallet)
.where((element) => _matchesSearchText(element))
.toList()
..sort(_sortFunc));
}
if (_balanceViewModel.wallet.type == WalletType.base) {
tokens.addAll(base!
.getERC20Currencies(_balanceViewModel.wallet)
.where((element) => _matchesSearchText(element))
.toList()
..sort(_sortFunc));
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
tokens.addAll(arbitrum!
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
tokens.addAll(evm!
.getERC20Currencies(_balanceViewModel.wallet)
.where((element) => _matchesSearchText(element))
.toList()
@@ -586,20 +484,8 @@ abstract class HomeSettingsViewModelBase with Store {
return solana!.getTokenAddress(asset);
}
if (_balanceViewModel.wallet.type == WalletType.ethereum) {
return ethereum!.getTokenAddress(asset);
}
if (_balanceViewModel.wallet.type == WalletType.polygon) {
return polygon!.getTokenAddress(asset);
}
if (_balanceViewModel.wallet.type == WalletType.base) {
return base!.getTokenAddress(asset);
}
if (_balanceViewModel.wallet.type == WalletType.arbitrum) {
return arbitrum!.getTokenAddress(asset);
if (isEVMCompatibleChain(_balanceViewModel.wallet.type)) {
return evm!.getTokenAddress(asset);
}
if (_balanceViewModel.wallet.type == WalletType.zano) {
+27 -14
View File
@@ -6,6 +6,7 @@ import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/src/screens/wallet_connect/services/bottom_sheet_service.dart';
import 'package:cake_wallet/src/screens/wallet_connect/widgets/bottom_sheet/bottom_sheet_message_display_widget.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_core/utils/proxy_wrapper.dart';
import 'package:mobx/mobx.dart';
@@ -23,7 +24,16 @@ abstract class NFTViewModelBase with Store {
: isLoading = false,
isImportNFTLoading = false,
nftAssetByWalletModels = ObservableList(),
solanaNftAssetModels = ObservableList();
solanaNftAssetModels = ObservableList() {
if (isEVMCompatibleChain(appStore.wallet!.type)) {
reaction((_) {
final wallet = appStore.wallet;
if (wallet != null) return wallet.chainId;
return null;
}, (_) => getNFTAssetByWallet());
}
}
final AppStore appStore;
final BottomSheetService bottomSheetService;
@@ -40,14 +50,14 @@ abstract class NFTViewModelBase with Store {
@action
Future<void> getNFTAssetByWallet() async {
final walletType = appStore.wallet!.type;
final wallet = appStore.wallet!;
if (!isNFTACtivatedChain(walletType)) return;
if (!isNFTACtivatedChain(wallet.type, wallet.chainId)) return;
final walletAddress = appStore.wallet!.walletInfo.address;
final walletAddress = wallet.walletInfo.address;
log('Fetching wallet NFTs for $walletAddress');
final chainName = getChainNameBasedOnWalletType(walletType);
final chainName = getChainNameBasedOnWalletType(wallet.type, chainId: wallet.chainId);
// the [chain] refers to the chain network that the nft is on
// the [format] refers to the number format type of the responses
// the [normalizedMetadata] field is a boolean that determines if
@@ -56,7 +66,7 @@ abstract class NFTViewModelBase with Store {
// the [excludeSpam] field is a boolean that determines if spam nfts be excluded from the response.
Uri uri;
if (walletType == WalletType.solana) {
if (wallet.type == WalletType.solana) {
uri = Uri.https(
'solana-gateway.moralis.io',
'/account/$chainName/$walletAddress/nft',
@@ -87,11 +97,10 @@ abstract class NFTViewModelBase with Store {
"X-API-Key": secrets.moralisApiKey,
},
);
final decodedResponse = jsonDecode(response.body) as Map<String, dynamic>;
final decodedResponse = jsonDecode(response.body);
if (walletType == WalletType.solana) {
if (wallet.type == WalletType.solana) {
final results = await Future.wait(
(decodedResponse as List<dynamic>).map(
(x) {
@@ -106,8 +115,7 @@ abstract class NFTViewModelBase with Store {
solanaNftAssetModels.addAll(results);
} else {
final result =
WalletNFTsResponseModel.fromJson(decodedResponse as Map<String, dynamic>).result ?? [];
final result = WalletNFTsResponseModel.fromJson(decodedResponse as Map<String, dynamic>).result ?? [];
nftAssetByWalletModels.clear();
@@ -139,7 +147,7 @@ abstract class NFTViewModelBase with Store {
"X-API-Key": secrets.moralisApiKey,
},
);
final decodedResponse = jsonDecode(response.body) as Map<String, dynamic>;
return SolanaNFTAssetModel.fromJson(decodedResponse);
@@ -147,7 +155,12 @@ abstract class NFTViewModelBase with Store {
@action
Future<void> importNFT(String tokenAddress, String? tokenId) async {
final chainName = getChainNameBasedOnWalletType(appStore.wallet!.type);
final walletType = appStore.wallet!.type;
int? chainId;
if (isEVMCompatibleChain(walletType)) {
chainId = evm!.getSelectedChainId(appStore.wallet!);
}
final chainName = getChainNameBasedOnWalletType(walletType, chainId: chainId);
// the [chain] refers to the chain network that the nft is on
// the [format] refers to the number format type of the responses
// the [normalizedMetadata] field is a boolean that determines if
@@ -179,7 +192,7 @@ abstract class NFTViewModelBase with Store {
"X-API-Key": secrets.moralisApiKey,
},
);
final decodedResponse = jsonDecode(response.body) as Map<String, dynamic>;
final nftAsset = NFTAssetModel.fromJson(decodedResponse);
@@ -1,12 +1,9 @@
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/entities/balance_display_mode.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/nano/nano.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/tron/tron.dart';
@@ -126,22 +123,8 @@ class TransactionListItem extends ActionListItem with Keyable {
CryptoCurrency? get assetOfTransaction {
try {
if (balanceViewModel.wallet.type == WalletType.ethereum) {
final asset = ethereum!.assetOfTransaction(balanceViewModel.wallet, transaction);
return asset;
}
if (balanceViewModel.wallet.type == WalletType.polygon) {
final asset = polygon!.assetOfTransaction(balanceViewModel.wallet, transaction);
return asset;
}
if (balanceViewModel.wallet.type == WalletType.base) {
final asset = base!.assetOfTransaction(balanceViewModel.wallet, transaction);
return asset;
}
if (balanceViewModel.wallet.type == WalletType.arbitrum) {
final asset = arbitrum!.assetOfTransaction(balanceViewModel.wallet, transaction);
if (isEVMCompatibleChain(balanceViewModel.wallet.type)) {
final asset = evm!.assetOfTransaction(balanceViewModel.wallet, transaction);
return asset;
}
@@ -184,32 +167,15 @@ class TransactionListItem extends ActionListItem with Keyable {
price: price);
break;
case WalletType.ethereum:
final asset = ethereum!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: ethereum!.formatterEthereumAmountToDouble(transaction: transaction),
price: price);
break;
case WalletType.polygon:
final asset = polygon!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: polygon!.formatterPolygonAmountToDouble(transaction: transaction),
price: price);
break;
case WalletType.base:
final asset = base!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: base!.formatterBaseAmountToDouble(transaction: transaction),
price: price);
break;
case WalletType.arbitrum:
final asset = arbitrum!.assetOfTransaction(balanceViewModel.wallet, transaction);
final asset = evm!.assetOfTransaction(balanceViewModel.wallet, transaction);
final price = balanceViewModel.fiatConvertationStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: arbitrum!.formatterArbitrumAmountToDouble(transaction: transaction),
price: price);
cryptoAmount: evm!.formatterEVMAmountToDouble(transaction: transaction),
price: price,
);
break;
case WalletType.nano:
amount = calculateFiatAmountRaw(
@@ -242,9 +208,10 @@ class TransactionListItem extends ActionListItem with Keyable {
}
final price = balanceViewModel.fiatConvertationStore.prices[asset];
amount = calculateFiatAmountRaw(
cryptoAmount: zano!.formatterIntAmountToDouble(amount: transaction.amount, currency: asset, forFee: false),
price: price);
break;
cryptoAmount: zano!.formatterIntAmountToDouble(
amount: transaction.amount, currency: asset, forFee: false),
price: price);
break;
case WalletType.decred:
amount = calculateFiatAmountRaw(
cryptoAmount: decred!.formatterDecredAmountToDouble(amount: transaction.amount),
@@ -19,7 +19,6 @@ import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/xoswap_exchange_provider.dart';
import 'package:cake_wallet/exchange/trade.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/src/screens/exchange_trade/exchange_trade_item.dart';
import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
@@ -339,7 +338,9 @@ abstract class ExchangeTradeViewModelBase with Store {
wallet.currency == CryptoCurrency.baseEth && tradeFrom?.tag == CryptoCurrency.baseEth.tag;
bool _isArbitrumToken() =>
wallet.currency == CryptoCurrency.arbEth && tradeFrom?.tag == CryptoCurrency.arbEth.tag;
wallet.currency == CryptoCurrency.arbEth &&
(tradeFrom?.tag == CryptoCurrency.arbEth.tag ||
tradeFrom?.title == CryptoCurrency.arbEth.tag); // This is to handle the CryptoCurrency.arb that doesn't have a tag but fully belongs to the Arbitrum chain
bool _isTronToken() =>
wallet.currency == CryptoCurrency.trx && tradeFrom?.tag == CryptoCurrency.trx.title;
@@ -485,5 +486,5 @@ abstract class ExchangeTradeViewModelBase with Store {
}
@computed
String get qrImage => getQrImage(wallet.type);
String get qrImage => getQrImage(wallet.type, selectedChainId: wallet.chainId);
}
@@ -27,7 +27,6 @@ import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/exolix_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/near_Intents_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/stealth_ex_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/swapsxyz_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/swaptrade_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/trocador_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/xoswap_exchange_provider.dart';
@@ -39,6 +38,7 @@ import 'package:cake_wallet/store/dashboard/fiat_conversion_store.dart';
import 'package:cake_wallet/store/dashboard/trades_store.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/store/templates/exchange_template_store.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/utils/feature_flag.dart';
import 'package:cake_wallet/utils/token_utilities.dart';
import 'package:cake_wallet/view_model/contact_list/contact_list_view_model.dart';
@@ -186,6 +186,17 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
if (isElectrumWallet) {
bitcoin!.updateFeeRates(wallet);
}
reaction((_) => wallet.currency, (_) async {
// When currency changes (e.g., EVM chain switch), update currencies
await Future.delayed(const Duration(milliseconds: 100));
receiveCurrency = wallet.currency;
depositCurrency = wallet.currency;
// Only refresh ETH tokens for EVM wallets
if (isEVMCompatibleChain(wallet.type)) {
_injectUserEthTokensIntoCurrencyLists();
}
});
}
bool useSameWalletAddress(CryptoCurrency currency) =>
@@ -332,7 +343,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
@computed
TransactionPriority get transactionPriority {
final priority = _settingsStore.priority[wallet.type];
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (priority == null) {
throw Exception('Unexpected type ${wallet.type.toString()}');
@@ -711,6 +722,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
isSendAll: isSendAllEnabled,
);
trade.walletId = wallet.id;
trade.chainId = wallet.chainId;
trade.fromWalletAddress = wallet.walletAddresses.address;
final canCreateTrade = await isCanCreateTrade(trade);
@@ -785,7 +797,7 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
WalletType.bitcoinCash,
WalletType.dogecoin,
].contains(wallet.type)) {
final priority = _settingsStore.priority[wallet.type]!;
final priority = _settingsStore.getPriority(wallet.type)!;
final amount = await bitcoin!.estimateFakeSendAllTxAmount(
wallet,
@@ -835,6 +847,12 @@ abstract class ExchangeViewModelBase extends WalletChangeListenerViewModel with
}
void _initialPairBasedOnWallet() {
if (isEVMCompatibleChain(wallet.type)) {
depositCurrency = wallet.currency;
receiveCurrency = CryptoCurrency.xmr;
return;
}
switch (wallet.type) {
case WalletType.monero:
depositCurrency = CryptoCurrency.xmr;
@@ -3,8 +3,7 @@ import 'dart:io';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/hardware_wallet/hardware_wallet_device.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
import 'package:cake_wallet/wallet_type_utils.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
@@ -89,9 +88,8 @@ abstract class BitboxViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.litecoin:
return bitcoin!.getBitboxHardwareWalletService(bitboxManager, false);
case WalletType.ethereum:
return ethereum!.getBitboxHardwareWalletService(bitboxManager);
case WalletType.polygon:
return polygon!.getBitboxHardwareWalletService(bitboxManager);
return evm!.getBitboxHardwareWalletService(bitboxManager);
default:
throw UnimplementedError();
}
@@ -104,9 +102,8 @@ abstract class BitboxViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.litecoin:
return bitcoin!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
case WalletType.ethereum:
return ethereum!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
case WalletType.polygon:
return polygon!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
return evm!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
default:
throw Exception('Unexpected wallet type: ${wallet.type}');
}
@@ -3,11 +3,10 @@ import 'dart:io';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/hardware_wallet/hardware_wallet_device.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/main.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/src/screens/connect_device/connect_device_page.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
@@ -187,9 +186,8 @@ abstract class LedgerViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.litecoin:
return bitcoin!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
case WalletType.ethereum:
return ethereum!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
case WalletType.polygon:
return polygon!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
return evm!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
default:
throw Exception('Unexpected wallet type: ${wallet.type}');
}
@@ -203,9 +201,8 @@ abstract class LedgerViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.litecoin:
return bitcoin!.getLedgerHardwareWalletService(connection, false);
case WalletType.ethereum:
return ethereum!.getLedgerHardwareWalletService(connection);
case WalletType.polygon:
return polygon!.getLedgerHardwareWalletService(connection);
return evm!.getLedgerHardwareWalletService(connection);
default:
throw UnimplementedError();
}
@@ -2,8 +2,7 @@ import 'dart:async';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/hardware_wallet/hardware_wallet_device.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
import 'package:cw_core/hardware/hardware_wallet_service.dart';
import 'package:cw_core/wallet_base.dart';
@@ -57,9 +56,8 @@ abstract class TrezorViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.litecoin:
return bitcoin!.getTrezorHardwareWalletService(trezorConnect, false);
case WalletType.ethereum:
return ethereum!.getTrezorHardwareWalletService(trezorConnect);
case WalletType.polygon:
return polygon!.getTrezorHardwareWalletService(trezorConnect);
return evm!.getTrezorHardwareWalletService(trezorConnect);
default:
throw UnimplementedError();
}
@@ -72,9 +70,8 @@ abstract class TrezorViewModelBase extends HardwareWalletViewModel with Store {
case WalletType.litecoin:
return bitcoin!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
case WalletType.ethereum:
return ethereum!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
case WalletType.polygon:
return polygon!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
return evm!.setHardwareWalletService(wallet, await getHardwareWalletService(wallet.type));
default:
throw Exception('Unexpected wallet type: ${wallet.type}');
}
@@ -2,7 +2,7 @@ import 'package:cake_wallet/core/execution_state.dart';
import 'package:cake_wallet/core/utilities.dart';
import 'package:cake_wallet/entities/calculate_fiat_amount.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.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';
@@ -13,7 +13,6 @@ import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/parse_fixed.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:mobx/mobx.dart';
part 'deuro_view_model.g.dart';
@@ -25,8 +24,8 @@ abstract class DEuroViewModelBase with Store {
static BigInt get MIN_ACCRUED_INTEREST => BigInt.parse("1000000000000");
DEuroViewModelBase(this._appStore, this.balanceViewModel, this._settingsStore,
this._fiatConversationStore,
DEuroViewModelBase(
this._appStore, this.balanceViewModel, this._settingsStore, this._fiatConversationStore,
[this.hardwareWalletViewModel]) {
reloadInterestRate();
reloadSavingsUserData();
@@ -84,7 +83,7 @@ abstract class DEuroViewModelBase with Store {
@computed
String get savingsBalanceFormated =>
ethereum!.formatterEthereumAmountToDouble(amount: savingsBalance).toStringAsFixed(6);
evm!.formatterEVMAmountToDouble(amount: savingsBalance).toStringAsFixed(6);
@computed
String get fiatSavingsBalanceFormated => _getDEuroFiatAmount(savingsBalanceFormated);
@@ -100,7 +99,7 @@ abstract class DEuroViewModelBase with Store {
@computed
String get accruedInterestFormated =>
ethereum!.formatterEthereumAmountToDouble(amount: accruedInterest).toStringAsFixed(6);
evm!.formatterEVMAmountToDouble(amount: accruedInterest).toStringAsFixed(6);
@computed
String get fiatAccruedInterestFormated => _getDEuroFiatAmount(accruedInterestFormated);
@@ -128,15 +127,15 @@ abstract class DEuroViewModelBase with Store {
@action
Future<void> reloadSavingsUserData() async {
approvedTokens = await ethereum!.getDEuroSavingsApproved(_appStore.wallet!);
savingsBalance = await ethereum!.getDEuroSavingsBalance(_appStore.wallet!);
accruedInterest = await ethereum!.getDEuroAccruedInterest(_appStore.wallet!);
approvedTokens = await evm!.getDEuroSavingsApproved(_appStore.wallet!) ?? BigInt.zero;
savingsBalance = await evm!.getDEuroSavingsBalance(_appStore.wallet!) ?? BigInt.zero;
accruedInterest = await evm!.getDEuroAccruedInterest(_appStore.wallet!) ?? BigInt.zero;
isLoading = false;
}
@action
Future<void> reloadInterestRate() async {
final interestRateRaw = await ethereum!.getDEuroInterestRate(_appStore.wallet!);
final interestRateRaw = await evm!.getDEuroInterestRate(_appStore.wallet!) ?? BigInt.zero;
interestRateFormated = (interestRateRaw / BigInt.from(10000)).toString();
}
@@ -150,8 +149,12 @@ abstract class DEuroViewModelBase with Store {
}
try {
state = TransactionCommitting();
final priority = _appStore.settingsStore.priority[WalletType.ethereum]!;
approvalTransaction = await ethereum!.enableDEuroSaving(_appStore.wallet!, priority);
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
final approval = await evm!.enableDEuroSaving(_appStore.wallet!, priority);
if (approval == null) {
throw Exception('DEuro saving not available');
}
approvalTransaction = approval;
state = InitialExecutionState();
} catch (e) {
state = FailureState(e.toString());
@@ -162,26 +165,57 @@ abstract class DEuroViewModelBase with Store {
Future<void> prepareSavingsEdit(String amountRaw, bool isAdding) async {
try {
state = TransactionCommitting();
final amount = parseFixed(amountRaw, 18);
final priority = _appStore.settingsStore.priority[WalletType.ethereum]!;
if (amountRaw.isEmpty || amountRaw.trim().isEmpty) {
throw Exception('Invalid amount: amount cannot be empty');
}
final amount = tryParseFixed(amountRaw, 18);
if (amount == BigInt.zero || amount == null) {
throw Exception('Invalid amount: amount cannot be zero');
}
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
actionType = isAdding ? DEuroActionType.deposit : DEuroActionType.withdraw;
transaction = await (isAdding
? ethereum!.addDEuroSaving(_appStore.wallet!, amount, priority)
: ethereum!.removeDEuroSaving(_appStore.wallet!, amount, priority));
final tx = await (isAdding
? evm!.addDEuroSaving(_appStore.wallet!, amount, priority)
: evm!.removeDEuroSaving(_appStore.wallet!, amount, priority));
if (tx == null) {
throw Exception('DEuro saving not available');
}
transaction = tx;
state = InitialExecutionState();
} catch (e) {
state = FailureState(e.toString());
}
}
Future<void> prepareCollectInterest() => prepareSavingsEdit(accruedInterestFormated, false);
Future<void> prepareCollectInterest() async {
if (accruedInterest < MIN_ACCRUED_INTEREST) {
state = FailureState('Accrued interest is below minimum threshold');
return;
}
final formatted = accruedInterestFormated;
if (formatted.isEmpty || formatted == '0.000000') {
state = FailureState('Invalid accrued interest amount');
return;
}
await prepareSavingsEdit(formatted, false);
}
Future<void> prepareReinvestInterest() async {
try {
state = TransactionCommitting();
actionType = DEuroActionType.reinvest;
final priority = _appStore.settingsStore.priority[WalletType.ethereum]!;
transaction = await ethereum!.reinvestDEuroInterest(_appStore.wallet!, priority);
final priority = _appStore.settingsStore.getPriority(wallet.type, chainId: wallet.chainId)!;
final tx = await evm!.reinvestDEuroInterest(_appStore.wallet!, priority);
if (tx == null) {
throw Exception('DEuro saving not available');
}
transaction = tx;
state = InitialExecutionState();
} catch (e) {
state = FailureState(e.toString());
@@ -10,6 +10,8 @@ import 'package:cw_core/node.dart';
import 'package:cake_wallet/entities/node_list.dart';
import 'package:cake_wallet/entities/default_settings_migration.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
part 'node_list_view_model.g.dart';
@@ -24,16 +26,37 @@ abstract class NodeListViewModelBase with Store {
reaction((_) => _appStore.wallet, (WalletBase? _wallet) {
_bindNodes();
});
reaction((_) {
final wallet = _appStore.wallet;
if (wallet != null && isEVMCompatibleChain(wallet.type)) {
// Access selectedChainId to track changes
return evm!.getSelectedChainId(wallet);
}
return null;
}, (_) {
_bindNodes();
});
}
@computed
Node get currentNode {
final node = settingsStore.nodes[_appStore.wallet!.type];
final wallet = _appStore.wallet!;
final walletType = wallet.type;
if (node == null) {
throw Exception('No node for wallet type: ${_appStore.wallet!.type}');
int? chainId;
if (isEVMCompatibleChain(walletType)) {
chainId = evm!.getSelectedChainId(wallet);
}
if (isEVMCompatibleChain(walletType) && chainId != null) {
return settingsStore.getCurrentNode(walletType, chainId: chainId);
}
final node = settingsStore.nodes[walletType];
if (node == null) {
throw Exception('No node for wallet type: $walletType');
}
return node;
}
@@ -56,11 +79,27 @@ abstract class NodeListViewModelBase with Store {
Future<void> reset() async {
await resetToDefault(_nodeSource);
final wallet = _appStore.wallet!;
final walletType = wallet.type;
Node node;
if (_appStore.wallet!.type == WalletType.bitcoin && _appStore.wallet!.isTestnet) {
if (walletType == WalletType.bitcoin && wallet.isTestnet) {
node = getBitcoinTestnetDefaultElectrumServer(nodes: _nodeSource)!;
} else if (isEVMCompatibleChain(walletType)) {
final chainId = evm!.getSelectedChainId(wallet);
if (chainId != null) {
final nodeWalletType = evm!.getWalletTypeByChainId(chainId);
if (nodeWalletType != null) {
node = getDefaultNode(nodes: _nodeSource, type: nodeWalletType)!;
} else {
throw Exception(
'Cannot reset node for EVM wallet: wallet type not found for chainId: $chainId');
}
} else {
throw Exception('Cannot reset node for EVM wallet: chainId is null');
}
} else {
node = getDefaultNode(nodes: _nodeSource, type: _appStore.wallet!.type)!;
node = getDefaultNode(nodes: _nodeSource, type: walletType)!;
}
await setAsCurrent(node);
@@ -70,14 +109,54 @@ abstract class NodeListViewModelBase with Store {
Future<void> delete(Node node) async => node.delete();
@action
Future<void> setAsCurrent(Node node) async => settingsStore.nodes[_appStore.wallet!.type] = node;
Future<void> setAsCurrent(Node node) async {
final wallet = _appStore.wallet!;
final walletType = wallet.type;
if (isEVMCompatibleChain(walletType)) {
final chainId = evm!.getSelectedChainId(wallet);
if (chainId != null) {
final nodeWalletType = evm!.getWalletTypeByChainId(chainId);
if (nodeWalletType != null) {
settingsStore.nodes[nodeWalletType] = node;
return;
}
}
throw Exception('Cannot set node for EVM wallet: chainId or wallet type not found');
}
// For non-EVM wallets, use the wallet type directly
settingsStore.nodes[walletType] = node;
}
@action
void _bindNodes() {
nodes.clear();
final wallet = _appStore.wallet!;
final walletType = wallet.type;
// We filter nodes by the wallet type corresponding to current chainId for EVM wallets
if (isEVMCompatibleChain(walletType)) {
final chainId = evm!.getSelectedChainId(wallet);
if (chainId != null) {
final nodeWalletType = evm!.getWalletTypeByChainId(chainId);
if (nodeWalletType != null) {
_nodeSource.bindToList(
nodes,
filter: (val) => val.type == nodeWalletType,
initialFire: true,
);
return;
}
}
// If chainId is null or wallet type not found, show no nodes
return;
}
// For non-EVM wallets, use the wallet type directly
_nodeSource.bindToList(
nodes,
filter: (val) => val.type == _appStore.wallet!.type,
filter: (val) => val.type == walletType,
initialFire: true,
);
}
+189 -32
View File
@@ -1,6 +1,8 @@
import 'dart:async';
import 'package:cake_wallet/core/universal_address_detector.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cw_core/wallet_info.dart';
@@ -14,21 +16,47 @@ part 'payment_view_model.g.dart';
class PaymentViewModel = PaymentViewModelBase with _$PaymentViewModel;
abstract class PaymentViewModelBase with Store {
PaymentViewModelBase({
required this.appStore,
});
PaymentViewModelBase({required this.appStore});
final AppStore appStore;
@observable
WalletType? detectedWalletType;
@observable
AddressDetectionResult? _lastDetectionResult;
@computed
int? get detectedChainId {
if (detectedWalletType == null) return null;
if (!isEVMCompatibleChain(detectedWalletType!)) return null;
if (_lastDetectionResult?.chainId != null) {
return _lastDetectionResult!.chainId;
}
// If detected wallet type is EVM-compatible, get chainId from detected currency
if (_lastDetectionResult?.detectedCurrency != null) {
return getChainIdByCryptoCurrency(_lastDetectionResult!.detectedCurrency!);
}
return evm!.getChainIdByWalletType(detectedWalletType!);
}
@observable
bool isProcessing = false;
@computed
WalletType get currentWalletType => appStore.wallet!.type;
@computed
int? get currentChainId {
if (!isEVMCompatibleChain(currentWalletType)) return null;
return evm!.getSelectedChainId(appStore.wallet!);
}
/// Main entry point - detect address type and check compatibility
@action
Future<PaymentFlowResult> processAddress(String addressData) async {
@@ -39,18 +67,79 @@ abstract class PaymentViewModelBase with Store {
// Detect address type
final detectionResult = UniversalAddressDetector.detectAddress(addressData);
_lastDetectionResult = detectionResult;
detectedWalletType = detectionResult.detectedWalletType;
if (!detectionResult.isValid || detectedWalletType == null) {
return PaymentFlowResult.incompatible('Unable to detect address type');
}
if (!addressData.contains(':') && _isEVMAddress(detectionResult.address)) {
return PaymentFlowResult.evmNetworkSelection(detectionResult);
final currentWallet = appStore.wallet;
if (isEVMCompatibleChain(detectedWalletType!)) {
final isRawEvmInput = !addressData.contains(':') && _isEVMAddress(detectionResult.address);
// Check if the current wallet is also EVM
if (currentWallet != null && isEVMCompatibleChain(currentWallet.type)) {
final currentChainId = evm!.getSelectedChainId(currentWallet);
final detectedChainIdValue = this.detectedChainId;
if (detectedChainIdValue != null && currentChainId != null) {
// For raw EVM address input that only defaulted to chainId 1,
// always force the EVM ecosystem bottom sheet so the user
// can pick the actual network and token.
if (isRawEvmInput && detectedChainIdValue == 1) {
final allEVMWallets = await getEVMCompatibleWallets();
final currentWalletInfo = currentWallet.walletInfo;
final otherEVMWallets =
allEVMWallets.where((w) => w.name != currentWallet.name).toList();
return PaymentFlowResult.evmNetworkSelection(
detectionResult,
compatibleWallets: otherEVMWallets,
wallet: currentWalletInfo,
);
}
if (detectedChainIdValue == currentChainId) {
return PaymentFlowResult.currentWalletCompatible();
}
final allEVMWallets = await getEVMCompatibleWallets();
final currentWalletInfo = currentWallet.walletInfo;
final otherEVMWallets =
allEVMWallets.where((w) => w.name != currentWallet.name).toList();
return PaymentFlowResult.evmNetworkSelection(
detectionResult,
compatibleWallets: otherEVMWallets,
wallet: currentWalletInfo,
);
}
}
// If the current wallet is not EVM or the chainId comparison failed
// We proceed with other checks
if (!addressData.contains(':') && _isEVMAddress(detectionResult.address)) {
final allEVMWallets = await getEVMCompatibleWallets();
return PaymentFlowResult.evmNetworkSelection(
detectionResult,
compatibleWallets: allEVMWallets,
);
}
// For EVM URIs, show network selection
final allEVMWallets = await getEVMCompatibleWallets();
return PaymentFlowResult.evmNetworkSelection(
detectionResult,
compatibleWallets: allEVMWallets,
);
}
// Check if current wallet is compatible
final currentWallet = appStore.wallet;
if (currentWallet != null && currentWallet.type == detectedWalletType) {
return PaymentFlowResult.currentWalletCompatible();
}
@@ -73,6 +162,16 @@ abstract class PaymentViewModelBase with Store {
}
}
@action
Future<void> selectChain() async {
if (detectedWalletType == null) return;
final node =
appStore.settingsStore.getCurrentNode(detectedWalletType!, chainId: detectedChainId);
await evm!.selectChain(appStore.wallet!, detectedChainId!, node: node);
}
bool _isEVMAddress(String address) {
return RegExp(r'^0x[a-fA-F0-9]{40}$').hasMatch(address);
}
@@ -80,12 +179,18 @@ abstract class PaymentViewModelBase with Store {
Future<List<WalletInfo>> getWalletsByType(WalletType walletType) async {
return (await WalletInfo.getAll()).where((wallet) => wallet.type == walletType).toList();
}
Future<List<WalletInfo>> getEVMCompatibleWallets() async {
final allWallets = await WalletInfo.getAll();
return allWallets.where((wallet) => isEVMCompatibleChain(wallet.type)).toList();
}
}
class PaymentFlowResult {
final PaymentFlowType type;
final String? message;
final WalletInfo? wallet;
final int? chainId;
final List<WalletInfo> wallets;
final WalletType? walletType;
final AddressDetectionResult? addressDetectionResult;
@@ -94,6 +199,7 @@ class PaymentFlowResult {
required this.type,
this.message,
this.wallet,
this.chainId,
this.wallets = const [],
this.walletType,
this.addressDetectionResult,
@@ -105,14 +211,24 @@ class PaymentFlowResult {
AddressDetectionResult addressDetectionResult, {
List<WalletInfo>? compatibleWallets,
WalletInfo? wallet,
}) =>
PaymentFlowResult._(
type: PaymentFlowType.evmNetworkSelection,
addressDetectionResult: addressDetectionResult,
walletType: addressDetectionResult.detectedWalletType,
wallets: compatibleWallets ?? [],
wallet: wallet,
);
}) {
int? chainId = addressDetectionResult.chainId;
if (chainId == null && addressDetectionResult.detectedCurrency != null) {
chainId = getChainIdByCryptoCurrency(addressDetectionResult.detectedCurrency!);
}
if (chainId == null && addressDetectionResult.detectedWalletType != null) {
chainId = evm!.getChainIdByWalletType(addressDetectionResult.detectedWalletType!);
}
return PaymentFlowResult._(
type: PaymentFlowType.evmNetworkSelection,
addressDetectionResult: addressDetectionResult,
walletType: addressDetectionResult.detectedWalletType,
chainId: chainId,
wallets: compatibleWallets ?? [],
wallet: wallet,
);
}
/// Current wallet is compatible
factory PaymentFlowResult.currentWalletCompatible() =>
@@ -122,29 +238,66 @@ class PaymentFlowResult {
factory PaymentFlowResult.singleWallet(
WalletInfo wallet,
AddressDetectionResult addressDetectionResult,
) =>
PaymentFlowResult._(
type: PaymentFlowType.singleWallet,
wallet: wallet,
walletType: wallet.type,
addressDetectionResult: addressDetectionResult);
) {
int? chainId = addressDetectionResult.chainId;
if (chainId == null && addressDetectionResult.detectedCurrency != null) {
chainId = getChainIdByCryptoCurrency(addressDetectionResult.detectedCurrency!);
}
if (chainId == null) {
chainId = evm!.getChainIdByWalletType(wallet.type);
}
return PaymentFlowResult._(
type: PaymentFlowType.singleWallet,
wallet: wallet,
walletType: wallet.type,
chainId: chainId,
addressDetectionResult: addressDetectionResult,
);
}
/// Multiple compatible wallets available
factory PaymentFlowResult.multipleWallets(
List<WalletInfo> wallets, AddressDetectionResult addressDetectionResult) =>
PaymentFlowResult._(
type: PaymentFlowType.multipleWallets,
wallets: wallets,
walletType: wallets.first.type,
addressDetectionResult: addressDetectionResult);
List<WalletInfo> wallets,
AddressDetectionResult addressDetectionResult,
) {
int? chainId = addressDetectionResult.chainId;
if (chainId == null && addressDetectionResult.detectedCurrency != null) {
chainId = getChainIdByCryptoCurrency(addressDetectionResult.detectedCurrency!);
}
if (chainId == null) {
chainId = evm!.getChainIdByWalletType(wallets.first.type);
}
return PaymentFlowResult._(
type: PaymentFlowType.multipleWallets,
wallets: wallets,
walletType: wallets.first.type,
addressDetectionResult: addressDetectionResult,
chainId: chainId,
);
}
/// No compatible wallets available
factory PaymentFlowResult.noWallets(
WalletType walletType, AddressDetectionResult addressDetectionResult) =>
PaymentFlowResult._(
type: PaymentFlowType.noWallets,
walletType: walletType,
addressDetectionResult: addressDetectionResult);
WalletType walletType,
AddressDetectionResult addressDetectionResult,
) {
int? chainId = addressDetectionResult.chainId;
if (chainId == null && addressDetectionResult.detectedCurrency != null) {
chainId = getChainIdByCryptoCurrency(addressDetectionResult.detectedCurrency!);
}
if (chainId == null) {
chainId = evm!.getChainIdByWalletType(walletType);
}
return PaymentFlowResult._(
type: PaymentFlowType.noWallets,
walletType: walletType,
addressDetectionResult: addressDetectionResult,
chainId: chainId,
);
}
/// Error occurred
factory PaymentFlowResult.error(String message) =>
@@ -159,6 +312,10 @@ class PaymentFlowResult {
return addressDetectionResult?.detectedCurrency;
}
if (walletType != null) {
if (isEVMCompatibleChain(walletType!)) {
return walletTypeToCryptoCurrency(walletType!, chainId: chainId);
}
return walletTypeToCryptoCurrency(walletType!);
}
return null;
@@ -85,7 +85,9 @@ class WalletRestoreFromQRCode {
try {
return AddressResolver.extractAddressByType(
raw: rawString,
type: walletTypeToCryptoCurrency(type),
type: walletTypeToCryptoCurrency(
type,
),
requireSurroundingWhitespaces: false,
);
} catch (_) {
@@ -118,7 +120,11 @@ class WalletRestoreFromQRCode {
String formattedUri = '';
WalletType? walletType = _extractWalletType(code);
final prefix = code.startsWith('xpub') ? 'xpub' : code.startsWith('zpub') ? 'zpub' : '????';
final prefix = code.startsWith('xpub')
? 'xpub'
: code.startsWith('zpub')
? 'zpub'
: '????';
if (walletType == null) {
await _specifyWalletAssets(context, "Can't determine wallet type, please pick it manually");
walletType =
@@ -129,15 +135,13 @@ class WalletRestoreFromQRCode {
formattedUri = seedPhrase != null
? '$walletType:?seed=$seedPhrase'
: code.startsWith(prefix)
? '$walletType:?$prefix=$code'
: throw Exception('Failed to determine valid seed phrase');
: code.startsWith(prefix)
? '$walletType:?$prefix=$code'
: throw Exception('Failed to determine valid seed phrase');
} else {
final index = code.indexOf(':');
final query = code.substring(index + 1).replaceAll('?', '&');
formattedUri = code.startsWith(prefix)
? '$walletType:?$prefix=$code'
:'$walletType:?$query';
formattedUri = code.startsWith(prefix) ? '$walletType:?$prefix=$code' : '$walletType:?$query';
}
final uri = Uri.parse(formattedUri);
@@ -174,8 +178,7 @@ class WalletRestoreFromQRCode {
throw Exception('Unexpected restore mode: tx_payment_id is invalid');
}
if (credentials.containsKey("xpub") ||
credentials.containsKey("zpub")) {
if (credentials.containsKey("xpub") || credentials.containsKey("zpub")) {
return WalletRestoreMode.keys;
}
+30 -31
View File
@@ -1,13 +1,10 @@
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/dogecoin/dogecoin.dart';
import 'package:cake_wallet/entities/priority_for_wallet_type.dart';
import 'package:cake_wallet/core/wallet_change_listener_view_model.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/view_model/dashboard/balance_view_model.dart';
import 'package:cw_core/crypto_currency.dart';
@@ -29,14 +26,15 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
this.balanceViewModel,
) : _settingsStore = appStore.settingsStore,
super(appStore: appStore) {
if (wallet.type == WalletType.bitcoin &&
_settingsStore.priority[wallet.type] == bitcoinTransactionPriorityCustom) {
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (wallet.type == WalletType.bitcoin && priority == bitcoinTransactionPriorityCustom) {
setTransactionPriority(bitcoinTransactionPriorityMedium);
}
final priority = _settingsStore.priority[wallet.type];
final priorities = priorityForWalletType(wallet.type);
if (!priorityForWalletType(wallet.type).contains(priority) && priorities.isNotEmpty) {
_settingsStore.priority[wallet.type] = priorities.first;
if (!priorities.contains(priority) && priorities.isNotEmpty) {
_settingsStore.setPriority(wallet.type, priorities.first, chainId: wallet.chainId);
}
}
@@ -49,13 +47,13 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
final BalanceViewModel balanceViewModel;
TransactionPriority get transactionPriority {
final priority = _settingsStore.priority[wallet.type];
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (priority == null) {
if (priority == null && hasFeesPriority) {
throw Exception('Unexpected type ${wallet.type}');
}
return priority;
return priority!;
}
int? getCustomPriorityIndex(List<TransactionPriority> priorities) {
@@ -76,6 +74,8 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
}
bool get isLowFee {
if (wallet.chainId == 42161) return false;
switch (wallet.type) {
case WalletType.monero:
case WalletType.wownero:
@@ -87,13 +87,11 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
case WalletType.litecoin:
return transactionPriority == bitcoin!.getLitecoinTransactionPrioritySlow();
case WalletType.ethereum:
return transactionPriority == ethereum!.getEthereumTransactionPrioritySlow();
case WalletType.polygon:
case WalletType.base:
return transactionPriority == evm!.getEVMTransactionPrioritySlow();
case WalletType.bitcoinCash:
return transactionPriority == bitcoinCash!.getBitcoinCashTransactionPrioritySlow();
case WalletType.polygon:
return transactionPriority == polygon!.getPolygonTransactionPrioritySlow();
case WalletType.base:
return transactionPriority == base!.getBaseTransactionPrioritySlow();
case WalletType.decred:
return transactionPriority == decred!.getDecredTransactionPrioritySlow();
case WalletType.dogecoin:
@@ -122,7 +120,8 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
wallet.type != WalletType.banano &&
wallet.type != WalletType.solana &&
wallet.type != WalletType.tron &&
wallet.type != WalletType.arbitrum;
wallet.chainId !=
42161; // Wallet type is generic for all EVM chains, so we need to check the chainId
@computed
bool get isElectrumWallet =>
@@ -140,7 +139,7 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
@action
void setTransactionPriority(TransactionPriority priority) =>
_settingsStore.priority[wallet.type] = priority;
_settingsStore.setPriority(wallet.type, priority, chainId: wallet.chainId);
bool showAlertForCustomFeeRate() {
if (wallet.type != WalletType.bitcoin || isLowFee) {
@@ -184,28 +183,28 @@ abstract class FeesViewModelBase extends WalletChangeListenerViewModel with Stor
case WalletType.haven:
case WalletType.wownero:
case WalletType.zano:
_settingsStore.priority[wallet.type] = monero!.getMoneroTransactionPriorityAutomatic();
_settingsStore.setPriority(wallet.type, monero!.getMoneroTransactionPriorityAutomatic());
break;
case WalletType.bitcoin:
_settingsStore.priority[wallet.type] = bitcoin!.getBitcoinTransactionPriorityMedium();
_settingsStore.setPriority(wallet.type, bitcoin!.getBitcoinTransactionPriorityMedium());
break;
case WalletType.litecoin:
_settingsStore.priority[wallet.type] = bitcoin!.getLitecoinTransactionPriorityMedium();
_settingsStore.setPriority(wallet.type, bitcoin!.getLitecoinTransactionPriorityMedium());
break;
case WalletType.ethereum:
_settingsStore.priority[wallet.type] = ethereum!.getDefaultTransactionPriority();
case WalletType.polygon:
case WalletType.base:
_settingsStore.setPriority(
wallet.type,
evm!.getDefaultTransactionPriority(),
chainId: wallet.chainId,
);
break;
case WalletType.bitcoinCash:
_settingsStore.priority[wallet.type] = bitcoinCash!.getDefaultTransactionPriority();
_settingsStore.setPriority(wallet.type, bitcoinCash!.getDefaultTransactionPriority());
break;
case WalletType.dogecoin:
_settingsStore.priority[wallet.type] = dogecoin!.getDefaultTransactionPriority();
break;
case WalletType.polygon:
_settingsStore.priority[wallet.type] = polygon!.getDefaultTransactionPriority();
break;
case WalletType.base:
_settingsStore.priority[wallet.type] = base!.getDefaultTransactionPriority();
_settingsStore.setPriority(wallet.type, dogecoin!.getDefaultTransactionPriority());
break;
default:
break;
+14 -40
View File
@@ -1,7 +1,4 @@
import 'dart:math';
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cake_wallet/di.dart';
@@ -10,10 +7,9 @@ import 'package:cake_wallet/entities/calculate_fiat_amount_raw.dart';
import 'package:cake_wallet/entities/contact_base.dart';
import 'package:cake_wallet/entities/parse_address_from_domain.dart';
import 'package:cake_wallet/entities/parsed_address.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/src/screens/send/widgets/extract_address_from_parsed.dart';
@@ -117,16 +113,10 @@ abstract class OutputBase with Store {
_amount = decred!.formatterStringDoubleToDecredAmount(_cryptoAmount);
break;
case WalletType.ethereum:
_amount = ethereum!.formatterEthereumParseAmount(_cryptoAmount);
break;
case WalletType.polygon:
_amount = polygon!.formatterPolygonParseAmount(_cryptoAmount);
break;
case WalletType.base:
_amount = base!.formatterBaseParseAmount(_cryptoAmount);
break;
case WalletType.arbitrum:
_amount = arbitrum!.formatterArbitrumParseAmount(_cryptoAmount);
_amount = evm!.formatterEVMParseAmount(_cryptoAmount);
break;
case WalletType.wownero:
_amount = wownero!.formatterWowneroParseAmount(amount: _cryptoAmount);
@@ -161,14 +151,15 @@ abstract class OutputBase with Store {
@action
Future<void> calculateEstimatedFee() async {
try {
final priority = _settingsStore.getPriority(_wallet.type, chainId: _wallet.chainId);
if (isEVMCompatibleChain(_wallet.type)) {
await _wallet.updateEstimatedFeesParams(_settingsStore.priority[_wallet.type]!);
await _wallet.updateEstimatedFeesParams(priority);
}
int fee = 0;
if (_settingsStore.priority[_wallet.type] != null) {
if (_settingsStore.getPriority(_wallet.type, chainId: _wallet.chainId) != null) {
fee = _wallet.calculateEstimatedFee(
_settingsStore.priority[_wallet.type]!,
_settingsStore.getPriority(_wallet.type, chainId: _wallet.chainId)!,
formattedCryptoAmount,
);
}
@@ -178,7 +169,7 @@ abstract class OutputBase with Store {
estimatedFee = monero!.formatterMoneroAmountToDouble(amount: fee).toString();
break;
case WalletType.bitcoin:
if (_settingsStore.priority[_wallet.type] ==
if (_settingsStore.getPriority(_wallet.type) ==
bitcoin!.getBitcoinTransactionPriorityCustom()) {
fee = bitcoin!.getEstimatedFeeWithFeeRate(
_wallet, _settingsStore.customBitcoinFeeRate, formattedCryptoAmount);
@@ -216,33 +207,16 @@ abstract class OutputBase with Store {
/// EVMs
case WalletType.ethereum:
String? fee = cryptoCurrencyHandler() == CryptoCurrency.eth
? ethereum!.getEthereumNativeEstimatedFee(_wallet)
: ethereum!.getEthereumERC20EstimatedFee(_wallet);
estimatedFee = formatFixed(BigInt.parse(fee ?? '0.0'), 18, fractionalDigits: 12);
break;
case WalletType.polygon:
String? fee = cryptoCurrencyHandler() == CryptoCurrency.maticpoly
? polygon!.getPolygonNativeEstimatedFee(_wallet)
: polygon!.getPolygonERC20EstimatedFee(_wallet);
estimatedFee = formatFixed(BigInt.parse(fee ?? '0.0'), 18, fractionalDigits: 12);
break;
case WalletType.base:
String? fee = cryptoCurrencyHandler() == CryptoCurrency.baseEth
? base!.getBaseNativeEstimatedFee(_wallet)
: base!.getBaseERC20EstimatedFee(_wallet);
estimatedFee = formatFixed(BigInt.parse(fee ?? '0.0'), 18, fractionalDigits: 12);
break;
case WalletType.arbitrum:
String? fee = cryptoCurrencyHandler() == CryptoCurrency.arbEth
? arbitrum!.getArbitrumNativeEstimatedFee(_wallet)
: arbitrum!.getArbitrumERC20EstimatedFee(_wallet);
final isNative = cryptoCurrencyHandler() == CryptoCurrency.eth ||
cryptoCurrencyHandler() == CryptoCurrency.maticpoly ||
cryptoCurrencyHandler() == CryptoCurrency.baseEth ||
cryptoCurrencyHandler() == CryptoCurrency.arbEth;
String? fee = isNative
? evm!.getEVMNativeEstimatedFee(_wallet)
: evm!.getEVMERC20EstimatedFee(_wallet);
estimatedFee = formatFixed(BigInt.parse(fee ?? '0.0'), 18, fractionalDigits: 12);
break;
@@ -1,3 +1,4 @@
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/view_model/send/template_view_model.dart';
import 'package:cw_core/crypto_currency.dart';
@@ -44,8 +45,12 @@ abstract class SendTemplateViewModelBase with Store {
recipients.remove(recipient);
}
AmountValidator get amountValidator =>
AmountValidator(currency: walletTypeToCryptoCurrency(_wallet.type));
AmountValidator get amountValidator => AmountValidator(
currency: walletTypeToCryptoCurrency(
_wallet.type,
chainId: _wallet.chainId,
),
);
AddressValidator get addressValidator =>
AddressValidator(type: _wallet.currency, isTestnet: _wallet.isTestnet);
@@ -54,12 +59,12 @@ abstract class SendTemplateViewModelBase with Store {
bool get hasMultiRecipient =>
_wallet.type != WalletType.haven &&
_wallet.type != WalletType.ethereum &&
_wallet.type != WalletType.polygon &&
_wallet.type != WalletType.base &&
_wallet.type != WalletType.arbitrum &&
_wallet.type != WalletType.solana &&
_wallet.type != WalletType.tron;
_wallet.type != WalletType.tron &&
_wallet.chainId != 1 &&
_wallet.chainId != 137 &&
_wallet.chainId != 8453 &&
_wallet.chainId != 42161;
@computed
CryptoCurrency get cryptoCurrency => _wallet.currency;
+66 -184
View File
@@ -1,6 +1,5 @@
import 'dart:async';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/address_validator.dart';
import 'package:cake_wallet/core/amount_validator.dart';
@@ -20,7 +19,7 @@ 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/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/exchange/provider/exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/swapsxyz_exchange_provider.dart';
import 'package:cake_wallet/exchange/provider/thorchain_exchange.provider.dart';
@@ -28,8 +27,6 @@ import 'package:cake_wallet/exchange/trade.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/polygon/polygon.dart';
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/routes.dart';
import 'package:cake_wallet/solana/solana.dart';
@@ -50,7 +47,6 @@ import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/erc20_token.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/exceptions.dart';
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/sync_status.dart';
@@ -73,7 +69,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
void onWalletChange(wallet) {
currencies = wallet.balance.keys.toList();
selectedCryptoCurrency = wallet.currency;
hasMultipleTokens = isEVMCompatibleChain(wallet.type) ||
hasMultipleTokens = isEVMWallet ||
wallet.type == WalletType.solana ||
wallet.type == WalletType.tron ||
wallet.type == WalletType.zano;
@@ -109,6 +105,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
appStore.wallet!.type == WalletType.solana ||
appStore.wallet!.type == WalletType.tron ||
appStore.wallet!.type == WalletType.zano,
selectedChainId = appStore.wallet!.chainId,
outputs = ObservableList<Output>(),
_settingsStore = appStore.settingsStore,
fiatFromSettings = appStore.settingsStore.fiatCurrency,
@@ -119,6 +116,20 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
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();
});
}
PendingTransaction? _pendingApprovalTx;
@@ -137,6 +148,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
bool get isMwebEnabled => balanceViewModel.mwebEnabled;
bool get isEVMWallet => isEVMCompatibleChain(walletType);
@action
void setShowAddressBookPopup(bool value) {
_settingsStore.showAddressBookPopupEnabled = value;
@@ -237,7 +249,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
CryptoCurrency get currency => wallet.currency;
Validator<String> amountValidator(Output output) => AmountValidator(
currency: walletTypeToCryptoCurrency(wallet.type),
currency: wallet.currency,
minValue: isSendToSilentPayments(output)
?
// TODO: get from server
@@ -266,7 +278,12 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
coinTypeToSpendFrom == UnspentCoinType.nonMweb) {
return balanceViewModel.balances.values.first.availableBalance;
}
return wallet.balance[selectedCryptoCurrency]!.formattedFullAvailableBalance;
// Handle case where balance might not be available yet (e.g., during chain switch)
final balanceForCurrency = wallet.balance[selectedCryptoCurrency];
if (balanceForCurrency == null) {
return wallet.formatCryptoAmount('0');
}
return balanceForCurrency.formattedFullAvailableBalance;
}
@action
@@ -383,6 +400,9 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
@observable
bool hasMultipleTokens;
@observable
int? selectedChainId;
@computed
List<ContactRecord> get contactsToShow => contactListViewModel.contacts
.where((element) => element.type == selectedCryptoCurrency)
@@ -540,30 +560,8 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
(trade.requiresTokenApproval ?? false) && !_isPreparedTransfer;
if (requiresTokenApproval && tokenContract.isNotEmpty && requiredAmount > BigInt.zero) {
if (walletType == WalletType.ethereum) {
final priority = _settingsStore.priority[WalletType.ethereum]!;
_pendingApprovalTx = await buildApprovalIfNeeded(
spender: routerTo!, // if API provides a specific spender, use that instead
tokenContract: tokenContract,
requiredAmount: requiredAmount,
sourceTokenDecimals: trade.sourceTokenDecimals,
);
// Build the callData tx
pendingTransaction = await ethereum!.createRawCallDataTransaction(
wallet,
routerTo,
routerData,
routerValueWei,
priority,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction; // do NOT fall back to regular flow
}
if (walletType == WalletType.polygon) {
final priority = _settingsStore.priority[WalletType.polygon]!;
if (isEVMWallet) {
final priority = _settingsStore.getPriority(walletType, chainId: selectedChainId);
_pendingApprovalTx = await buildApprovalIfNeeded(
spender: routerTo!,
tokenContract: tokenContract,
@@ -572,54 +570,15 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
);
// Build the callData tx
pendingTransaction = await polygon!.createRawCallDataTransaction(
pendingTransaction = await evm!.createRawCallDataTransaction(
wallet,
routerTo,
routerData,
routerValueWei,
priority,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction; // do NOT fall back to regular flow
}
if (walletType == WalletType.base) {
final priority = _settingsStore.priority[WalletType.base]!;
_pendingApprovalTx = await buildApprovalIfNeeded(
spender: routerTo!,
tokenContract: tokenContract,
requiredAmount: requiredAmount,
sourceTokenDecimals: trade.sourceTokenDecimals,
);
// Build the callData tx
pendingTransaction = await base!.createRawCallDataTransaction(
wallet,
routerTo,
routerData,
routerValueWei,
priority,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction; // do NOT fall back to regular flow
}
if (walletType == WalletType.arbitrum) {
_pendingApprovalTx = await buildApprovalIfNeeded(
spender: routerTo!,
tokenContract: tokenContract,
requiredAmount: requiredAmount,
sourceTokenDecimals: trade.sourceTokenDecimals,
);
// Build the callData tx
pendingTransaction = await arbitrum!.createRawCallDataTransaction(
wallet,
routerTo,
routerData,
routerValueWei,
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
? _settingsStore.useBlinkProtection
: false,
);
_isSwapsXYZCallDataTx = true;
@@ -629,51 +588,17 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
}
// No approval needed (or prepared transfer): send exactly what backend prepared
if (walletType == WalletType.ethereum) {
final priority = _settingsStore.priority[WalletType.ethereum]!;
pendingTransaction = await ethereum!.createRawCallDataTransaction(
if (isEVMWallet) {
final priority = _settingsStore.getPriority(walletType, chainId: selectedChainId);
pendingTransaction = await evm!.createRawCallDataTransaction(
wallet,
routerTo!,
routerData,
routerValueWei,
priority,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction;
}
if (walletType == WalletType.polygon) {
final priority = _settingsStore.priority[WalletType.polygon]!;
pendingTransaction = await polygon!.createRawCallDataTransaction(
wallet,
routerTo!,
routerData,
routerValueWei,
priority,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction;
}
if (walletType == WalletType.base) {
final priority = _settingsStore.priority[WalletType.base]!;
pendingTransaction = await base!.createRawCallDataTransaction(
wallet,
routerTo!,
routerData,
routerValueWei,
priority,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
return pendingTransaction;
}
if (walletType == WalletType.arbitrum) {
pendingTransaction = await arbitrum!.createRawCallDataTransaction(
wallet,
routerTo!,
routerData,
routerValueWei,
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
? _settingsStore.useBlinkProtection
: false,
);
_isSwapsXYZCallDataTx = true;
state = ExecutedSuccessfullyState();
@@ -871,7 +796,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
}
Object _credentials([ExchangeProvider? provider]) {
final priority = _settingsStore.priority[wallet.type];
final priority = _settingsStore.getPriority(wallet.type, chainId: wallet.chainId);
if (priority == null &&
wallet.type != WalletType.nano &&
@@ -879,6 +804,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
wallet.type != WalletType.solana &&
wallet.type != WalletType.tron &&
wallet.type != WalletType.arbitrum) {
// Wallet type is generic for all EVM chains, so we need to check the chainId
throw Exception('Priority is null for wallet type: ${wallet.type}');
}
@@ -911,19 +837,19 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
.createWowneroTransactionCreationCredentials(outputs: outputs, priority: priority!);
case WalletType.ethereum:
return ethereum!.createEthereumTransactionCredentials(outputs,
priority: priority!, currency: selectedCryptoCurrency);
case WalletType.polygon:
case WalletType.base:
case WalletType.arbitrum:
return evm!.createEVMTransactionCredentials(
outputs,
priority: priority,
currency: selectedCryptoCurrency,
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
? _settingsStore.useBlinkProtection
: false,
);
case WalletType.nano:
return nano!.createNanoTransactionCredentials(outputs);
case WalletType.polygon:
return polygon!.createPolygonTransactionCredentials(outputs,
priority: priority!, currency: selectedCryptoCurrency);
case WalletType.base:
return base!.createBaseTransactionCredentials(outputs,
priority: priority!, currency: selectedCryptoCurrency);
case WalletType.arbitrum:
return arbitrum!
.createArbitrumTransactionCredentials(outputs, currency: selectedCryptoCurrency);
case WalletType.solana:
return solana!
.createSolanaTransactionCredentials(outputs, currency: selectedCryptoCurrency);
@@ -1063,11 +989,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
return errorMessage;
}
if (walletType == WalletType.ethereum ||
walletType == WalletType.polygon ||
walletType == WalletType.base ||
walletType == WalletType.arbitrum ||
walletType == WalletType.haven) {
if (isEVMWallet || walletType == WalletType.haven) {
if (errorMessage.contains('gas required exceeds allowance')) {
return S.current.gas_exceeds_allowance;
}
@@ -1096,6 +1018,10 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
'''${S.current.overshot}: ${parsedErrorMessageResult.overshotEth} ${walletType == WalletType.polygon ? "POL" : "ETH"} (${parsedErrorMessageResult.overshotUsd} ${fiatFromSettings.name})''';
}
if (errorMessage.contains('max fee per gas less than block base fee')) {
return S.current.tx_retry_message;
}
return errorMessage;
}
@@ -1105,7 +1031,7 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
}
if (errorMessage.contains('Transaction expired')) {
return 'An error occurred while processing the transaction. Please retry the transaction';
return S.current.tx_retry_message;
}
}
@@ -1184,29 +1110,8 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
if (requiredAmount <= BigInt.zero) return null;
bool needsApproval = false;
if (walletType == WalletType.ethereum) {
needsApproval = await ethereum!.isApprovalRequired(
wallet,
tokenContract,
spender,
requiredAmount,
);
} else if (walletType == WalletType.polygon) {
needsApproval = await polygon!.isApprovalRequired(
wallet,
tokenContract,
spender,
requiredAmount,
);
} else if (walletType == WalletType.base) {
needsApproval = await base!.isApprovalRequired(
wallet,
tokenContract,
spender,
requiredAmount,
);
} else if (walletType == WalletType.arbitrum) {
needsApproval = await arbitrum!.isApprovalRequired(
if (isEVMWallet) {
needsApproval = await evm!.isApprovalRequired(
wallet,
tokenContract,
spender,
@@ -1227,39 +1132,16 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
),
);
if (walletType == WalletType.ethereum) {
final priority = _settingsStore.priority[WalletType.ethereum]!;
return await ethereum!.createTokenApproval(
if (isEVMWallet) {
final priority = _settingsStore.getPriority(walletType, chainId: selectedChainId);
return await evm!.createTokenApproval(
wallet,
requiredAmount,
spender,
erc20Token,
priority,
);
} else if (walletType == WalletType.polygon) {
final priority = _settingsStore.priority[WalletType.polygon]!;
return await polygon!.createTokenApproval(
wallet,
requiredAmount,
spender,
erc20Token,
priority,
);
} else if (walletType == WalletType.base) {
final priority = _settingsStore.priority[WalletType.base]!;
return await base!.createTokenApproval(
wallet,
requiredAmount,
spender,
erc20Token,
priority,
);
} else if (walletType == WalletType.arbitrum) {
return await arbitrum!.createTokenApproval(
wallet,
requiredAmount,
spender,
erc20Token,
useBlinkProtection:
canSupportBlinkProtection(selectedChainId) ? _settingsStore.useBlinkProtection : false,
);
}
@@ -15,27 +15,27 @@ import 'package:mobx/mobx.dart';
part 'other_settings_view_model.g.dart';
class OtherSettingsViewModel = OtherSettingsViewModelBase
with _$OtherSettingsViewModel;
class OtherSettingsViewModel = OtherSettingsViewModelBase with _$OtherSettingsViewModel;
abstract class OtherSettingsViewModelBase with Store {
OtherSettingsViewModelBase(this._settingsStore, this._wallet, this.sendViewModel)
: walletType = _wallet.type,
chainId = _wallet.chainId,
currentVersion = '' {
PackageInfo.fromPlatform().then(
(PackageInfo packageInfo) => currentVersion = packageInfo.version);
PackageInfo.fromPlatform()
.then((PackageInfo packageInfo) => currentVersion = packageInfo.version);
final priority = _settingsStore.priority[_wallet.type];
final priority = _settingsStore.getPriority(_wallet.type, chainId: _wallet.chainId);
final priorities = priorityForWalletType(_wallet.type);
if (!priorities.contains(priority) && priorities.isNotEmpty) {
_settingsStore.priority[_wallet.type] = priorities.first;
_settingsStore.setPriority(_wallet.type, priorities.first, chainId: _wallet.chainId);
}
}
final WalletType walletType;
final WalletBase<Balance, TransactionHistoryBase<TransactionInfo>,
TransactionInfo> _wallet;
final int? chainId;
final WalletBase<Balance, TransactionHistoryBase<TransactionInfo>, TransactionInfo> _wallet;
@observable
String currentVersion;
@@ -45,7 +45,7 @@ abstract class OtherSettingsViewModelBase with Store {
@computed
TransactionPriority get transactionPriority {
final priority = _settingsStore.priority[walletType];
final priority = _settingsStore.getPriority(walletType, chainId: chainId);
if (priority == null) {
throw Exception('Unexpected type ${walletType.toString()}');
@@ -66,8 +66,12 @@ abstract class OtherSettingsViewModelBase with Store {
].contains(_wallet.hardwareWalletType);
@computed
bool get displayTransactionPriority =>
!(changeRepresentativeEnabled || [WalletType.solana, WalletType.tron].contains(_wallet.type));
bool get displayTransactionPriority => !(changeRepresentativeEnabled ||
[
WalletType.solana,
WalletType.tron,
WalletType.arbitrum,
].contains(_wallet.type));
String getDisplayPriority(dynamic priority) {
final _priority = priority as TransactionPriority;
@@ -95,22 +99,20 @@ abstract class OtherSettingsViewModelBase with Store {
WalletType.dogecoin,
].contains(_wallet.type)) {
final rate = bitcoin!.getFeeRate(_wallet, _priority);
return bitcoin!.bitcoinTransactionPriorityWithLabel(_priority, rate,
customRate: customValue);
return bitcoin!.bitcoinTransactionPriorityWithLabel(_priority, rate, customRate: customValue);
}
return priority.toString();
}
void onDisplayPrioritySelected(TransactionPriority priority) =>
_settingsStore.priority[walletType] = priority;
_settingsStore.setPriority(walletType, priority, chainId: chainId);
void onDisplayBitcoinPrioritySelected(
TransactionPriority priority, double customValue) {
void onDisplayBitcoinPrioritySelected(TransactionPriority priority, double customValue) {
if (_wallet.type == WalletType.bitcoin) {
_settingsStore.customBitcoinFeeRate = customValue.round();
}
_settingsStore.priority[_wallet.type] = priority;
_settingsStore.setPriority(_wallet.type, priority, chainId: _wallet.chainId);
}
@action
@@ -120,13 +122,12 @@ abstract class OtherSettingsViewModelBase with Store {
}
@computed
double get customBitcoinFeeRate =>
_settingsStore.customBitcoinFeeRate.toDouble();
double get customBitcoinFeeRate => _settingsStore.customBitcoinFeeRate.toDouble();
int? get customPriorityItemIndex {
final priorities = priorityForWalletType(walletType);
final customItem = priorities.firstWhereOrNull(
(element) => element == bitcoin!.getBitcoinTransactionPriorityCustom());
final customItem = priorities
.firstWhereOrNull((element) => element == bitcoin!.getBitcoinTransactionPriorityCustom());
return customItem != null ? priorities.indexOf(customItem) : null;
}
@@ -1,12 +1,10 @@
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
import 'package:cake_wallet/entities/exchange_api_mode.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/store/settings_store.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/utils/device_info.dart';
import 'package:cw_core/balance.dart';
import 'package:cw_core/transaction_history.dart';
@@ -89,6 +87,11 @@ abstract class PrivacySettingsViewModelBase with Store {
@computed
bool get useMempoolFeeAPI => _settingsStore.useMempoolFeeAPI;
@computed
bool get useBlinkProtection => _settingsStore.useBlinkProtection;
bool get canUseBlinkProtection => canSupportBlinkProtection(_wallet.chainId);
@computed
bool get lookupTwitter => _settingsStore.lookupsTwitter;
@@ -116,13 +119,13 @@ abstract class PrivacySettingsViewModelBase with Store {
@computed
bool get usePayjoin => _settingsStore.usePayjoin;
bool get canUseEtherscan => _wallet.type == WalletType.ethereum;
bool get canUseEtherscan => _wallet.chainId == 1;
bool get canUsePolygonScan => _wallet.type == WalletType.polygon;
bool get canUsePolygonScan => _wallet.chainId == 137;
bool get canUseBaseScan => _wallet.type == WalletType.base;
bool get canUseBaseScan => _wallet.chainId == 8453;
bool get canUseArbiScan => _wallet.type == WalletType.arbitrum;
bool get canUseArbiScan => _wallet.chainId == 42161;
bool get canUseTronGrid => _wallet.type == WalletType.tron;
@@ -180,19 +183,19 @@ abstract class PrivacySettingsViewModelBase with Store {
@action
void setUseEtherscan(bool value) {
_settingsStore.useEtherscan = value;
ethereum!.updateEtherscanUsageState(_wallet, value);
evm!.updateScanProviderUsageState(_wallet, value);
}
@action
void setUsePolygonScan(bool value) {
_settingsStore.usePolygonScan = value;
polygon!.updatePolygonScanUsageState(_wallet, value);
evm!.updateScanProviderUsageState(_wallet, value);
}
@action
void setUseBaseScan(bool value) {
_settingsStore.useBaseScan = value;
base!.updateBaseScanUsageState(_wallet, value);
evm!.updateScanProviderUsageState(_wallet, value);
}
@action
@@ -204,12 +207,15 @@ abstract class PrivacySettingsViewModelBase with Store {
@action
void setUseArbiScan(bool value) {
_settingsStore.useArbiScan = value;
arbitrum!.updateArbitrumScanUsageState(_wallet, value);
evm!.updateScanProviderUsageState(_wallet, value);
}
@action
void setUseMempoolFeeAPI(bool value) => _settingsStore.useMempoolFeeAPI = value;
@action
void setUseBlinkProtection(bool value) => _settingsStore.useBlinkProtection = value;
@action
void setUsePayjoin(bool value) {
_settingsStore.usePayjoin = value;
@@ -1,11 +1,12 @@
import 'package:cake_wallet/core/address_validator.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:cw_core/currency_for_wallet_type.dart';
import 'package:cw_core/utils/print_verbose.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/transaction_info.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/entities/priority_for_wallet_type.dart';
import 'package:cake_wallet/entities/transaction_description.dart';
@@ -68,20 +69,14 @@ abstract class TransactionDetailsViewModelBase with Store {
_addHavenListItems(tx, dateFormat);
break;
case WalletType.ethereum:
_addEthereumListItems(tx, dateFormat);
case WalletType.polygon:
case WalletType.base:
case WalletType.arbitrum:
_addEVMListItems(tx, dateFormat);
break;
case WalletType.nano:
_addNanoListItems(tx, dateFormat);
break;
case WalletType.polygon:
_addPolygonListItems(tx, dateFormat);
break;
case WalletType.base:
_addBaseListItems(tx, dateFormat);
break;
case WalletType.arbitrum:
_addArbitrumListItems(tx, dateFormat);
break;
case WalletType.solana:
_addSolanaListItems(tx, dateFormat);
break;
@@ -129,10 +124,10 @@ abstract class TransactionDetailsViewModelBase with Store {
items.add(
BlockExplorerListItem(
title: S.current.view_in_block_explorer,
value: _explorerDescription(type),
value: _explorerDescription(type, wallet.chainId),
onTap: () async {
try {
final uri = Uri.parse(_explorerUrl(type, tx.txHash));
final uri = Uri.parse(_explorerUrl(type, tx.txHash, wallet.chainId));
if (await canLaunchUrl(uri)) await launchUrl(uri, mode: LaunchMode.externalApplication);
} catch (e) {}
},
@@ -175,7 +170,12 @@ abstract class TransactionDetailsViewModelBase with Store {
@observable
bool canReplaceByFee;
String _explorerUrl(WalletType type, String txId) {
String _explorerUrl(WalletType type, String txId, int? chainId) {
if (chainId != null) {
final explorerUrl = evm!.getExplorerUrlForChainId(chainId);
if (explorerUrl != null) return '$explorerUrl/tx/${txId}';
}
switch (type) {
case WalletType.monero:
return 'https://monero.com/tx/${txId}';
@@ -189,12 +189,16 @@ abstract class TransactionDetailsViewModelBase with Store {
return 'https://explorer.havenprotocol.org/search?value=${txId}';
case WalletType.ethereum:
return 'https://etherscan.io/tx/${txId}';
case WalletType.base:
return 'https://basescan.org/tx/${txId}';
case WalletType.arbitrum:
return 'https://arbiscan.io/tx/${txId}';
case WalletType.polygon:
return 'https://polygonscan.com/tx/${txId}';
case WalletType.nano:
return 'https://nanexplorer.com/nano/block/${txId}';
case WalletType.banano:
return 'https://nanexplorer.com/banano/block/${txId}';
case WalletType.polygon:
return 'https://polygonscan.com/tx/${txId}';
case WalletType.solana:
return 'https://solscan.io/tx/${txId}';
case WalletType.tron:
@@ -207,16 +211,19 @@ abstract class TransactionDetailsViewModelBase with Store {
return 'https://${wallet.isTestnet ? "testnet" : "dcrdata"}.decred.org/tx/${txId.split(':')[0]}';
case WalletType.dogecoin:
return 'https://blockchair.com/dogecoin/transaction/${txId}';
case WalletType.base:
return 'https://basescan.org/tx/${txId}';
case WalletType.arbitrum:
return 'https://arbiscan.io/tx/${txId}';
case WalletType.none:
return '';
}
}
String _explorerDescription(WalletType type) {
String _explorerDescription(WalletType type, int? chainId) {
if (chainId != null) {
final explorerUrl = evm!.getExplorerUrlForChainId(chainId, showProtocol: false);
if (explorerUrl != null) {
return S.current.view_transaction_on + explorerUrl;
}
}
switch (type) {
case WalletType.monero:
return S.current.view_transaction_on + 'Monero.com';
@@ -445,7 +452,7 @@ abstract class TransactionDetailsViewModelBase with Store {
]);
}
void _addEthereumListItems(TransactionInfo tx, DateFormat dateFormat) {
void _addEVMListItems(TransactionInfo tx, DateFormat dateFormat) {
final _items = [
StandartListItem(
title: S.current.transaction_details_transaction_id,
@@ -539,156 +546,6 @@ abstract class TransactionDetailsViewModelBase with Store {
items.addAll(_items);
}
void _addPolygonListItems(TransactionInfo tx, DateFormat dateFormat) {
final _items = [
StandartListItem(
title: S.current.transaction_details_transaction_id,
value: tx.txHash,
key: ValueKey('standard_list_item_transaction_details_id_key'),
),
StandartListItem(
title: S.current.transaction_details_date,
value: dateFormat.format(tx.date),
key: ValueKey('standard_list_item_transaction_details_date_key'),
),
StandartListItem(
title: S.current.confirmations,
value: tx.confirmations.toString(),
key: ValueKey('standard_list_item_transaction_confirmations_key'),
),
StandartListItem(
title: S.current.transaction_details_height,
value: '${tx.height}',
key: ValueKey('standard_list_item_transaction_details_height_key'),
),
StandartListItem(
title: S.current.transaction_details_amount,
value: tx.amountFormatted(),
key: ValueKey('standard_list_item_transaction_details_amount_key'),
),
if (tx.feeFormatted()?.isNotEmpty ?? false)
StandartListItem(
title: S.current.transaction_details_fee,
value: tx.feeFormatted()!,
key: ValueKey('standard_list_item_transaction_details_fee_key'),
),
if (showRecipientAddress && tx.to != null && tx.direction == TransactionDirection.outgoing)
StandartListItem(
title: S.current.transaction_details_recipient_address,
value: tx.to!,
key: ValueKey('standard_list_item_transaction_details_recipient_address_key'),
),
if (tx.direction == TransactionDirection.incoming && tx.from != null)
StandartListItem(
title: S.current.transaction_details_source_address,
value: tx.from!,
key: ValueKey('standard_list_item_transaction_details_source_address_key'),
),
];
items.addAll(_items);
}
void _addBaseListItems(TransactionInfo tx, DateFormat dateFormat) {
final _items = [
StandartListItem(
title: S.current.transaction_details_transaction_id,
value: tx.txHash,
key: ValueKey('standard_list_item_transaction_details_id_key'),
),
StandartListItem(
title: S.current.transaction_details_date,
value: dateFormat.format(tx.date),
key: ValueKey('standard_list_item_transaction_details_date_key'),
),
StandartListItem(
title: S.current.confirmations,
value: tx.confirmations.toString(),
key: ValueKey('standard_list_item_transaction_confirmations_key'),
),
StandartListItem(
title: S.current.transaction_details_height,
value: '${tx.height}',
key: ValueKey('standard_list_item_transaction_details_height_key'),
),
StandartListItem(
title: S.current.transaction_details_amount,
value: tx.amountFormatted(),
key: ValueKey('standard_list_item_transaction_details_amount_key'),
),
if (tx.feeFormatted()?.isNotEmpty ?? false)
StandartListItem(
title: S.current.transaction_details_fee,
value: tx.feeFormatted()!,
key: ValueKey('standard_list_item_transaction_details_fee_key'),
),
if (showRecipientAddress && tx.to != null && tx.direction == TransactionDirection.outgoing)
StandartListItem(
title: S.current.transaction_details_recipient_address,
value: tx.to!,
key: ValueKey('standard_list_item_transaction_details_recipient_address_key'),
),
if (tx.direction == TransactionDirection.incoming && tx.from != null)
StandartListItem(
title: S.current.transaction_details_source_address,
value: tx.from!,
key: ValueKey('standard_list_item_transaction_details_source_address_key'),
),
];
items.addAll(_items);
}
void _addArbitrumListItems(TransactionInfo tx, DateFormat dateFormat) {
final _items = [
StandartListItem(
title: S.current.transaction_details_transaction_id,
value: tx.txHash,
key: ValueKey('standard_list_item_transaction_details_id_key'),
),
StandartListItem(
title: S.current.transaction_details_date,
value: dateFormat.format(tx.date),
key: ValueKey('standard_list_item_transaction_details_date_key'),
),
StandartListItem(
title: S.current.confirmations,
value: tx.confirmations.toString(),
key: ValueKey('standard_list_item_transaction_confirmations_key'),
),
StandartListItem(
title: S.current.transaction_details_height,
value: '${tx.height}',
key: ValueKey('standard_list_item_transaction_details_height_key'),
),
StandartListItem(
title: S.current.transaction_details_amount,
value: tx.amountFormatted(),
key: ValueKey('standard_list_item_transaction_details_amount_key'),
),
if (tx.feeFormatted()?.isNotEmpty ?? false)
StandartListItem(
title: S.current.transaction_details_fee,
value: tx.feeFormatted()!,
key: ValueKey('standard_list_item_transaction_details_fee_key'),
),
if (showRecipientAddress && tx.to != null && tx.direction == TransactionDirection.outgoing)
StandartListItem(
title: S.current.transaction_details_recipient_address,
value: tx.to!,
key: ValueKey('standard_list_item_transaction_details_recipient_address_key'),
),
if (tx.direction == TransactionDirection.incoming && tx.from != null)
StandartListItem(
title: S.current.transaction_details_source_address,
value: tx.from!,
key: ValueKey('standard_list_item_transaction_details_source_address_key'),
),
];
items.addAll(_items);
}
void _addSolanaListItems(TransactionInfo tx, DateFormat dateFormat) {
final _items = [
StandartListItem(
@@ -768,8 +625,7 @@ abstract class TransactionDetailsViewModelBase with Store {
StandardPickerListItem(
key: ValueKey('standard_picker_list_item_transaction_priorities_key'),
title: S.current.estimated_new_fee,
value: bitcoin!.formatterBitcoinAmountToString(amount: newFee) +
' ${walletTypeToCryptoCurrency(wallet.type)}',
value: bitcoin!.formatterBitcoinAmountToString(amount: newFee) + ' ${wallet.currency}',
items: priorityForWalletType(wallet.type),
customValue: settingsStore.customBitcoinFeeRate.toDouble(),
maxValue: maxCustomFeeRate,
@@ -1,7 +1,6 @@
import 'dart:developer' as dev;
import 'dart:core';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/fiat_conversion_service.dart';
import 'package:cake_wallet/core/payment_uris.dart';
@@ -9,11 +8,10 @@ import 'package:cake_wallet/core/wallet_change_listener_view_model.dart';
import 'package:cake_wallet/entities/auto_generate_subaddress_status.dart';
import 'package:cake_wallet/entities/fiat_api_mode.dart';
import 'package:cake_wallet/entities/fiat_currency.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/reactions/wallet_utils.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/decred/decred.dart';
@@ -47,7 +45,7 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
required this.yatStore,
required this.fiatConversionStore,
}) : _baseItems = <ListItem>[],
selectedCurrency = walletTypeToCryptoCurrency(appStore.wallet!.type),
selectedCurrency = appStore.wallet!.currency,
_cryptoNumberFormat = NumberFormat(_cryptoNumberPattern),
hasAccounts = [WalletType.monero, WalletType.wownero, WalletType.haven]
.contains(appStore.wallet!.type),
@@ -57,11 +55,14 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
_init();
}
@computed
int? get selectedChainId => wallet.chainId;
@override
void onWalletChange(wallet) {
_init();
selectedCurrency = walletTypeToCryptoCurrency(wallet.type);
selectedCurrency = wallet.currency;
hasAccounts = [WalletType.monero, WalletType.wownero, WalletType.haven].contains(wallet.type);
}
@@ -75,7 +76,7 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
double? _fiatRate;
String _rawAmount = '';
List<Currency> get currencies => [walletTypeToCryptoCurrency(wallet.type), ...FiatCurrency.all];
List<Currency> get currencies => [wallet.currency, ...FiatCurrency.all];
String get buttonTitle {
if (isElectrumWallet) {
@@ -114,6 +115,21 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
@computed
PaymentURI get uri {
if (isEVMCompatibleChain(wallet.type) && selectedChainId != null) {
switch (selectedChainId) {
case 1:
return EthereumURI(amount: amount, address: address.address);
case 137:
return PolygonURI(amount: amount, address: address.address);
case 8453:
return BaseURI(amount: amount, address: address.address);
case 42161:
return ArbitrumURI(amount: amount, address: address.address);
default:
return EthereumURI(amount: amount, address: address.address);
}
}
switch (wallet.type) {
case WalletType.monero:
return MoneroURI(amount: amount, address: address.address);
@@ -205,7 +221,9 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
address: address.address,
txCount: address.txCount,
balance: AmountConverter.amountIntToString(
walletTypeToCryptoCurrency(type), address.balance),
walletTypeToCryptoCurrency(type),
address.balance,
),
isChange: address.isChange,
);
});
@@ -221,7 +239,9 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
address: address.address,
txCount: address.txCount,
balance: AmountConverter.amountIntToString(
walletTypeToCryptoCurrency(type), address.balance),
walletTypeToCryptoCurrency(type),
address.balance,
),
isChange: address.isChange,
isOneTimeReceiveAddress: true,
);
@@ -238,7 +258,9 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
address: subaddress.address,
txCount: subaddress.txCount,
balance: AmountConverter.amountIntToString(
walletTypeToCryptoCurrency(type), subaddress.balance),
walletTypeToCryptoCurrency(type),
subaddress.balance,
),
isChange: subaddress.isChange);
});
@@ -257,26 +279,8 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
}
}
if (wallet.type == WalletType.ethereum) {
final primaryAddress = ethereum!.getAddress(wallet);
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
if (wallet.type == WalletType.polygon) {
final primaryAddress = polygon!.getAddress(wallet);
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
if (wallet.type == WalletType.base) {
final primaryAddress = base!.getAddress(wallet);
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
if (wallet.type == WalletType.arbitrum) {
final primaryAddress = arbitrum!.getAddress(wallet);
if (isEVMCompatibleChain(wallet.type)) {
final primaryAddress = evm!.getAddress(wallet);
addressList.add(WalletAddressListItem(isPrimary: true, name: null, address: primaryAddress));
}
@@ -415,17 +419,47 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
WalletType.dogecoin
].contains(wallet.type);
@computed
List<String> get walletImages {
List<String> getWalletImages(int? chainId) {
if (chainId != null) {
switch (chainId) {
case 1:
return [
'assets/images/eth_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/usdt_wallet_icon.svg',
'assets/images/deuro_icon.svg',
'assets/images/more_tokens.svg',
];
case 137:
return [
'assets/images/pol_icon.svg',
'assets/images/eth_pol_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/usdt_wallet_icon.svg',
'assets/images/more_tokens.svg',
];
case 8453:
return [
'assets/images/eth_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/more_tokens.svg',
];
case 42161:
return [
'assets/images/crypto/arbitrum.webp',
'assets/images/usdc_icon.svg',
'assets/images/more_tokens.svg',
];
default:
return [
'assets/images/eth_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/usdt_wallet_icon.svg',
];
}
}
switch (wallet.type) {
case WalletType.ethereum:
return [
'assets/images/eth_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/usdt_wallet_icon.svg',
'assets/images/deuro_icon.svg',
'assets/images/more_tokens.svg',
];
case WalletType.solana:
return [
'assets/images/sol_icon.svg',
@@ -433,14 +467,6 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
'assets/images/usdt_wallet_icon.svg',
'assets/images/more_tokens.svg',
];
case WalletType.polygon:
return [
'assets/images/pol_icon.svg',
'assets/images/eth_pol_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/usdt_wallet_icon.svg',
'assets/images/more_tokens.svg',
];
case WalletType.tron:
return [
'assets/images/trx_icon.svg',
@@ -453,28 +479,16 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
'assets/images/zano_icon.svg',
'assets/images/more_tokens.svg',
];
case WalletType.base:
return [
'assets/images/eth_icon.svg',
'assets/images/usdc_icon.svg',
'assets/images/more_tokens.svg',
];
case WalletType.arbitrum:
return [
'assets/images/crypto/arbitrum.webp',
'assets/images/usdc_icon.svg',
'assets/images/more_tokens.svg',
];
default:
return [];
}
}
@computed
String get qrImage => getQrImage(type);
String get qrImage => getQrImage(type, selectedChainId: selectedChainId);
@computed
String get monoImage => getChainMonoImage(type);
String get monoImage => getChainMonoImage(type, selectedChainId: selectedChainId);
@computed
bool get isBalanceAvailable => isElectrumWallet;
@@ -544,7 +558,7 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
selectedCurrency = currency;
if (currency is FiatCurrency && _settingsStore.fiatCurrency != currency) {
final cryptoCurrency = walletTypeToCryptoCurrency(wallet.type);
final cryptoCurrency = wallet.currency;
dev.log("Requesting Fiat rate for $cryptoCurrency-$currency");
FiatConversionService.fetchPrice(
@@ -575,7 +589,7 @@ abstract class WalletAddressListViewModelBase extends WalletChangeListenerViewMo
@action
void _convertAmountToCrypto() {
final cryptoCurrency = walletTypeToCryptoCurrency(wallet.type);
final cryptoCurrency = wallet.currency;
final fiatRate = _fiatRate ?? (fiatConversionStore.prices[cryptoCurrency] ?? 0.0);
if (fiatRate <= 0.0) {
@@ -1,10 +1,9 @@
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/generate_wallet_password.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/generated/i18n.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/view_model/hardware_wallet/hardware_wallet_view_model.dart';
import 'package:cake_wallet/view_model/hardware_wallet/ledger_view_model.dart';
@@ -79,11 +78,11 @@ abstract class WalletHardwareRestoreViewModelBase extends WalletCreationVM with
bitcoin!.createBitcoinHardwareWalletCredentials(name: name, accountData: selectedAccount!);
break;
case WalletType.ethereum:
credentials =
ethereum!.createEthereumHardwareWalletCredentials(name: name, hwAccountData: selectedAccount!);
break;
case WalletType.polygon:
credentials = polygon!.createPolygonHardwareWalletCredentials(name: name, hwAccountData: selectedAccount!);
credentials = evm!.createEVMHardwareWalletCredentials(
name: name,
hwAccountData: selectedAccount!,
);
break;
case WalletType.monero:
final password = walletPassword ?? generateWalletPassword();
+19 -4
View File
@@ -14,6 +14,8 @@ import 'package:flutter/foundation.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:polyseed/polyseed.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
part 'wallet_keys_view_model.g.dart';
@@ -21,12 +23,12 @@ class WalletKeysViewModel = WalletKeysViewModelBase with _$WalletKeysViewModel;
abstract class WalletKeysViewModelBase with Store {
WalletKeysViewModelBase(this._appStore)
: title = '${walletTypeToString(_appStore.wallet!.type)} ${S.current.wallet_keys}',
_wallet = _appStore.wallet!,
: _wallet = _appStore.wallet!,
_walletName = _appStore.wallet!.type.name,
_restoreHeight = _appStore.wallet!.walletInfo.restoreHeight,
_restoreHeightByTransactions = 0,
items = ObservableList<StandartListItem>() {
items = ObservableList<StandartListItem>(),
_title = _getInitialTitle(_appStore.wallet!) {
_populateKeysItems();
reaction((_) => _appStore.wallet, (WalletBase? _wallet) {
@@ -49,11 +51,24 @@ abstract class WalletKeysViewModelBase with Store {
}
}
static String _getInitialTitle(WalletBase wallet) {
if (isEVMCompatibleChain(wallet.type)) {
final currentChain = evm!.getCurrentChain(wallet);
return '${currentChain?.name ?? walletTypeToString(wallet.type)} ${S.current.wallet_keys}';
}
return '${walletTypeToString(wallet.type)} ${S.current.wallet_keys}';
}
bool get isBitcoin => _wallet.type == WalletType.bitcoin;
final ObservableList<StandartListItem> items;
final String title;
@observable
String _title;
String get title => _title;
final WalletBase _wallet;
final String _walletName;
final AppStore _appStore;
+5 -29
View File
@@ -1,14 +1,11 @@
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/core/new_wallet_arguments.dart';
import 'package:cake_wallet/dogecoin/dogecoin.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/zano/zano.dart';
import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/tron/tron.dart';
import 'package:cake_wallet/wownero/wownero.dart';
import 'package:hive/hive.dart';
import 'package:mobx/mobx.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
@@ -21,10 +18,7 @@ import 'package:cake_wallet/view_model/wallet_creation_vm.dart';
import 'package:cake_wallet/decred/decred.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cw_core/wallet_credentials.dart';
import 'package:cw_core/wallet_info.dart';
import 'package:cw_core/wallet_type.dart';
import '../polygon/polygon.dart';
import 'advanced_privacy_settings_view_model.dart';
part 'wallet_new_vm.g.dart';
@@ -51,8 +45,7 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store {
bool get hasLanguageSelector =>
[WalletType.monero, WalletType.haven, WalletType.wownero].contains(type);
bool get showLanguageSelector =>
newWalletArguments?.mnemonic == null && hasLanguageSelector;
bool get showLanguageSelector => newWalletArguments?.mnemonic == null && hasLanguageSelector;
bool get hasSeedType =>
newWalletArguments?.mnemonic == null &&
@@ -85,21 +78,10 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store {
mnemonic: newWalletArguments!.mnemonic,
);
case WalletType.ethereum:
return ethereum!.createEthereumNewWalletCredentials(
name: name,
password: walletPassword,
mnemonic: newWalletArguments!.mnemonic,
passphrase: passphrase,
);
case WalletType.polygon:
case WalletType.base:
return base!.createBaseNewWalletCredentials(
name: name,
password: walletPassword,
mnemonic: newWalletArguments!.mnemonic,
passphrase: passphrase,
);
case WalletType.arbitrum:
return arbitrum!.createArbitrumNewWalletCredentials(
return evm!.createEVMNewWalletCredentials(
name: name,
password: walletPassword,
mnemonic: newWalletArguments!.mnemonic,
@@ -127,13 +109,7 @@ abstract class WalletNewVMBase extends WalletCreationVM with Store {
mnemonic: newWalletArguments!.mnemonic,
passphrase: passphrase,
);
case WalletType.polygon:
return polygon!.createPolygonNewWalletCredentials(
name: name,
password: walletPassword,
mnemonic: newWalletArguments!.mnemonic,
passphrase: passphrase,
);
case WalletType.solana:
return solana!.createSolanaNewWalletCredentials(
name: name,
+35 -65
View File
@@ -1,15 +1,13 @@
import 'package:cake_wallet/arbitrum/arbitrum.dart';
import 'package:cake_wallet/base/base.dart';
import 'package:cake_wallet/bitcoin/bitcoin.dart';
import 'package:cake_wallet/bitcoin_cash/bitcoin_cash.dart';
import 'package:cake_wallet/core/generate_wallet_password.dart';
import 'package:cake_wallet/core/wallet_creation_service.dart';
import 'package:cake_wallet/di.dart';
import 'package:cake_wallet/dogecoin/dogecoin.dart';
import 'package:cake_wallet/ethereum/ethereum.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/monero/monero.dart';
import 'package:cake_wallet/nano/nano.dart';
import 'package:cake_wallet/polygon/polygon.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/solana/solana.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/tron/tron.dart';
@@ -68,7 +66,7 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
}
walletCreationService.changeWalletType(type: type);
if (restoredWallet != null) {
if(restoredWallet!.restoreMode == WalletRestoreMode.seed) {
if (restoredWallet!.restoreMode == WalletRestoreMode.seed) {
seedSettingsViewModel.setPassphrase(restoredWallet!.passphrase);
}
}
@@ -78,18 +76,12 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
static const decredSeedMnemonicLength = 15;
late List<WalletRestoreMode> availableModes;
late final bool hasSeedLanguageSelector = [
WalletType.monero,
WalletType.haven,
WalletType.wownero
].contains(type);
late final bool hasSeedLanguageSelector =
[WalletType.monero, WalletType.haven, WalletType.wownero].contains(type);
late final bool hasBlockchainHeightSelector =
[WalletType.monero, WalletType.haven, WalletType.wownero].contains(type);
late final bool hasBlockchainHeightSelector = [
WalletType.monero,
WalletType.haven,
WalletType.wownero
].contains(type);
late final bool hasRestoreFromPrivateKey = [
WalletType.ethereum,
WalletType.polygon,
@@ -101,10 +93,8 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
WalletType.tron
].contains(type);
late final bool onlyViewKeyRestore = [
if (FeatureFlag.hasBitcoinViewOnly) WalletType.bitcoin,
WalletType.decred
].contains(type);
late final bool onlyViewKeyRestore =
[if (FeatureFlag.hasBitcoinViewOnly) WalletType.bitcoin, WalletType.decred].contains(type);
final RestoredWallet? restoredWallet;
final HardwareWalletType? hardwareWalletType;
@@ -131,7 +121,11 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
switch (type) {
case WalletType.monero:
return monero!.createMoneroRestoreWalletFromSeedCredentials(
name: name, height: height, mnemonic: seed, password: password, passphrase: passphrase??'');
name: name,
height: height,
mnemonic: seed,
password: password,
passphrase: passphrase ?? '');
case WalletType.bitcoin:
case WalletType.litecoin:
return bitcoin!.createBitcoinRestoreWalletFromSeedCredentials(
@@ -142,13 +136,7 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
derivationType: derivationInfo!.derivationType!,
derivationPath: derivationInfo.derivationPath!,
);
case WalletType.ethereum:
return ethereum!.createEthereumRestoreWalletFromSeedCredentials(
name: name,
mnemonic: seed,
password: password,
passphrase: passphrase,
);
case WalletType.bitcoinCash:
return bitcoinCash!.createBitcoinCashRestoreWalletFromSeedCredentials(
name: name,
@@ -172,22 +160,11 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
derivationType: derivationInfo!.derivationType!,
passphrase: passphrase,
);
case WalletType.ethereum:
case WalletType.polygon:
return polygon!.createPolygonRestoreWalletFromSeedCredentials(
name: name,
mnemonic: seed,
password: password,
passphrase: passphrase,
);
case WalletType.base:
return base!.createBaseRestoreWalletFromSeedCredentials(
name: name,
mnemonic: seed,
password: password,
passphrase: passphrase,
);
case WalletType.arbitrum:
return arbitrum!.createArbitrumRestoreWalletFromSeedCredentials(
return evm!.createEVMRestoreWalletFromSeedCredentials(
name: name,
mnemonic: seed,
password: password,
@@ -212,7 +189,7 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
name: name,
mnemonic: seed,
password: password,
passphrase: passphrase??'',
passphrase: passphrase ?? '',
height: height,
);
case WalletType.zano:
@@ -220,14 +197,14 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
name: name,
password: password,
height: height,
passphrase: passphrase??'',
passphrase: passphrase ?? '',
mnemonic: seed,
);
case WalletType.decred:
return decred!.createDecredRestoreWalletFromSeedCredentials(
name: name,
mnemonic: seed,
password: password,
name: name,
mnemonic: seed,
password: password,
);
case WalletType.none:
case WalletType.haven:
@@ -271,13 +248,6 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
language: 'English',
);
case WalletType.ethereum:
return ethereum!.createEthereumRestoreWalletFromPrivateKey(
name: name,
privateKey: options['private_key'] as String,
password: password,
);
case WalletType.nano:
return nano!.createNanoRestoreWalletFromKeysCredentials(
name: name,
@@ -285,20 +255,11 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
seedKey: options['private_key'] as String,
derivationType: derivationInfo!.derivationType!,
);
case WalletType.ethereum:
case WalletType.polygon:
return polygon!.createPolygonRestoreWalletFromPrivateKey(
name: name,
password: password,
privateKey: options['private_key'] as String,
);
case WalletType.base:
return base!.createBaseRestoreWalletFromPrivateKey(
name: name,
password: password,
privateKey: options['private_key'] as String,
);
case WalletType.arbitrum:
return arbitrum!.createArbitrumRestoreWalletFromPrivateKey(
return evm!.createEVMRestoreWalletFromPrivateKey(
name: name,
password: password,
privateKey: options['private_key'] as String,
@@ -343,7 +304,16 @@ abstract class WalletRestoreViewModelBase extends WalletCreationVM with Store {
var list = <DerivationInfo>[];
var walletType = credentials["walletType"] as WalletType;
var appStore = getIt.get<AppStore>();
var node = appStore.settingsStore.getCurrentNode(walletType);
int? chainId;
if (isEVMCompatibleChain(walletType)) {
if (appStore.wallet != null) {
chainId = evm!.getSelectedChainId(appStore.wallet!);
}
chainId ??= evm!.getChainIdByWalletType(walletType);
}
var node = appStore.settingsStore.getCurrentNode(walletType, chainId: chainId);
switch (walletType) {
case WalletType.bitcoin:
+12 -1
View File
@@ -6,6 +6,8 @@ import 'package:flutter/foundation.dart';
import 'package:cw_core/wallet_type.dart';
import 'package:mobx/mobx.dart';
import 'package:cw_core/wallet_base.dart';
import 'package:cake_wallet/evm/evm.dart';
import 'package:cake_wallet/reactions/wallet_connect.dart';
part 'wallet_seed_view_model.g.dart';
@@ -15,11 +17,20 @@ abstract class WalletSeedViewModelBase with Store {
WalletSeedViewModelBase(WalletBase wallet)
: name = wallet.name,
seed = wallet.seed!,
walletType = walletTypeToString(wallet.type),
walletType = _getWalletTypeName(wallet),
currentOptions = ObservableList<String>(),
verificationIndices = ObservableList<int>() {
setupSeedVerification();
}
static String _getWalletTypeName(WalletBase wallet) {
if (isEVMCompatibleChain(wallet.type)) {
final currentChain = evm!.getCurrentChain(wallet);
return currentChain?.name ?? walletTypeToString(wallet.type);
} else {
return walletTypeToString(wallet.type);
}
}
@observable
String name;
@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:cake_wallet/reactions/wallet_connect.dart';
import 'package:cake_wallet/store/app_store.dart';
import 'package:cake_wallet/core/wallet_loading_service.dart';
import 'package:cw_core/wallet_info.dart';
@@ -29,8 +30,12 @@ abstract class WalletSwitcherViewModelBase with Store {
@action
Future<List<WalletInfo>> getWallets(WalletType? walletType) async {
final wiList = await WalletInfo.getAll();
if (walletType == null) {
return wiList;
if (walletType == null) return wiList;
// For EVM-compatible wallet types, show all EVM-compatible wallets
// This allows users to switch between any EVM wallet regardless of the specific chain
if (isEVMCompatibleChain(walletType)) {
return wiList.where((wallet) => isEVMCompatibleChain(wallet.type)).toList();
}
return wiList.where((wallet) => wallet.type == walletType).toList();