mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-12-02 12:14:09 +01:00
refactor: delete dead Cake Pay/buy/exchange code; split di setup()
- Cake Pay: 36 files (~5.3k LOC) plus DI registrations, routes, and UI branches (feature was hard-disabled and unreachable) - unreachable buy providers: robinhood, dfx, onramper, meld, kryptonim (~1.7k LOC); MoonPay untouched - exchange providers that only existed as commented-out wiring: changenow, sideshift, chainflip, exolix, swaptrade, letsexchange, stealthex, xoswap, swapsxyz, thorchain, simpleswap (~5.2k LOC); Trocador untouched; ExchangeProviderDescription values and Hive adapters kept so stored trades and orders still deserialize - di.dart setup() split from one 1,452-line function into 10 sequential chunk functions; registration execution order verified identical before and after (251 register calls)
This commit is contained in:
@@ -21,11 +21,8 @@ import 'package:hash_wallet/entities/template.dart';
|
||||
import 'package:hash_wallet/entities/transaction_description.dart';
|
||||
import 'package:hash_wallet/entities/wallet_contact.dart';
|
||||
import 'package:hash_wallet/evm/evm.dart';
|
||||
import 'package:hash_wallet/exchange/exchange_provider_description.dart';
|
||||
import 'package:hash_wallet/exchange/provider/exchange_provider.dart';
|
||||
import 'package:hash_wallet/exchange/provider/near_Intents_exchange_provider.dart';
|
||||
import 'package:hash_wallet/exchange/provider/swapsxyz_exchange_provider.dart';
|
||||
import 'package:hash_wallet/exchange/provider/thorchain_exchange.provider.dart';
|
||||
import 'package:hash_wallet/exchange/trade.dart';
|
||||
import 'package:hash_wallet/generated/i18n.dart';
|
||||
import 'package:hash_wallet/monero/monero.dart';
|
||||
@@ -47,13 +44,11 @@ import 'package:hash_wallet/view_model/unspent_coins/unspent_coins_list_view_mod
|
||||
import 'package:hash_wallet/wownero/wownero.dart';
|
||||
import 'package:cw_core/crypto_currency.dart';
|
||||
import 'package:cw_core/currency_for_wallet_type.dart';
|
||||
import 'package:cw_core/erc20_token.dart';
|
||||
import 'package:cw_core/exceptions.dart';
|
||||
import 'package:cw_core/lnurl.dart';
|
||||
import 'package:cw_core/pending_transaction.dart';
|
||||
import 'package:cw_core/sync_status.dart';
|
||||
import 'package:cw_core/transaction_info.dart';
|
||||
import 'package:cw_core/transaction_priority.dart';
|
||||
import 'package:cw_core/unspent_coin_type.dart';
|
||||
import 'package:cw_core/utils/print_verbose.dart';
|
||||
import 'package:cw_core/wallet_type.dart';
|
||||
@@ -131,10 +126,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
});
|
||||
}
|
||||
|
||||
// Store trade and provider references for post-commit updates (e.g., Jupiter trade ID update)
|
||||
Trade? _currentTrade;
|
||||
ExchangeProvider? _currentProvider;
|
||||
|
||||
@observable
|
||||
ExecutionState state;
|
||||
|
||||
@@ -596,8 +587,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
|
||||
@action
|
||||
Future<PendingTransaction?> createTransaction({ExchangeProvider? provider, Trade? trade}) async {
|
||||
_currentTrade = trade;
|
||||
_currentProvider = provider;
|
||||
pendingTransaction = null;
|
||||
|
||||
try {
|
||||
@@ -615,184 +604,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
}
|
||||
}
|
||||
|
||||
// Swaps.xyz (EVM) path
|
||||
if (isEVMWallet && trade != null && provider is SwapsXyzExchangeProvider) {
|
||||
final routerTo = trade.inputAddress;
|
||||
final routerData = trade.routerData;
|
||||
|
||||
|
||||
if (routerData != null && routerData != '0x') {
|
||||
final tokenContract = (trade.sourceTokenAddress ?? '').toLowerCase();
|
||||
final priority = _settingsStore.getPriority(
|
||||
walletType, chainId: selectedChainId);
|
||||
final routerValueWei = BigInt.tryParse(trade.routerValue ?? '0') ??
|
||||
BigInt.zero;
|
||||
|
||||
if (routerTo == null || routerTo.isEmpty) {
|
||||
state = FailureState('Invalid router address');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
final selector = _decodeMethodSelector(routerData);
|
||||
const transferSig = '0xa9059cbb';
|
||||
const swapAndExecuteSig = '0x9be111d1';
|
||||
|
||||
// Direct Transfer (Simple routing, no approval needed)
|
||||
if (selector == transferSig) {
|
||||
pendingTransaction = await evm!.createRawCallDataTransaction(
|
||||
wallet,
|
||||
routerTo,
|
||||
routerData,
|
||||
BigInt.zero,
|
||||
priority,
|
||||
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
|
||||
? _settingsStore.useBlinkProtection
|
||||
: false,
|
||||
);
|
||||
state = ExecutedSuccessfullyState();
|
||||
return pendingTransaction;
|
||||
}
|
||||
|
||||
// Smart Swap (Requires Approval)
|
||||
if (selector == swapAndExecuteSig) {
|
||||
final requiredAmount = BigInt.tryParse(
|
||||
(trade.sourceTokenAmountRaw ?? '0').replaceAll('n', '')) ??
|
||||
BigInt.zero;
|
||||
|
||||
final needsApproval = tokenContract.isNotEmpty &&
|
||||
requiredAmount > BigInt.zero
|
||||
? await evm!.isApprovalRequired(
|
||||
wallet, tokenContract, routerTo, requiredAmount)
|
||||
: false;
|
||||
|
||||
printV(
|
||||
'[Swaps.xyz sending flow] Approval required: $needsApproval for token ${trade
|
||||
.from?.title} ${trade.from?.tag ??
|
||||
''} with amount $requiredAmount');
|
||||
|
||||
if (needsApproval) {
|
||||
// USDT Approval Flow (Special Case). We must reset allowance to 0 first.
|
||||
final isUSDTMainnet = selectedChainId == 1 &&
|
||||
tokenContract.toLowerCase() ==
|
||||
'0xdac17f958d2ee523a2206206994597c13d831ec7';
|
||||
|
||||
if (isUSDTMainnet) {
|
||||
final currentAllowance = await evm!.getAllowance(
|
||||
wallet, tokenContract, routerTo);
|
||||
|
||||
if (currentAllowance != null &&
|
||||
currentAllowance > BigInt.zero) {
|
||||
printV(
|
||||
'[Swaps.xyz sending flow] currentAllowance USDT: $currentAllowance. Resetting to 0 before setting new allowance.');
|
||||
|
||||
final resetTx = await buildApprovalNeeded(
|
||||
spender: routerTo,
|
||||
tokenContract: tokenContract,
|
||||
requiredAmount: BigInt.zero,
|
||||
// Approve 0
|
||||
sourceTokenDecimals: trade.sourceTokenDecimals,
|
||||
priority: priority
|
||||
);
|
||||
|
||||
if (resetTx != null) {
|
||||
await resetTx.commit();
|
||||
|
||||
final resetConfirmed = await _waitForApprovalUpdate(
|
||||
tokenContract: tokenContract,
|
||||
spender: routerTo,
|
||||
requiredAmount: BigInt.zero, // Wait until it equals 0
|
||||
waitForExactMatch: true,
|
||||
);
|
||||
|
||||
if (!resetConfirmed) {
|
||||
state = FailureState(
|
||||
'Failed to reset USDT allowance. Please try again.');
|
||||
return null;
|
||||
}
|
||||
printV(
|
||||
'[Swaps.xyz sending flow] USDT allowance reset to 0 confirmed on-chain.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Standard Approval Flow
|
||||
final approvalTx = await buildApprovalNeeded(
|
||||
spender: routerTo,
|
||||
tokenContract: tokenContract,
|
||||
requiredAmount: requiredAmount,
|
||||
sourceTokenDecimals: trade.sourceTokenDecimals,
|
||||
priority: priority
|
||||
);
|
||||
|
||||
if (approvalTx == null) {
|
||||
state = FailureState('Failed to build approval transaction');
|
||||
return null;
|
||||
}
|
||||
|
||||
pendingTransaction = null;
|
||||
|
||||
try {
|
||||
printV(
|
||||
'[Swaps.xyz sending flow] Submitting approval transaction for token ${trade
|
||||
.from?.title} ${trade.from?.tag ?? ''} ');
|
||||
await approvalTx.commit();
|
||||
|
||||
// Wait for the approval to be mined on-chain
|
||||
final isApproved = await _waitForApprovalUpdate(
|
||||
tokenContract: tokenContract,
|
||||
spender: routerTo,
|
||||
requiredAmount: requiredAmount,
|
||||
);
|
||||
|
||||
if (!isApproved) {
|
||||
state = FailureState(
|
||||
'Approval transaction failed or timed out on-chain. Try again.');
|
||||
return null;
|
||||
}
|
||||
printV(
|
||||
'[Swaps.xyz sending flow] Approval transaction confirmed on-chain. Proceeding with swap execution.');
|
||||
} catch (e, s) {
|
||||
printV(
|
||||
'[Swaps.xyz sending flow] Approval transaction error: $e\n$s');
|
||||
state = FailureState(
|
||||
translateErrorMessage(e, wallet.type, wallet.currency));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Construct Final Swap Transaction
|
||||
printV('[Swaps.xyz sending flow] Building swap transaction');
|
||||
pendingTransaction = await evm!.createRawCallDataTransaction(
|
||||
wallet,
|
||||
routerTo,
|
||||
routerData,
|
||||
routerValueWei,
|
||||
priority,
|
||||
sourceTokenAddress: tokenContract,
|
||||
sourceTokenAmount: requiredAmount,
|
||||
useBlinkProtection: canSupportBlinkProtection(selectedChainId)
|
||||
? _settingsStore.useBlinkProtection
|
||||
: false,
|
||||
);
|
||||
|
||||
state = ExecutedSuccessfullyState();
|
||||
return pendingTransaction;
|
||||
}
|
||||
|
||||
state = FailureState('Unsupported Swaps.xyz transaction type');
|
||||
return null;
|
||||
} catch (e, s) {
|
||||
printV('Swaps.xyz transaction error: $e\n$s');
|
||||
state = FailureState(
|
||||
'Failed to create Swaps.xyz transaction - ${translateErrorMessage(
|
||||
e, wallet.type, wallet.currency)}');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
// END Swaps.xyz path
|
||||
|
||||
// Regular flow
|
||||
|
||||
|
||||
@@ -823,16 +634,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
}
|
||||
}
|
||||
|
||||
if (provider is ThorChainExchangeProvider) {
|
||||
final outputCount = pendingTransaction?.outputCount ?? 0;
|
||||
if (outputCount > 10) {
|
||||
throw Exception("THORChain does not support more than 10 outputs");
|
||||
}
|
||||
|
||||
if (_hasTaprootInput(pendingTransaction)) {
|
||||
throw Exception("THORChain does not support Taproot addresses");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -936,13 +737,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
|
||||
state = TransactionCommitted();
|
||||
|
||||
if (_currentTrade != null) {
|
||||
final provider = _currentTrade!.provider;
|
||||
if (provider == ExchangeProviderDescription.swapsXyz) {
|
||||
registerSwapsXyzTransaction(_currentTrade!);
|
||||
}
|
||||
}
|
||||
|
||||
// Immediate transaction update for EVM chains and Nano
|
||||
if (isEVMWallet || [WalletType.bitcoin, WalletType.nano].contains(walletType)) {
|
||||
Future.delayed(Duration(seconds: 4), () async {
|
||||
@@ -1121,88 +915,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
return null;
|
||||
}
|
||||
|
||||
// Helper functions for EVM transaction monitoring and approval flow
|
||||
|
||||
// Polls the token contract directly to see if allowance is updated.
|
||||
Future<bool> _waitForApprovalUpdate({
|
||||
required String tokenContract,
|
||||
required String spender,
|
||||
required BigInt requiredAmount,
|
||||
bool waitForExactMatch = false,
|
||||
}) async {
|
||||
if (!isEVMWallet || evm == null) return false;
|
||||
|
||||
int attempts = 0;
|
||||
const int maxAttempts = 30; // ~60 seconds
|
||||
|
||||
printV('[Swaps.xyz sending flow] Starting allowance check. Target: $requiredAmount (Exact match: $waitForExactMatch)');
|
||||
|
||||
while (attempts < maxAttempts) {
|
||||
try {
|
||||
final currentAllowance = await evm!.getAllowance(wallet, tokenContract, spender);
|
||||
|
||||
if (currentAllowance != null) {
|
||||
printV('[Swaps.xyz sending flow] Current Allowance: $currentAllowance / Target: $requiredAmount');
|
||||
|
||||
if (waitForExactMatch) {
|
||||
// For Reset (Target 0): We need it to be exactly 0 (or less, though it can't be negative)
|
||||
if (currentAllowance <= requiredAmount) {
|
||||
printV('[Swaps.xyz sending flow] Allowance reset verified!');
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
// For Approval: We need it to be at least the required amount
|
||||
if (currentAllowance >= requiredAmount) {
|
||||
printV('[Swaps.xyz sending flow] Allowance verified!');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
printV('[Swaps.xyz sending flow] Allowance check error: $e');
|
||||
}
|
||||
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
attempts++;
|
||||
}
|
||||
|
||||
printV('[Swaps.xyz sending flow] Allowance check timed out.');
|
||||
return false;
|
||||
}
|
||||
|
||||
// Builds a token approval transaction
|
||||
Future<PendingTransaction?> buildApprovalNeeded({
|
||||
required String spender,
|
||||
required String tokenContract,
|
||||
required BigInt requiredAmount,
|
||||
required TransactionPriority? priority,
|
||||
int? sourceTokenDecimals,
|
||||
}) async {
|
||||
|
||||
final erc20Token = wallet.balance.keys.whereType<Erc20Token>().firstWhere(
|
||||
(t) => t.contractAddress.toLowerCase() == tokenContract.toLowerCase(),
|
||||
orElse: () => Erc20Token(
|
||||
name: '',
|
||||
symbol: '',
|
||||
contractAddress: tokenContract,
|
||||
decimal: sourceTokenDecimals ?? 18,
|
||||
enabled: true,
|
||||
),
|
||||
);
|
||||
|
||||
return await evm!.createTokenApproval(
|
||||
wallet,
|
||||
requiredAmount,
|
||||
spender,
|
||||
erc20Token,
|
||||
priority,
|
||||
useBlinkProtection:
|
||||
canSupportBlinkProtection(selectedChainId) ? _settingsStore.useBlinkProtection : false,
|
||||
);
|
||||
}
|
||||
|
||||
// End EVM helper functions
|
||||
|
||||
String translateErrorMessage(
|
||||
Object error,
|
||||
WalletType walletType,
|
||||
@@ -1322,63 +1034,6 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _hasTaprootInput(PendingTransaction? pendingTransaction) {
|
||||
if (walletType == WalletType.bitcoin && pendingTransaction != null) {
|
||||
return bitcoin!.hasTaprootInput(pendingTransaction);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Future<void> registerSwapsXyzTransaction(Trade trade) async {
|
||||
try {
|
||||
|
||||
// register only for vmId is alt-vm or bridgeId is alt-vm (trade.needToRegisterInSwapXyz)
|
||||
final needToRegister = trade.needToRegisterInSwapXyz ?? false;
|
||||
if (!needToRegister) return;
|
||||
|
||||
final vmId = (trade.providerId ?? '').toLowerCase();
|
||||
if (vmId.isEmpty) {
|
||||
printV('SwapsXyz: transaction register: skipped (vmId empty)');
|
||||
return;
|
||||
}
|
||||
|
||||
final txHash = pendingTransaction?.evmTxHashFromRawHex
|
||||
?? pendingTransaction?.id
|
||||
?? '';
|
||||
|
||||
if (txHash.isEmpty) {
|
||||
printV('SwapsXyz: transaction register: skipped (txHash empty)');
|
||||
return;
|
||||
}
|
||||
|
||||
final chainId = int.tryParse(trade.router ?? '') ?? 0;
|
||||
if (chainId <= 0) {
|
||||
printV('SwapsXyz: transaction register: skipped (invalid chainId)');
|
||||
return;
|
||||
}
|
||||
|
||||
printV(
|
||||
'SwapsXyz: attempting to register transaction: tradeId = ${trade.id}, txHash = $txHash, chainId = $chainId, vmId = $vmId');
|
||||
|
||||
final registered = await SwapsXyzExchangeProvider.registerAltVmTx(
|
||||
txId: trade.id,
|
||||
txHash: txHash,
|
||||
chainId: chainId,
|
||||
vmId: vmId,
|
||||
);
|
||||
|
||||
if (!registered) {
|
||||
printV('SwapsXyz: transaction register: failed');
|
||||
} else {
|
||||
printV('SwapsXyz: transaction register: success');
|
||||
}
|
||||
} catch (e) {
|
||||
printV('registerSwapsXyzTransaction error: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@computed
|
||||
bool get usePayjoin => _settingsStore.usePayjoin;
|
||||
|
||||
@@ -1397,6 +1052,4 @@ abstract class SendViewModelBase extends WalletChangeListenerViewModel with Stor
|
||||
}
|
||||
}
|
||||
|
||||
String _decodeMethodSelector(String s) =>
|
||||
(s.startsWith('0x') && s.length >= 10) ? s.substring(0, 10) : '';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user