games_app/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart
2026-11-15 16:59:27 +02:00

627 lines
26 KiB
Dart

/// Wallet presentation: on-chain withdrawal form with 2FA confirmation.
library;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:uuid/uuid.dart';
import '../../../core/di/injection.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/amount_utils.dart';
import '../../../core/utils/coin_display.dart';
import '../../../data/repositories/wallet_repository_impl.dart';
import '../../../domain/repositories/health_repository.dart';
import '../../../domain/repositories/repositories.dart';
import '../../../l10n/app_strings.dart';
import '../../../shared/widgets/app_snackbar.dart';
import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_skeleton.dart';
import '../../../shared/widgets/section_error.dart';
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../bloc/wallet_bloc.dart';
import '../utils/money_confirm_preflight.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 {
const WithdrawScreen({super.key});
@override
State<WithdrawScreen> createState() => _WithdrawScreenState();
}
/// Validates inputs, shows a confirmation dialog, and dispatches [WalletWithdrawRequested].
class _WithdrawScreenState extends State<WithdrawScreen> {
final _addressController = TextEditingController();
final _amountController = TextEditingController();
final _totpController = TextEditingController();
String? _selectedWalletType;
String _networkFeeRaw = '0';
bool _withdrawalsEnabled = false;
bool _withdrawalsSuspended = false;
bool _healthLoaded = false;
bool _healthFailed = false;
bool _confirming = false;
/// One key per opened screen: a double tap or a retried request is not duplicated server-side.
final String _idempotencyKey = 'wd-${const Uuid().v4()}';
@override
void initState() {
super.initState();
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
_loadHealthFresh();
_loadWithdrawSecurityFlag();
}
Future<void> _loadWithdrawSecurityFlag() async {
try {
final cached = sl<AuthRepository>().peekLastProfile();
if (cached != null && mounted) {
setState(() => _withdrawalsSuspended = cached.withdrawalsSuspended);
}
final profile = await sl<AuthRepository>().getProfile(force: true);
if (!mounted) return;
setState(() => _withdrawalsSuspended = profile.withdrawalsSuspended);
} catch (_) {
// Keep last known flag; API still returns a clear error on submit.
}
}
Future<void> _loadHealthFresh() async {
try {
final health = await sl<HealthRepository>().getHealth();
if (!mounted) return;
setState(() {
_networkFeeRaw = health.withdrawalNetworkFeeRaw;
_withdrawalsEnabled = health.withdrawalsEnabled;
_healthLoaded = true;
_healthFailed = false;
});
} catch (_) {
if (!mounted) return;
setState(() {
_withdrawalsEnabled = false;
_healthLoaded = true;
_healthFailed = true;
});
}
}
Future<void> _refreshAll() async {
context.read<WalletBloc>().add(const WalletLoadRequested());
await Future.wait([_loadHealthFresh(), _loadWithdrawSecurityFlag()]);
}
@override
void dispose() {
_addressController.dispose();
_amountController.dispose();
_totpController.dispose();
super.dispose();
}
Future<void> _submitWithdraw() async {
if (_confirming) return;
final s = context.strings;
if (!_healthLoaded || _healthFailed) {
showErrorSnackBar(context, s.couldNotVerifyWithdrawStatus);
await _loadHealthFresh();
return;
}
if (_withdrawalsSuspended) {
showErrorSnackBar(context, s.withdrawalsSuspendedAccount);
return;
}
if (!_withdrawalsEnabled) {
showErrorSnackBar(context, s.withdrawalsDisabled);
return;
}
if (_addressController.text.isEmpty ||
_amountController.text.isEmpty ||
_totpController.text.length != 6) {
showErrorSnackBar(context, s.fillWithdrawFields);
return;
}
final state = context.read<WalletBloc>().state;
final enabledRails =
state.walletTypes.where((t) => t.withdrawEnabled == true).toList();
final railCode = (_selectedWalletType != null &&
enabledRails.any((t) => t.code == _selectedWalletType))
? _selectedWalletType!
: (enabledRails.isNotEmpty ? enabledRails.first.code : null);
if (railCode == null) {
showErrorSnackBar(context, s.noWithdrawNetworks);
return;
}
final amountHuman = _amountController.text.trim();
final amountRaw = humanAmountToRaw(amountHuman, _kLedgerUsdtDecimals);
if (amountRaw == '0') {
showErrorSnackBar(context, s.enterValidAmount);
return;
}
setState(() => _confirming = true);
try {
final preflight = await fetchMoneyConfirmPreflight(
walletRepo: sl<WalletRepository>(),
healthRepo: sl<HealthRepository>(),
);
if (!mounted) return;
setState(() {
_networkFeeRaw = preflight.health.withdrawalNetworkFeeRaw;
_withdrawalsEnabled = preflight.health.withdrawalsEnabled;
_healthLoaded = true;
_healthFailed = false;
});
context.read<WalletBloc>().add(const WalletLoadRequested());
if (_withdrawalsSuspended) {
showErrorSnackBar(context, s.withdrawalsSuspendedAccount);
return;
}
if (!preflight.health.withdrawalsEnabled) {
showErrorSnackBar(context, s.withdrawalsDisabled);
return;
}
final feeRaw =
CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, _kLedgerUsdtDecimals);
final totalRaw = BigInt.parse(amountRaw) + feeRaw;
if (preflight.balances.isEmpty) {
showErrorSnackBar(context, s.walletBalanceNotLoaded);
return;
}
final balance = preflight.balances.firstWhere(
(b) => b.walletType.code == _kLedgerUsdtCode,
orElse: () => preflight.balances.first,
);
final available = BigInt.tryParse(balance.available) ?? BigInt.zero;
if (totalRaw > available) {
showErrorSnackBar(
context,
'${s.insufficientBalance} — ${s.withdrawTotalDebited(rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals))}',
);
return;
}
final feeHuman = rawAmountToHuman(feeRaw.toString(), _kLedgerUsdtDecimals);
final address = _addressController.text.trim();
final confirmed = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(s.confirmWithdrawal),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(s.withdrawYouReceive(amountHuman)),
if (feeRaw > BigInt.zero) ...[
const SizedBox(height: 8),
Text(s.withdrawNetworkFee(feeHuman)),
Text(
s.withdrawTotalDebited(
rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals),
),
),
],
const SizedBox(height: 8),
SelectableText('To: $address'),
const SizedBox(height: 16),
Text(
s.withdrawIrreversibleHint,
style: Theme.of(ctx).textTheme.bodySmall,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: Text(s.cancel),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: Text(s.confirmAction),
),
],
),
);
if (confirmed == true && mounted) {
context.read<WalletBloc>().add(
WalletWithdrawRequested(
walletType: railCode,
toAddress: address,
amount: amountRaw,
totpCode: _totpController.text,
idempotencyKey: _idempotencyKey,
),
);
}
} catch (_) {
if (!mounted) return;
showErrorSnackBar(context, s.couldNotRefreshBalance);
} finally {
if (mounted) setState(() => _confirming = false);
}
}
@override
Widget build(BuildContext context) {
final s = context.strings;
final bottomInset = MediaQuery.paddingOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('withdraw_screen'),
body: Column(
children: [
TlotoGradientAppBar(title: s.withdraw, showBack: true),
Expanded(
child: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.errorMessage != curr.errorMessage ||
prev.withdrawTxId != curr.withdrawTxId,
listener: (context, state) {
if (state.errorMessage != null &&
state.errorMessage!.isNotEmpty) {
showErrorSnackBar(context, state.errorMessage!);
context.read<WalletBloc>().add(const WalletClearFeedback());
}
if (state.withdrawTxId != null) {
showSuccessSnackBar(context, s.withdrawalSubmitted);
context.read<WalletBloc>().add(const WalletClearFeedback());
context.pop();
}
},
builder: (context, state) {
final loadingEmpty = !state.isLoaded && state.balances.isEmpty;
if (loadingEmpty) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
children: const [
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 48),
],
);
}
if (_healthFailed && state.balances.isEmpty) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
children: [
SectionError(
message: s.couldNotVerifyWithdrawStatus,
onRetry: _refreshAll,
),
],
);
}
final types = state.walletTypes
.where((t) => t.withdrawEnabled == true)
.toList();
final balances = state.balances;
if (types.isEmpty) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(
40,
40,
40,
40 + bottomInset,
),
children: [
Icon(
Icons.account_balance_outlined,
size: 48,
color: Theme.of(context).colorScheme.outline,
),
const SizedBox(height: 16),
Text(
s.noWithdrawNetworks,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge,
),
const SizedBox(height: 12),
Center(
child: TextButton(
onPressed: _refreshAll,
child: Text(s.retry),
),
),
],
);
}
final selectedCode = (_selectedWalletType != null &&
types.any((t) => t.code == _selectedWalletType))
? _selectedWalletType!
: types.first.code;
if (_selectedWalletType != selectedCode) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() => _selectedWalletType = selectedCode);
}
});
}
final selectedType =
types.firstWhere((t) => t.code == selectedCode);
final networkLabel =
CoinDisplay.networkLabel(selectedType.code);
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,
withdrawalsSuspended: _withdrawalsSuspended,
);
final formEnabled = _healthLoaded &&
!_healthFailed &&
eligibility.allowed &&
!_confirming;
return RefreshIndicator(
onRefresh: _refreshAll,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_healthFailed) ...[
SectionError(
compact: true,
message: s.couldNotVerifyFees,
onRetry: _loadHealthFresh,
),
const SizedBox(height: 12),
],
if (_healthLoaded && !eligibility.allowed) ...[
PredCard(
padding: const EdgeInsets.all(12),
child: Text(
switch (eligibility.reason) {
WithdrawBlockReason.accountSuspended =>
s.withdrawalsSuspendedAccount,
WithdrawBlockReason.globalOff =>
s.withdrawalsDisabled,
WithdrawBlockReason.noNetwork =>
s.noWithdrawNetworks,
WithdrawBlockReason.insufficientForFee =>
'${s.insufficientBalance} ($feeHuman USDT).',
null => s.withdrawalsDisabled,
},
style: Theme.of(context).textTheme.bodySmall,
),
),
const SizedBox(height: 12),
],
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (eligibility.allowed &&
feeRaw > BigInt.zero &&
spendable != null) ...[
Text(
s.withdrawMaxAfterFee(
rawAmountToHuman(
eligibility.maxReceivableRaw.toString(),
_kLedgerUsdtDecimals,
),
),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
],
Text(
s.payoutNetwork,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
key: ValueKey('withdraw_rail_$selectedCode'),
isExpanded: true,
initialValue: selectedCode,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(
'${t.name} — ${CoinDisplay.networkLabel(t.code)}',
overflow: TextOverflow.ellipsis,
),
),
)
.toList(),
onChanged: formEnabled
? (v) => setState(
() => _selectedWalletType = v,
)
: null,
),
const SizedBox(height: 10),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.link_rounded,
size: 20,
color: AppColors.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
s.withdrawPayoutRailHint(networkLabel),
style: Theme.of(context)
.textTheme
.bodySmall,
),
),
],
),
const SizedBox(height: 14),
TextField(
controller: _addressController,
enabled: formEnabled,
decoration: InputDecoration(
labelText: s.destinationAddress,
hintText: CoinDisplay.addressPlaceholder(
selectedType.code,
),
prefixIcon: const Icon(
Icons.account_balance_wallet_outlined,
),
),
),
if (feeRaw > BigInt.zero) ...[
const SizedBox(height: 12),
Text(
s.withdrawFeeBanner(feeHuman),
style:
Theme.of(context).textTheme.bodySmall,
),
],
const SizedBox(height: 12),
TextField(
controller: _amountController,
enabled: formEnabled,
keyboardType:
const TextInputType.numberWithOptions(
decimal: true,
),
decoration: InputDecoration(
labelText: s.amountToReceive,
prefixIcon:
const Icon(Icons.attach_money),
),
),
if (spendable != null) ...[
const SizedBox(height: 8),
Text(
s.availableUsdt(
rawAmountToHuman(
spendable.available,
_kLedgerUsdtDecimals,
),
),
key: const Key('withdraw_available'),
style:
Theme.of(context).textTheme.bodySmall,
),
],
],
),
),
const SizedBox(height: 12),
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
s.totpRequiredWithdraw,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
TextField(
controller: _totpController,
enabled: formEnabled,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(
labelText: s.totpSixDigit,
prefixIcon: const Icon(Icons.security),
),
),
const SizedBox(height: 8),
Text(
s.withdrawWrongNetworkWarn(networkLabel),
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(color: AppColors.warning),
),
],
),
),
const SizedBox(height: 20),
FilledButton(
key: const Key('withdraw_submit'),
onPressed: formEnabled ? _submitWithdraw : null,
child: _confirming
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Text(s.withdraw),
),
],
),
),
);
},
),
),
],
),
),
);
}
}