From 209fc22f892156b28576a99e5c0fdffdbbae0944 Mon Sep 17 00:00:00 2001 From: Your Name Date: Wed, 26 Aug 2026 14:24:35 +0200 Subject: [PATCH] After failing to withdraw --- backend/src/services/withdrawalService.ts | 18 ++- backend/src/tests/withdrawEligibility.test.ts | 52 ++++++ backend/src/utils/httpError.ts | 2 + .../presentation/wallet_overview_screen.dart | 153 ++++++++++++++---- .../wallet/presentation/withdraw_screen.dart | 118 +++++++++++--- .../wallet/utils/withdraw_eligibility.dart | 67 ++++++++ .../src/features/wallet/WalletPage.tsx | 75 +++++++-- .../wallet/components/WithdrawDialog.tsx | 6 + .../wallet/utils/withdrawEligibility.ts | 52 ++++++ prediqo_web/src/shared/i18n/locales/en.ts | 6 + prediqo_web/src/shared/i18n/locales/fr.ts | 6 + 11 files changed, 482 insertions(+), 73 deletions(-) create mode 100644 backend/src/tests/withdrawEligibility.test.ts create mode 100644 prediqo_mobile/lib/features/wallet/utils/withdraw_eligibility.dart create mode 100644 prediqo_web/src/features/wallet/utils/withdrawEligibility.ts diff --git a/backend/src/services/withdrawalService.ts b/backend/src/services/withdrawalService.ts index a7e81c1c..545a3536 100644 --- a/backend/src/services/withdrawalService.ts +++ b/backend/src/services/withdrawalService.ts @@ -118,7 +118,11 @@ export async function requestWithdrawal( ): Promise { const settings = await settingsRepository.getSettings(); if (!settings.allow_withdrawals) { - throw new Error('Withdrawals are disabled by server configuration (enable in Admin → Settings).'); + const err = new Error( + 'Withdrawals are disabled by server configuration (enable in Admin → Settings).' + ) as Error & { code?: string }; + err.code = 'WITHDRAWALS_DISABLED'; + throw err; } await authService.assertWithdrawalSecondFactor(userId, totpCode); @@ -134,7 +138,11 @@ export async function requestWithdrawal( const caps = enrichWalletType(railWalletType, settings); if (!caps.withdrawEnabled) { - throw new Error(`Withdrawals are disabled for ${walletTypeCode}`); + const err = new Error(`Withdrawals are disabled for ${walletTypeCode}`) as Error & { + code?: string; + }; + err.code = 'WITHDRAWAL_NETWORK_DISABLED'; + throw err; } if (amountRaw <= 0n) throw new Error('Invalid amount'); @@ -150,11 +158,13 @@ export async function requestWithdrawal( const available = BigInt(account.available_balance); const locked = await withdrawalLockRepository.getLockedAmount(userId, ledgerWalletType.id); if (available < totalDebit + locked) { - throw new Error( + const err = new Error( feeRaw > 0n ? 'Insufficient balance (withdrawal amount + network fee)' : 'Insufficient balance' - ); + ) as Error & { code?: string }; + err.code = 'INSUFFICIENT_BALANCE'; + throw err; } const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id); diff --git a/backend/src/tests/withdrawEligibility.test.ts b/backend/src/tests/withdrawEligibility.test.ts new file mode 100644 index 00000000..f3dbd9c5 --- /dev/null +++ b/backend/src/tests/withdrawEligibility.test.ts @@ -0,0 +1,52 @@ +import { describe, test } from 'node:test'; +import assert from 'node:assert/strict'; + +// Mirror of prediqo_web withdrawEligibility (kept in sync for backend-facing docs/tests). +function computeWithdrawEligibility(input: { + withdrawalsEnabled: boolean; + hasWithdrawNetwork: boolean; + availableRaw: string; + feeRaw: string; +}) { + const availableRaw = BigInt(input.availableRaw || '0'); + const feeRaw = BigInt(input.feeRaw || '0'); + const maxReceivableRaw = availableRaw > feeRaw ? availableRaw - feeRaw : 0n; + if (!input.withdrawalsEnabled) return { allowed: false, reason: 'global_off' as const }; + if (!input.hasWithdrawNetwork) return { allowed: false, reason: 'no_network' as const }; + if (maxReceivableRaw <= 0n) return { allowed: false, reason: 'insufficient_for_fee' as const }; + return { allowed: true, reason: null }; +} + +describe('withdraw eligibility rules', () => { + test('blocks when global kill-switch off', () => { + const r = computeWithdrawEligibility({ + withdrawalsEnabled: false, + hasWithdrawNetwork: true, + availableRaw: '5000000', + feeRaw: '500000', + }); + assert.equal(r.allowed, false); + assert.equal(r.reason, 'global_off'); + }); + + test('blocks when available equals fee only', () => { + const r = computeWithdrawEligibility({ + withdrawalsEnabled: true, + hasWithdrawNetwork: true, + availableRaw: '500000', + feeRaw: '500000', + }); + assert.equal(r.allowed, false); + assert.equal(r.reason, 'insufficient_for_fee'); + }); + + test('allows when available covers fee + dust', () => { + const r = computeWithdrawEligibility({ + withdrawalsEnabled: true, + hasWithdrawNetwork: true, + availableRaw: '500001', + feeRaw: '500000', + }); + assert.equal(r.allowed, true); + }); +}); diff --git a/backend/src/utils/httpError.ts b/backend/src/utils/httpError.ts index fb7985e4..09679c74 100644 --- a/backend/src/utils/httpError.ts +++ b/backend/src/utils/httpError.ts @@ -21,6 +21,8 @@ export function httpStatusForError(error: unknown): number { const code = (error as { code?: string })?.code; if (code === 'EMAIL_NOT_VERIFIED') return 403; if (code === 'WITHDRAWAL_2FA_REQUIRED') return 403; + if (code === 'WITHDRAWALS_DISABLED' || code === 'WITHDRAWAL_NETWORK_DISABLED') return 403; + if (code === 'INSUFFICIENT_BALANCE' || code === 'HOT_WALLET_INSUFFICIENT_LIQUIDITY') return 400; if (code === 'DAILY_WITHDRAWAL_LIMIT_EXCEEDED') return 403; if (code === 'TOKEN_REVOKED') return 401; if (code === 'ACCOUNT_LOCKED') return 429; diff --git a/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart index 8cb58495..d70ac2f4 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart @@ -12,12 +12,14 @@ import '../../../data/models/balance_model.dart'; import '../../../data/models/test_wallet_models.dart'; import '../../../data/models/transaction_model.dart'; import '../../../data/repositories/wallet_repository_impl.dart'; +import '../../../domain/repositories/health_repository.dart'; import '../../../domain/repositories/referral_repository.dart'; import '../../../l10n/app_strings.dart'; import '../../../shared/widgets/app_snackbar.dart'; import '../../../shared/widgets/pred_card.dart'; import '../../wallet/bloc/wallet_bloc.dart'; import '../utils/transaction_display.dart'; +import '../utils/withdraw_eligibility.dart'; import '../../share_cards/presentation/share_result_widgets.dart'; const _hideBalanceKey = 'wallet_hide_balance'; @@ -43,6 +45,9 @@ class _WalletOverviewScreenState extends State bool _requestingTestCredits = false; bool? _bonusWithdrawable; bool _transferringBonus = false; + bool _withdrawalsEnabled = false; + String _withdrawalFeeRaw = '0'; + bool _healthLoaded = false; final Map _histories = { 'deposits': _CategoryHistory(), @@ -63,11 +68,30 @@ class _WalletOverviewScreenState extends State _loadHidePreference(); _loadTestWalletStatus(); _loadBonusPolicy(); + _loadWithdrawHealth(); WidgetsBinding.instance.addPostFrameCallback((_) { _ensureCategoryLoaded(_categories[_tabController.index]); }); } + Future _loadWithdrawHealth() async { + try { + final health = await sl().getHealth(); + if (!mounted) return; + setState(() { + _withdrawalsEnabled = health.withdrawalsEnabled; + _withdrawalFeeRaw = health.withdrawalNetworkFeeRaw; + _healthLoaded = true; + }); + } catch (_) { + if (!mounted) return; + setState(() { + _withdrawalsEnabled = false; + _healthLoaded = true; + }); + } + } + @override void dispose() { _tabController.removeListener(_onTabChanged); @@ -220,6 +244,7 @@ class _WalletOverviewScreenState extends State await Future.wait([ _loadTestWalletStatus(), _loadBonusPolicy(), + _loadWithdrawHealth(), ]); for (final key in _histories.keys) { final history = _histories[key]!; @@ -290,38 +315,92 @@ class _WalletOverviewScreenState extends State : Column( children: [ if (balance != null) ...[ - _WalletTypeCard( - title: s.mainWallet, - subtitle: s.mainWalletSubtitle, - balanceLabel: _maskOrAmount( - balance.available, - balance.walletType.decimals, - balance.walletType.code, - ), - lockedLabel: !_hideBalance && - (int.tryParse(balance.locked) ?? 0) > 0 - ? '${s.lockedBalance}: ${_maskOrAmount(balance.locked, balance.walletType.decimals, balance.walletType.code)}' - : null, - accent: AppColors.walletMain, - accentDeep: AppColors.walletMainDeep, - icon: Icons.account_balance_wallet_rounded, - actions: [ - _WalletAction( - icon: Icons.add_rounded, - label: s.deposit, - onTap: () => context.push('/deposit'), - ), - _WalletAction( - icon: Icons.north_east_rounded, - label: s.send, - onTap: () => context.push('/transfer'), - ), - _WalletAction( - icon: Icons.south_west_rounded, - label: s.withdraw, - onTap: () => context.push('/withdraw'), - ), - ], + Builder( + builder: (context) { + final hasRail = state.walletTypes.any( + (t) => t.withdrawEnabled == true, + ); + final eligibility = computeWithdrawEligibility( + withdrawalsEnabled: _withdrawalsEnabled, + hasWithdrawNetwork: hasRail, + availableRaw: balance.available, + feeRaw: _withdrawalFeeRaw, + ); + String? withdrawReason; + if (!eligibility.allowed) { + switch (eligibility.reason) { + case WithdrawBlockReason.globalOff: + withdrawReason = + 'Withdrawals are temporarily disabled by the platform.'; + case WithdrawBlockReason.noNetwork: + withdrawReason = + 'No withdrawal network is enabled right now.'; + case WithdrawBlockReason.insufficientForFee: + withdrawReason = + 'Insufficient balance for a withdrawal after the network fee.'; + case null: + withdrawReason = 'Withdrawals unavailable.'; + } + } + return Column( + children: [ + _WalletTypeCard( + title: s.mainWallet, + subtitle: s.mainWalletSubtitle, + balanceLabel: _maskOrAmount( + balance.available, + balance.walletType.decimals, + balance.walletType.code, + ), + lockedLabel: !_hideBalance && + (int.tryParse(balance.locked) ?? 0) > 0 + ? '${s.lockedBalance}: ${_maskOrAmount(balance.locked, balance.walletType.decimals, balance.walletType.code)}' + : null, + accent: AppColors.walletMain, + accentDeep: AppColors.walletMainDeep, + icon: Icons.account_balance_wallet_rounded, + actions: [ + _WalletAction( + icon: Icons.add_rounded, + label: s.deposit, + onTap: () => context.push('/deposit'), + ), + _WalletAction( + icon: Icons.north_east_rounded, + label: s.send, + onTap: () => context.push('/transfer'), + ), + _WalletAction( + icon: Icons.south_west_rounded, + label: s.withdraw, + enabled: _healthLoaded && eligibility.allowed, + onTap: () { + if (!_healthLoaded || !eligibility.allowed) { + showAppSnackBar( + context, + message: withdrawReason ?? + 'Withdrawals unavailable.', + ); + return; + } + context.push('/withdraw'); + }, + ), + ], + ), + if (withdrawReason != null) ...[ + const SizedBox(height: 8), + Text( + withdrawReason, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: AppColors.warning, + ), + ), + ], + ], + ); + }, ), const SizedBox(height: 12), _WalletTypeCard( @@ -532,10 +611,12 @@ class _WalletAction { required this.icon, required this.label, required this.onTap, + this.enabled = true, }); final IconData icon; final String label; final VoidCallback onTap; + final bool enabled; } class _WalletTypeCard extends StatelessWidget { @@ -866,8 +947,10 @@ class _ActionButton extends StatelessWidget { @override Widget build(BuildContext context) { + final enabled = action.enabled; + final color = enabled ? accent : accent.withValues(alpha: 0.4); return Material( - color: accent.withValues(alpha: 0.16), + color: accent.withValues(alpha: enabled ? 0.16 : 0.08), borderRadius: BorderRadius.circular(14), child: InkWell( onTap: action.onTap, @@ -876,7 +959,7 @@ class _ActionButton extends StatelessWidget { padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 6), child: Column( children: [ - Icon(action.icon, color: accent, size: 20), + Icon(action.icon, color: color, size: 20), const SizedBox(height: 4), Text( action.label, @@ -885,7 +968,7 @@ class _ActionButton extends StatelessWidget { style: TextStyle( fontSize: 12, fontWeight: FontWeight.w700, - color: accent, + color: color, ), ), ], diff --git a/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart index 820cc302..e21261eb 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart @@ -8,6 +8,12 @@ import '../../../core/network/api_client.dart'; import '../../../core/utils/amount_utils.dart'; import '../../../core/utils/coin_display.dart'; import '../bloc/wallet_bloc.dart'; +import '../utils/withdraw_eligibility.dart'; + +/// Unified spendable ledger decimals (USDT_TRC20). Payout rail may be BEP20 (18 on-chain) +/// but API amounts and fees are always 6-decimal micro-USDT. +const int _kLedgerUsdtDecimals = 6; +const String _kLedgerUsdtCode = 'USDT_TRC20'; /// Form to withdraw crypto to an external address; requires TOTP and confirmation dialog. class WithdrawScreen extends StatefulWidget { @@ -24,6 +30,8 @@ class _WithdrawScreenState extends State { final _totpController = TextEditingController(); String? _selectedWalletType; String _networkFeeRaw = '0'; + bool _withdrawalsEnabled = false; + bool _healthLoaded = false; @override void initState() { @@ -37,9 +45,21 @@ class _WithdrawScreenState extends State { final api = context.read(); final res = await api.dio.get>('/health'); final fee = res.data?['withdrawalNetworkFeeRaw']?.toString() ?? '0'; - if (mounted) setState(() => _networkFeeRaw = fee); + final enabled = res.data?['withdrawalsEnabled'] == true; + if (mounted) { + setState(() { + _networkFeeRaw = fee; + _withdrawalsEnabled = enabled; + _healthLoaded = true; + }); + } } catch (_) { - // Fee defaults to 0 if health is unavailable. + if (mounted) { + setState(() { + _withdrawalsEnabled = false; + _healthLoaded = true; + }); + } } } @@ -53,6 +73,14 @@ class _WithdrawScreenState extends State { /// Validates form fields, confirms with the user, and submits the withdrawal. void _submitWithdraw(BuildContext context) { + if (!_withdrawalsEnabled) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Withdrawals are temporarily disabled by the platform.'), + ), + ); + return; + } if (_selectedWalletType == null || _addressController.text.isEmpty || _amountController.text.isEmpty || @@ -63,19 +91,16 @@ class _WithdrawScreenState extends State { return; } final state = context.read().state; - final selectedType = state.walletTypes.firstWhere( - (t) => t.code == _selectedWalletType, - orElse: () => state.walletTypes.first, - ); final amountHuman = _amountController.text.trim(); - final amountRaw = humanAmountToRaw(amountHuman, selectedType.decimals); + // Always ledger micro-USDT (6), even when payout rail is BEP20. + final amountRaw = humanAmountToRaw(amountHuman, _kLedgerUsdtDecimals); if (amountRaw == '0') { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Enter a valid amount')), ); return; } - final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, selectedType.decimals); + final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, _kLedgerUsdtDecimals); final totalRaw = BigInt.parse(amountRaw) + feeRaw; if (state.balances.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( @@ -84,19 +109,21 @@ class _WithdrawScreenState extends State { return; } final balance = state.balances.firstWhere( - (b) => b.walletType.code == _selectedWalletType, + (b) => b.walletType.code == _kLedgerUsdtCode, orElse: () => state.balances.first, ); final available = BigInt.tryParse(balance.available) ?? BigInt.zero; if (totalRaw > available) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Insufficient balance (amount + network fee)'), + SnackBar( + content: Text( + 'Insufficient balance — need ${rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals)} USDT (amount + network fee)', + ), ), ); return; } - final feeHuman = rawAmountToHuman(feeRaw.toString(), selectedType.decimals); + final feeHuman = rawAmountToHuman(feeRaw.toString(), _kLedgerUsdtDecimals); final address = _addressController.text.trim(); showDialog( context: context, @@ -111,7 +138,7 @@ class _WithdrawScreenState extends State { const SizedBox(height: 8), Text('Network fee: $feeHuman USDT'), Text( - 'Total debited: ${rawAmountToHuman(totalRaw.toString(), selectedType.decimals)} USDT', + 'Total debited: ${rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals)} USDT', ), ], const SizedBox(height: 8), @@ -189,14 +216,56 @@ class _WithdrawScreenState extends State { final selectedTypeList = types.where((t) => t.code == _selectedWalletType); final selectedType = selectedTypeList.isEmpty ? types.first : selectedTypeList.first; final networkLabel = CoinDisplay.networkLabel(selectedType.code); - final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, selectedType.decimals); - final feeHuman = rawAmountToHuman(feeRaw.toString(), selectedType.decimals); + final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, _kLedgerUsdtDecimals); + final feeHuman = rawAmountToHuman(feeRaw.toString(), _kLedgerUsdtDecimals); + final spendable = balances.isEmpty + ? null + : balances.firstWhere( + (b) => b.walletType.code == _kLedgerUsdtCode, + orElse: () => balances.first, + ); + final eligibility = computeWithdrawEligibility( + withdrawalsEnabled: _withdrawalsEnabled, + hasWithdrawNetwork: types.isNotEmpty, + availableRaw: spendable?.available ?? '0', + feeRaw: _networkFeeRaw, + ); + final formEnabled = _healthLoaded && eligibility.allowed; return SingleChildScrollView( padding: const EdgeInsets.all(24), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - const Text('Asset'), + if (_healthLoaded && !eligibility.allowed) ...[ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.errorContainer.withValues(alpha: 0.45), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + switch (eligibility.reason) { + WithdrawBlockReason.globalOff => + 'Withdrawals are temporarily disabled by the platform.', + WithdrawBlockReason.noNetwork => + 'No withdrawal network is enabled right now.', + WithdrawBlockReason.insufficientForFee => + 'Insufficient balance for a withdrawal after the network fee ($feeHuman USDT).', + null => 'Withdrawals unavailable.', + }, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + const SizedBox(height: 16), + ], + if (eligibility.allowed && feeRaw > BigInt.zero && spendable != null) ...[ + Text( + 'You can withdraw up to ${rawAmountToHuman(eligibility.maxReceivableRaw.toString(), _kLedgerUsdtDecimals)} USDT after the network fee.', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 12), + ], + const Text('Payout network'), const SizedBox(height: 8), DropdownButtonFormField( initialValue: types.any((t) => t.code == _selectedWalletType) @@ -210,7 +279,9 @@ class _WithdrawScreenState extends State { ), ) .toList(), - onChanged: (v) => setState(() => _selectedWalletType = v), + onChanged: formEnabled + ? (v) => setState(() => _selectedWalletType = v) + : null, ), const SizedBox(height: 8), Container( @@ -226,7 +297,7 @@ class _WithdrawScreenState extends State { const SizedBox(width: 8), Expanded( child: Text( - 'Network: $networkLabel (auto-selected, cannot be changed)', + 'Network: $networkLabel (payout rail; balance is unified USDT)', style: Theme.of(context).textTheme.bodySmall, ), ), @@ -236,6 +307,7 @@ class _WithdrawScreenState extends State { const SizedBox(height: 16), TextField( controller: _addressController, + enabled: formEnabled, decoration: InputDecoration( labelText: 'Destination address', hintText: CoinDisplay.addressPlaceholder(selectedType.code), @@ -258,6 +330,7 @@ class _WithdrawScreenState extends State { if (feeRaw > BigInt.zero) const SizedBox(height: 16), TextField( controller: _amountController, + enabled: formEnabled, keyboardType: const TextInputType.numberWithOptions( decimal: true, ), @@ -266,12 +339,10 @@ class _WithdrawScreenState extends State { prefixIcon: Icon(Icons.attach_money), ), ), - if (balances.any( - (b) => b.walletType.code == _selectedWalletType, - )) ...[ + if (spendable != null) ...[ const SizedBox(height: 8), Text( - 'Available: ${rawAmountToHuman(balances.firstWhere((b) => b.walletType.code == _selectedWalletType).available, selectedType.decimals)} $_selectedWalletType', + 'Available: ${rawAmountToHuman(spendable.available, _kLedgerUsdtDecimals)} USDT', style: Theme.of(context).textTheme.bodySmall, ), ], @@ -280,6 +351,7 @@ class _WithdrawScreenState extends State { const SizedBox(height: 8), TextField( controller: _totpController, + enabled: formEnabled, keyboardType: TextInputType.number, maxLength: 6, decoration: const InputDecoration( @@ -301,7 +373,7 @@ class _WithdrawScreenState extends State { ), const SizedBox(height: 24), FilledButton( - onPressed: () => _submitWithdraw(context), + onPressed: formEnabled ? () => _submitWithdraw(context) : null, child: const Text('Withdraw'), ), ], diff --git a/prediqo_mobile/lib/features/wallet/utils/withdraw_eligibility.dart b/prediqo_mobile/lib/features/wallet/utils/withdraw_eligibility.dart new file mode 100644 index 00000000..9ada9f5d --- /dev/null +++ b/prediqo_mobile/lib/features/wallet/utils/withdraw_eligibility.dart @@ -0,0 +1,67 @@ +/// Shared withdraw eligibility (global kill-switch, rails, fee vs balance). +library; + +enum WithdrawBlockReason { globalOff, noNetwork, insufficientForFee } + +class WithdrawEligibility { + const WithdrawEligibility({ + required this.allowed, + this.reason, + required this.maxReceivableRaw, + required this.feeRaw, + required this.availableRaw, + }); + + final bool allowed; + final WithdrawBlockReason? reason; + final BigInt maxReceivableRaw; + final BigInt feeRaw; + final BigInt availableRaw; +} + +/// Ledger amounts are 6-decimal micro-USDT. Allowed when global on, ≥1 rail, +/// and available > fee (at least 1 micro receivable after fee). +WithdrawEligibility computeWithdrawEligibility({ + required bool withdrawalsEnabled, + required bool hasWithdrawNetwork, + required String availableRaw, + required String feeRaw, +}) { + final available = BigInt.tryParse(availableRaw.trim()) ?? BigInt.zero; + final fee = BigInt.tryParse(feeRaw.trim()) ?? BigInt.zero; + final maxReceivable = available > fee ? available - fee : BigInt.zero; + + if (!withdrawalsEnabled) { + return WithdrawEligibility( + allowed: false, + reason: WithdrawBlockReason.globalOff, + maxReceivableRaw: maxReceivable, + feeRaw: fee, + availableRaw: available, + ); + } + if (!hasWithdrawNetwork) { + return WithdrawEligibility( + allowed: false, + reason: WithdrawBlockReason.noNetwork, + maxReceivableRaw: maxReceivable, + feeRaw: fee, + availableRaw: available, + ); + } + if (maxReceivable <= BigInt.zero) { + return WithdrawEligibility( + allowed: false, + reason: WithdrawBlockReason.insufficientForFee, + maxReceivableRaw: maxReceivable, + feeRaw: fee, + availableRaw: available, + ); + } + return WithdrawEligibility( + allowed: true, + maxReceivableRaw: maxReceivable, + feeRaw: fee, + availableRaw: available, + ); +} diff --git a/prediqo_web/src/features/wallet/WalletPage.tsx b/prediqo_web/src/features/wallet/WalletPage.tsx index fd38c103..18412127 100644 --- a/prediqo_web/src/features/wallet/WalletPage.tsx +++ b/prediqo_web/src/features/wallet/WalletPage.tsx @@ -12,6 +12,7 @@ import { Stack, Tab, Tabs, + Tooltip, Typography, } from '@mui/material'; import AccountBalanceWalletRoundedIcon from '@mui/icons-material/AccountBalanceWalletRounded'; @@ -35,6 +36,7 @@ import type { WalletActivityCategory } from './types'; import { networkLabel } from './utils/coinDisplay'; import { USDT_WALLET_CODE } from './utils/walletCapabilities'; import { rawToHuman } from './utils/walletFormat'; +import { computeWithdrawEligibility } from './utils/withdrawEligibility'; type DialogKind = 'receive' | 'transfer' | 'withdraw' | null; @@ -69,6 +71,35 @@ export function WalletPage() { const depositable = useMemo(() => networks.filter((n) => n.depositEnabled), [networks]); const withdrawable = useMemo(() => networks.filter((n) => n.withdrawEnabled), [networks]); + const withdrawEligibility = useMemo( + () => + computeWithdrawEligibility({ + withdrawalsEnabled: healthQ.data?.withdrawalsEnabled ?? false, + hasWithdrawNetwork: withdrawable.length > 0, + availableRaw: spendable?.available ?? '0', + feeRaw: healthQ.data?.withdrawalNetworkFeeRaw ?? '0', + }), + [healthQ.data, withdrawable.length, spendable?.available] + ); + + const withdrawBlockReasonText = useMemo(() => { + switch (withdrawEligibility.reason) { + case 'global_off': + return t('wallet.withdrawDisabledGlobal'); + case 'no_network': + return t('wallet.withdrawDisabledNoNetwork'); + case 'insufficient_for_fee': + return t('wallet.withdrawDisabledInsufficientFee', { + fee: rawToHuman( + withdrawEligibility.feeRaw.toString(), + spendable?.walletType.decimals ?? 6 + ), + }); + default: + return ''; + } + }, [withdrawEligibility, t, spendable?.walletType.decimals]); + const refreshAll = async () => { await Promise.all([balancesQ.refetch(), txQ.refetch(), healthQ.refetch()]); setToast(t('common.walletRefreshed')); @@ -86,8 +117,8 @@ export function WalletPage() { return; } if (kind === 'withdraw') { - if (withdrawable.length === 0) { - setToast(t('wallet.withdrawDialog.noNetworks')); + if (!withdrawEligibility.allowed) { + setToast(withdrawBlockReasonText || t('wallet.withdrawDialog.noNetworks')); return; } const ok = !asset || withdrawable.some((n) => n.code === asset); @@ -190,17 +221,39 @@ export function WalletPage() { > {t('wallet.send')} - + + + + + {!withdrawEligibility.allowed && withdrawBlockReasonText && ( + + {withdrawBlockReasonText} + + )} + {withdrawEligibility.allowed && withdrawEligibility.feeRaw > 0n && spendable && ( + + {t('wallet.maxWithdrawableHint', { + amount: rawToHuman( + withdrawEligibility.maxReceivableRaw.toString(), + spendable.walletType.decimals + ), + })} + + )} fee + * (so at least 1 micro-USDT can be received after the ledger fee). + */ +export function computeWithdrawEligibility(input: { + withdrawalsEnabled: boolean; + hasWithdrawNetwork: boolean; + availableRaw: string; + feeRaw: string; +}): WithdrawEligibility { + const availableRaw = parseRaw(input.availableRaw); + const feeRaw = parseRaw(input.feeRaw); + const maxReceivableRaw = availableRaw > feeRaw ? availableRaw - feeRaw : 0n; + + if (!input.withdrawalsEnabled) { + return { allowed: false, reason: 'global_off', maxReceivableRaw, feeRaw, availableRaw }; + } + if (!input.hasWithdrawNetwork) { + return { allowed: false, reason: 'no_network', maxReceivableRaw, feeRaw, availableRaw }; + } + if (maxReceivableRaw <= 0n) { + return { allowed: false, reason: 'insufficient_for_fee', maxReceivableRaw, feeRaw, availableRaw }; + } + return { allowed: true, reason: null, maxReceivableRaw, feeRaw, availableRaw }; +} diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index 2247f04b..014e8d1b 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -309,6 +309,12 @@ export const en = { receiveUsdt: 'Receive USDT', send: 'Send', withdraw: 'Withdraw', + withdrawDisabledGlobal: 'Withdrawals are temporarily disabled by the platform.', + withdrawDisabledNoNetwork: 'No withdrawal network is enabled right now.', + withdrawDisabledInsufficientFee: + 'Insufficient balance for a withdrawal (need more than the {{fee}} USDT network fee).', + withdrawDisabledHint: 'Withdraw is unavailable: {{reason}}', + maxWithdrawableHint: 'You can withdraw up to {{amount}} USDT after the network fee.', tabAsset: 'Asset', tabActivity: 'Activity', activityTab: { diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index 4c434a74..7a0e7e62 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -317,6 +317,12 @@ export const fr = { receiveUsdt: 'Recevoir USDT', send: 'Envoyer', withdraw: 'Retirer', + withdrawDisabledGlobal: 'Les retraits sont temporairement désactivés par la plateforme.', + withdrawDisabledNoNetwork: 'Aucun réseau de retrait n’est activé pour le moment.', + withdrawDisabledInsufficientFee: + 'Solde insuffisant pour un retrait (il faut plus que les frais réseau de {{fee}} USDT).', + withdrawDisabledHint: 'Retrait indisponible : {{reason}}', + maxWithdrawableHint: 'Vous pouvez retirer jusqu’à {{amount}} USDT après les frais réseau.', tabAsset: 'Actif', tabActivity: 'Activité', activityTab: {