After refonte for the options of Profile4

This commit is contained in:
Your Name 2026-10-25 18:21:07 +02:00
parent 3e18a4df25
commit e5f52cf3cc
5 changed files with 1197 additions and 856 deletions

View File

@ -2,15 +2,18 @@
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 '../../../core/errors/app_exception.dart';
import '../../../core/theme/app_theme.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/coin_display.dart';
import '../../../data/models/wallet_type_model.dart';
import '../../../l10n/app_strings.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';
/// Lets the user choose USDT before opening the deposit address screen.
@ -18,7 +21,8 @@ class DepositAssetSelectScreen extends StatefulWidget {
const DepositAssetSelectScreen({super.key});
@override
State<DepositAssetSelectScreen> createState() => _DepositAssetSelectScreenState();
State<DepositAssetSelectScreen> createState() =>
_DepositAssetSelectScreenState();
}
/// Loads wallet types on init and renders the asset picker list.
@ -32,107 +36,128 @@ class _DepositAssetSelectScreenState extends State<DepositAssetSelectScreen> {
@override
Widget build(BuildContext context) {
final s = context.strings;
return Scaffold(
key: const Key('deposit_asset_select_screen'),
appBar: AppBar(
title: Text(s.deposit),
flexibleSpace: Container(
decoration: const BoxDecoration(gradient: AppTheme.goldGradient),
),
),
body: BlocBuilder<WalletBloc, WalletState>(
builder: (context, state) {
final types =
state.walletTypes.where((t) => t.depositEnabled == true).toList();
// Keep skeleton while core wallet load is in flight, or before any
// balances/types snapshot exists (types resolve after balances).
final loading = types.isEmpty &&
(state.isLoading ||
(state.balances.isEmpty &&
state.walletTypes.isEmpty &&
(state.errorMessage == null || state.errorMessage!.isEmpty)));
final failed = state.errorMessage != null &&
state.errorMessage!.isNotEmpty &&
types.isEmpty &&
!state.isLoading;
final bottomInset = MediaQuery.paddingOf(context).bottom;
if (loading) {
return ListView(
padding: const EdgeInsets.all(20),
children: const [
PredSkeletonCard(height: 72),
SizedBox(height: 12),
PredSkeletonCard(height: 72),
],
);
}
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('deposit_asset_select_screen'),
body: Column(
children: [
TlotoGradientAppBar(title: s.deposit, showBack: true),
Expanded(
child: BlocBuilder<WalletBloc, WalletState>(
builder: (context, state) {
final types = state.walletTypes
.where((t) => t.depositEnabled == true)
.toList();
final loading = types.isEmpty &&
(state.isLoading ||
(state.balances.isEmpty &&
state.walletTypes.isEmpty &&
(state.errorMessage == null ||
state.errorMessage!.isEmpty)));
final failed = state.errorMessage != null &&
state.errorMessage!.isNotEmpty &&
types.isEmpty &&
!state.isLoading;
if (failed) {
return ListView(
padding: const EdgeInsets.all(20),
children: [
SectionError(
message: state.errorMessage ?? AppException.connectionFailedMessage,
onRetry: () => context
.read<WalletBloc>()
.add(const WalletLoadRequested()),
),
],
);
}
if (loading) {
return ListView(
padding:
EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset),
children: const [
PredSkeletonCard(height: 72),
SizedBox(height: 12),
PredSkeletonCard(height: 72),
],
);
}
if (types.isEmpty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.account_balance_wallet_rounded,
size: 48,
color: Theme.of(context).colorScheme.outline,
if (failed) {
return ListView(
padding:
EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset),
children: [
SectionError(
message: state.errorMessage ??
AppException.connectionFailedMessage,
onRetry: () => context
.read<WalletBloc>()
.add(const WalletLoadRequested()),
),
],
);
}
if (types.isEmpty) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding:
EdgeInsets.fromLTRB(40, 40, 40, 40 + bottomInset),
children: [
Icon(
Icons.account_balance_wallet_rounded,
size: 48,
color: Theme.of(context).colorScheme.outline,
),
const SizedBox(height: 16),
Text(
s.noDepositOptions,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge,
),
],
);
}
return RefreshIndicator(
onRefresh: () async {
context
.read<WalletBloc>()
.add(const WalletLoadRequested());
},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding:
EdgeInsets.fromLTRB(20, 16, 20, 24 + bottomInset),
children: [
Text(
s.chooseDepositAsset,
style:
Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 8),
Text(
s.chooseDepositAssetHint,
style:
Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context)
.colorScheme
.onSurfaceVariant,
),
),
const SizedBox(height: 20),
...types.map(
(wt) => Padding(
padding: const EdgeInsets.only(bottom: 10),
child: _DepositAssetTile(walletType: wt),
),
),
],
),
const SizedBox(height: 16),
Text(
'No deposit options available',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge,
),
],
),
);
},
),
);
}
return RefreshIndicator(
onRefresh: () async {
context.read<WalletBloc>().add(const WalletLoadRequested());
},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(20),
children: [
Text(
'Choose asset to deposit',
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onSurface,
),
),
const SizedBox(height: 8),
Text(
'Select a deposit network (TRON TRC20 or BSC BEP20). Credits go to your single USDT balance for predictions.',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 20),
...types.map((wt) => _DepositAssetTile(walletType: wt)),
],
),
);
},
],
),
),
);
}
@ -146,40 +171,38 @@ class _DepositAssetTile extends StatelessWidget {
@override
Widget build(BuildContext context) {
final network = CoinDisplay.networkLabel(walletType.code);
return Card(
margin: const EdgeInsets.only(bottom: 12),
child: InkWell(
onTap: () => context.push('/deposit/${walletType.code}'),
borderRadius: BorderRadius.circular(16),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
child: Row(
children: [
CoinDisplay.iconWidget(context, walletType.code, size: 48),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
walletType.name,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
network,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
return PredCard(
padding: EdgeInsets.zero,
onTap: () => context.push('/deposit/${walletType.code}'),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
CoinDisplay.iconWidget(context, walletType.code, size: 44),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
walletType.name,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 2),
Text(
network,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color:
Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
Icon(Icons.chevron_right_rounded, color: AppColors.goldDark),
],
),
),
const Icon(Icons.chevron_right_rounded, color: AppColors.primary),
],
),
),
);

View File

@ -6,10 +6,14 @@ import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../../core/errors/app_exception.dart';
import '../../../core/theme/app_colors.dart';
import '../../../core/utils/coin_display.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';
/// Shows the blockchain deposit address and QR code for [walletTypeCode].
@ -32,7 +36,9 @@ class _DepositScreenState extends State<DepositScreen> {
if (bloc.state.walletTypes.isEmpty) {
bloc.add(const WalletLoadRequested(ifStale: true));
}
bloc.add(WalletDepositAddressRequested(walletTypeCode: widget.walletTypeCode));
bloc.add(
WalletDepositAddressRequested(walletTypeCode: widget.walletTypeCode),
);
}
void _retry() {
@ -40,183 +46,226 @@ class _DepositScreenState extends State<DepositScreen> {
if (bloc.state.walletTypes.isEmpty) {
bloc.add(const WalletLoadRequested());
}
bloc.add(WalletDepositAddressRequested(walletTypeCode: widget.walletTypeCode));
bloc.add(
WalletDepositAddressRequested(walletTypeCode: widget.walletTypeCode),
);
}
@override
Widget build(BuildContext context) {
final s = context.strings;
return Scaffold(
key: const Key('deposit_screen'),
appBar: AppBar(title: Text('${s.deposit} ${widget.walletTypeCode}')),
body: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.walletTypes.isEmpty && curr.walletTypes.isNotEmpty,
listener: (context, state) {
// Types arrived after soft load — request address now.
if (state.depositWalletType?.code != widget.walletTypeCode ||
state.depositAddress == null) {
context.read<WalletBloc>().add(
WalletDepositAddressRequested(walletTypeCode: widget.walletTypeCode),
);
}
},
builder: (context, state) {
final matching = state.depositWalletType?.code == widget.walletTypeCode;
final address = matching ? state.depositAddress : null;
final wt = matching ? state.depositWalletType : null;
final error = state.errorMessage;
final loading = address == null &&
(state.isLoading || state.walletTypes.isEmpty || error == null);
final bottomInset = MediaQuery.paddingOf(context).bottom;
if (address == null || wt == null) {
if (error != null && error.isNotEmpty && !state.isLoading) {
return ListView(
padding: const EdgeInsets.all(24),
children: [
SectionError(
message: error,
onRetry: _retry,
),
],
);
}
if (loading) {
return ListView(
padding: const EdgeInsets.all(24),
children: const [
PredSkeletonCard(height: 120),
SizedBox(height: 16),
PredSkeletonCard(height: 220),
SizedBox(height: 16),
PredSkeletonCard(height: 56),
],
);
}
return ListView(
padding: const EdgeInsets.all(24),
children: [
SectionError(
message: AppException.connectionFailedMessage,
onRetry: _retry,
),
],
);
}
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('deposit_screen'),
body: Column(
children: [
TlotoGradientAppBar(
title: '${s.deposit} ${widget.walletTypeCode}',
showBack: true,
),
Expanded(
child: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.walletTypes.isEmpty && curr.walletTypes.isNotEmpty,
listener: (context, state) {
if (state.depositWalletType?.code != widget.walletTypeCode ||
state.depositAddress == null) {
context.read<WalletBloc>().add(
WalletDepositAddressRequested(
walletTypeCode: widget.walletTypeCode,
),
);
}
},
builder: (context, state) {
final matching =
state.depositWalletType?.code == widget.walletTypeCode;
final address = matching ? state.depositAddress : null;
final wt = matching ? state.depositWalletType : null;
final error = state.errorMessage;
final loading = address == null &&
(state.isLoading ||
state.walletTypes.isEmpty ||
error == null);
final network = CoinDisplay.networkLabel(wt.code);
return RefreshIndicator(
onRefresh: () async => _retry(),
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(24),
child: Column(
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.surfaceContainerHighest
.withValues(alpha: 0.7),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Theme.of(context)
.colorScheme
.outline
.withValues(alpha: 0.4),
),
),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.info_outline_rounded,
size: 20,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'Network is automatically selected. You cannot change it.',
style: Theme.of(context).textTheme.titleSmall?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
),
),
],
if (address == null || wt == null) {
if (error != null &&
error.isNotEmpty &&
!state.isLoading) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
const SizedBox(height: 8),
Text(
'Send only $network — ${wt.name} to this address. Sending any other asset or using a different network may result in permanent loss.',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
children: [
SectionError(message: error, onRetry: _retry),
],
);
}
if (loading) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
children: const [
PredSkeletonCard(height: 120),
SizedBox(height: 16),
PredSkeletonCard(height: 220),
SizedBox(height: 16),
PredSkeletonCard(height: 56),
],
);
}
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
children: [
SectionError(
message: AppException.connectionFailedMessage,
onRetry: _retry,
),
],
);
}
final network = CoinDisplay.networkLabel(wt.code);
return RefreshIndicator(
onRefresh: () async => _retry(),
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
child: Column(
children: [
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.info_outline_rounded,
size: 20,
color: AppColors.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
s.depositNetworkLocked,
style: Theme.of(context)
.textTheme
.titleSmall
?.copyWith(
fontWeight: FontWeight.w700,
),
),
),
],
),
const SizedBox(height: 8),
Text(
s.depositSendOnlyWarning(network, wt.name),
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: AppColors.textSecondary,
),
),
],
),
),
const SizedBox(height: 20),
Text(
'${s.deposit} ${wt.name}',
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(fontWeight: FontWeight.w800),
textAlign: TextAlign.center,
),
const SizedBox(height: 6),
Text(
s.depositNetworkLabel(network),
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: AppColors.primary,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 20),
PredCard(
padding: const EdgeInsets.all(16),
child: Column(
children: [
QrImageView(
data: address,
version: QrVersions.auto,
size: 200,
backgroundColor: Colors.white,
),
const SizedBox(height: 16),
SelectableText(
address,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: 'monospace',
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 14),
FilledButton.icon(
onPressed: () {
Clipboard.setData(
ClipboardData(text: address),
);
showSuccessSnackBar(
context,
s.addressCopied,
);
},
icon: const Icon(Icons.copy_rounded),
label: Text(s.copyAddress),
),
],
),
),
const SizedBox(height: 16),
Text(
s.depositConfirmationsHint(wt.name, network),
style: Theme.of(context).textTheme.bodySmall,
textAlign: TextAlign.center,
),
],
),
),
),
const SizedBox(height: 20),
Text(
'${s.deposit} ${wt.name}',
style: Theme.of(context).textTheme.titleMedium,
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
'Network: $network',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.primary,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 24),
QrImageView(
data: address,
version: QrVersions.auto,
size: 220,
backgroundColor: Colors.white,
),
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: SelectableText(
address,
style: const TextStyle(fontFamily: 'monospace'),
),
),
const SizedBox(height: 16),
FilledButton.icon(
onPressed: () {
Clipboard.setData(ClipboardData(text: address));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Address copied to clipboard')),
);
},
icon: const Icon(Icons.copy),
label: const Text('Copy address'),
style: FilledButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
),
),
const SizedBox(height: 24),
Text(
'Deposits are credited after blockchain confirmations. Only send ${wt.name} on $network to this address.',
style: Theme.of(context).textTheme.bodySmall,
textAlign: TextAlign.center,
),
],
);
},
),
),
);
},
],
),
),
);
}

View File

@ -2,6 +2,7 @@
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 '../../../core/di/injection.dart';
@ -13,8 +14,10 @@ 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';
@ -68,6 +71,11 @@ class _TransferScreenState extends State<TransferScreen> {
}
}
Future<void> _refreshAll() async {
context.read<WalletBloc>().add(const WalletLoadRequested());
await _loadSecurityContext(forceProfile: true);
}
@override
void dispose() {
_emailController.dispose();
@ -83,7 +91,7 @@ class _TransferScreenState extends State<TransferScreen> {
if (_needs2faSetup) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(this.context, s.transferTwoFaRequiredBody);
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
return;
}
@ -91,13 +99,13 @@ class _TransferScreenState extends State<TransferScreen> {
_emailController.text.trim().isEmpty ||
_amountController.text.isEmpty) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(this.context, s.transferFillFields);
showErrorSnackBar(context, s.transferFillFields);
return;
}
if (_requireWithdrawal2fa && _totpController.text.trim().length != 6) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(this.context, s.transferFillFields);
showErrorSnackBar(context, s.transferFillFields);
return;
}
@ -109,14 +117,13 @@ class _TransferScreenState extends State<TransferScreen> {
final amountHuman = _amountController.text.trim();
final amountRaw = humanAmountToRaw(amountHuman, selectedType.decimals);
if (amountRaw == '0') {
setState(() => _localError = 'Enter a valid amount');
showErrorSnackBar(this.context, 'Enter a valid amount');
setState(() => _localError = s.enterValidAmount);
showErrorSnackBar(context, s.enterValidAmount);
return;
}
setState(() => _confirming = true);
try {
// Force fresh balance + health before money confirm (never trust display cache).
final preflight = await fetchMoneyConfirmPreflight(
walletRepo: sl<WalletRepository>(),
healthRepo: sl<HealthRepository>(),
@ -133,7 +140,7 @@ class _TransferScreenState extends State<TransferScreen> {
if (_requireWithdrawal2fa && _totpEnabled == false) {
setState(() => _localError = s.transferTwoFaRequiredBody);
showErrorSnackBar(this.context, s.transferTwoFaRequiredBody);
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
return;
}
@ -141,43 +148,43 @@ class _TransferScreenState extends State<TransferScreen> {
.where((b) => b.walletType.code == _selectedWalletType)
.toList();
if (match.isEmpty) {
showErrorSnackBar(this.context, 'Wallet balance not loaded');
showErrorSnackBar(context, s.walletBalanceNotLoaded);
return;
}
final available = BigInt.tryParse(match.first.available) ?? BigInt.zero;
final need = BigInt.tryParse(amountRaw) ?? BigInt.zero;
if (need > available) {
showErrorSnackBar(this.context, 'Insufficient balance');
showErrorSnackBar(context, s.insufficientBalance);
return;
}
final email = _emailController.text.trim().toLowerCase();
final confirmed = await showDialog<bool>(
context: this.context,
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Confirm transfer'),
title: Text(s.confirmTransfer),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Amount: $amountHuman $_selectedWalletType'),
Text('${s.amountLabel}: $amountHuman ${selectedType.name}'),
const SizedBox(height: 8),
Text('To: $email'),
SelectableText('${s.recipientEmail}: $email'),
const SizedBox(height: 16),
const Text(
'This will move balance to another user in this app. The recipient will see the balance immediately.',
style: TextStyle(fontSize: 13),
Text(
s.transferImmediateHint,
style: Theme.of(ctx).textTheme.bodySmall,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('Cancel'),
child: Text(s.cancel),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('Confirm'),
child: Text(s.confirmAction),
),
],
),
@ -196,7 +203,7 @@ class _TransferScreenState extends State<TransferScreen> {
}
} catch (_) {
if (!mounted) return;
showErrorSnackBar(this.context, 'Could not refresh balance. Try again.');
showErrorSnackBar(context, s.couldNotRefreshBalance);
} finally {
if (mounted) setState(() => _confirming = false);
}
@ -205,246 +212,320 @@ class _TransferScreenState extends State<TransferScreen> {
@override
Widget build(BuildContext context) {
final s = context.strings;
return Scaffold(
key: const Key('transfer_screen'),
appBar: AppBar(title: Text(s.transfer)),
body: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.errorMessage != curr.errorMessage ||
prev.transferTxId != curr.transferTxId,
listener: (context, state) {
if (state.errorMessage != null && state.errorMessage!.isNotEmpty) {
setState(() {
_submitting = false;
_localError = state.errorMessage;
});
showErrorSnackBar(context, state.errorMessage!);
context.read<WalletBloc>().add(const WalletClearFeedback());
}
if (state.transferTxId != null) {
setState(() => _submitting = false);
showSuccessSnackBar(context, s.transferCompleted);
context.read<WalletBloc>().add(const WalletClearFeedback());
context.pop();
}
},
builder: (context, state) {
if (!state.isLoaded && state.balances.isEmpty) {
return ListView(
padding: const EdgeInsets.all(24),
children: const [
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 48),
],
);
}
final types = state.walletTypes;
final balances = state.balances;
if (types.isEmpty) {
return ListView(
padding: const EdgeInsets.all(24),
children: [
SectionError(
message: state.errorMessage ?? 'No wallet types',
onRetry: () => context
.read<WalletBloc>()
.add(const WalletLoadRequested()),
),
],
);
}
_selectedWalletType ??= types.first.code;
final selectedTypeList = types.where(
(t) => t.code == _selectedWalletType,
);
final selectedType = selectedTypeList.isEmpty
? types.first
: selectedTypeList.first;
final networkLabel = CoinDisplay.networkLabel(selectedType.code);
final busy = _submitting || _confirming;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_securityFailed) ...[
SectionError(
compact: true,
message: 'Could not verify 2FA requirements.',
onRetry: () => _loadSecurityContext(forceProfile: true),
),
const SizedBox(height: 16),
],
if (_needs2faSetup) ...[
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppColors.warning.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: AppColors.warning.withValues(alpha: 0.4),
final bottomInset = MediaQuery.paddingOf(context).bottom;
return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle,
child: Scaffold(
key: const Key('transfer_screen'),
body: Column(
children: [
TlotoGradientAppBar(title: s.transfer, showBack: true),
Expanded(
child: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.errorMessage != curr.errorMessage ||
prev.transferTxId != curr.transferTxId,
listener: (context, state) {
if (state.errorMessage != null &&
state.errorMessage!.isNotEmpty) {
setState(() {
_submitting = false;
_localError = state.errorMessage;
});
showErrorSnackBar(context, state.errorMessage!);
context.read<WalletBloc>().add(const WalletClearFeedback());
}
if (state.transferTxId != null) {
setState(() => _submitting = false);
showSuccessSnackBar(context, s.transferCompleted);
context.read<WalletBloc>().add(const WalletClearFeedback());
context.pop();
}
},
builder: (context, state) {
if (!state.isLoaded && state.balances.isEmpty) {
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),
],
);
}
final types = state.walletTypes;
final balances = state.balances;
if (types.isEmpty) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.transferTwoFaRequiredTitle,
style: const TextStyle(fontWeight: FontWeight.w800),
),
const SizedBox(height: 6),
Text(
s.transferTwoFaRequiredBody,
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 10),
OutlinedButton(
onPressed: () => context.push('/totp-setup'),
child: Text(s.enableTwoFa),
SectionError(
message: state.errorMessage ?? s.walletBalanceNotLoaded,
onRetry: _refreshAll,
),
],
),
),
const SizedBox(height: 16),
],
if (_localError != null) ...[
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppColors.danger.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: AppColors.danger.withValues(alpha: 0.4),
);
}
_selectedWalletType ??= types.first.code;
if (!types.any((t) => t.code == _selectedWalletType)) {
_selectedWalletType = types.first.code;
}
final selectedType = types.firstWhere(
(t) => t.code == _selectedWalletType,
);
final networkLabel =
CoinDisplay.networkLabel(selectedType.code);
final busy = _submitting || _confirming;
return RefreshIndicator(
onRefresh: _refreshAll,
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
),
child: Text(
_localError!,
style: const TextStyle(
color: AppColors.danger,
fontWeight: FontWeight.w600,
padding: EdgeInsets.fromLTRB(
20,
16,
20,
24 + bottomInset,
),
),
),
const SizedBox(height: 16),
],
const Text('Recipient email'),
const SizedBox(height: 8),
TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
enabled: !_needs2faSetup && !busy,
decoration: const InputDecoration(
labelText: 'Email address',
prefixIcon: Icon(Icons.email_outlined),
),
),
const SizedBox(height: 16),
const Text('Asset'),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
initialValue: _selectedWalletType,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(t.name),
),
)
.toList(),
onChanged: (_needs2faSetup || busy)
? null
: (v) => setState(() => _selectedWalletType = v),
),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 10,
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.info_outline,
size: 20,
color: Theme.of(context).colorScheme.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
'Network: $networkLabel',
style: Theme.of(context).textTheme.bodySmall,
),
),
],
),
),
const SizedBox(height: 16),
TextField(
controller: _amountController,
enabled: !_needs2faSetup && !busy,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
decoration: const InputDecoration(
labelText: 'Amount',
prefixIcon: Icon(Icons.attach_money),
),
),
if (balances.any(
(b) => b.walletType.code == _selectedWalletType,
)) ...[
const SizedBox(height: 8),
Text(
'Available: ${rawAmountToHuman(balances.firstWhere((b) => b.walletType.code == _selectedWalletType).available, selectedType.decimals)} $_selectedWalletType',
key: const Key('transfer_available'),
style: Theme.of(context).textTheme.bodySmall,
),
],
if (!_needs2faSetup) ...[
const SizedBox(height: 16),
Text(s.transferTotpHint),
const SizedBox(height: 8),
TextField(
controller: _totpController,
enabled: !busy,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(
labelText: s.totpCode,
prefixIcon: const Icon(Icons.security),
),
),
],
const SizedBox(height: 24),
FilledButton(
key: const Key('transfer_submit'),
onPressed: busy ? null : _submitTransfer,
child: busy
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_securityFailed) ...[
SectionError(
compact: true,
message: s.couldNotVerify2fa,
onRetry: () =>
_loadSecurityContext(forceProfile: true),
),
const SizedBox(height: 12),
],
if (_needs2faSetup) ...[
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.transferTwoFaRequiredTitle,
style: const TextStyle(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 6),
Text(
s.transferTwoFaRequiredBody,
style:
Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 10),
OutlinedButton(
onPressed: () =>
context.push('/totp-setup'),
child: Text(s.enableTwoFa),
),
],
),
),
const SizedBox(height: 12),
],
if (_localError != null) ...[
PredCard(
padding: const EdgeInsets.all(14),
child: Text(
_localError!,
style: const TextStyle(
color: AppColors.danger,
fontWeight: FontWeight.w600,
),
),
),
const SizedBox(height: 12),
],
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
s.recipientEmail,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
TextField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
autocorrect: false,
enabled: !_needs2faSetup && !busy,
decoration: InputDecoration(
labelText: s.emailAddressLabel,
prefixIcon:
const Icon(Icons.email_outlined),
),
),
const SizedBox(height: 14),
Text(
s.assetLabel,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
DropdownButtonFormField<String>(
key: ValueKey(
'transfer_asset_$_selectedWalletType',
),
isExpanded: true,
initialValue: _selectedWalletType,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(
t.name,
overflow: TextOverflow.ellipsis,
),
),
)
.toList(),
onChanged: (_needs2faSetup || busy)
? null
: (v) => setState(
() => _selectedWalletType = v,
),
),
const SizedBox(height: 10),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(
Icons.info_outline,
size: 20,
color: AppColors.primary,
),
const SizedBox(width: 8),
Expanded(
child: Text(
s.depositNetworkLabel(networkLabel),
style: Theme.of(context)
.textTheme
.bodySmall,
),
),
],
),
const SizedBox(height: 14),
TextField(
controller: _amountController,
enabled: !_needs2faSetup && !busy,
keyboardType:
const TextInputType.numberWithOptions(
decimal: true,
),
decoration: InputDecoration(
labelText: s.amountLabel,
prefixIcon:
const Icon(Icons.attach_money),
),
),
if (balances.any(
(b) =>
b.walletType.code == _selectedWalletType,
)) ...[
const SizedBox(height: 8),
Text(
s.availableAsset(
rawAmountToHuman(
balances
.firstWhere(
(b) =>
b.walletType.code ==
_selectedWalletType,
)
.available,
selectedType.decimals,
),
selectedType.name,
),
key: const Key('transfer_available'),
style:
Theme.of(context).textTheme.bodySmall,
),
],
],
),
),
)
: Text(s.transfer),
),
],
if (!_needs2faSetup) ...[
const SizedBox(height: 12),
PredCard(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
s.transferTotpHint,
style: const TextStyle(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
TextField(
controller: _totpController,
enabled: !busy,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: InputDecoration(
labelText: s.totpCode,
prefixIcon:
const Icon(Icons.security),
),
),
],
),
),
],
const SizedBox(height: 20),
FilledButton(
key: const Key('transfer_submit'),
onPressed: busy ? null : _submitTransfer,
child: busy
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: Text(s.transfer),
),
],
),
),
);
},
),
),
);
},
],
),
),
);
}

View File

@ -2,16 +2,21 @@
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 '../../../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 '../../../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';
@ -48,7 +53,6 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
_loadHealthFresh();
}
/// Health/fees must always come from the network (never display-cache alone).
Future<void> _loadHealthFresh() async {
try {
final health = await sl<HealthRepository>().getHealth();
@ -69,6 +73,11 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
}
}
Future<void> _refreshAll() async {
context.read<WalletBloc>().add(const WalletLoadRequested());
await _loadHealthFresh();
}
@override
void dispose() {
_addressController.dispose();
@ -77,50 +86,39 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
super.dispose();
}
/// Validates form fields, force-refreshes balance+health, confirms, then submits.
Future<void> _submitWithdraw() async {
if (_confirming) return;
final s = context.strings;
if (!_healthLoaded || _healthFailed) {
ScaffoldMessenger.of(this.context).showSnackBar(
const SnackBar(content: Text('Could not verify withdrawal status. Retry.')),
);
showErrorSnackBar(context, s.couldNotVerifyWithdrawStatus);
await _loadHealthFresh();
return;
}
if (!_withdrawalsEnabled) {
ScaffoldMessenger.of(this.context).showSnackBar(
const SnackBar(
content: Text('Withdrawals are temporarily disabled by the platform.'),
),
);
showErrorSnackBar(context, s.withdrawalsDisabled);
return;
}
if (_addressController.text.isEmpty ||
_amountController.text.isEmpty ||
_totpController.text.length != 6) {
ScaffoldMessenger.of(this.context).showSnackBar(
const SnackBar(content: Text('Fill all fields and enter 2FA code')),
);
showErrorSnackBar(context, s.fillWithdrawFields);
return;
}
final state = context.read<WalletBloc>().state;
final enabledRails = state.walletTypes.where((t) => t.withdrawEnabled == true).toList();
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) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('No withdrawal network is enabled right now.')),
);
showErrorSnackBar(context, s.noWithdrawNetworks);
return;
}
final amountHuman = _amountController.text.trim();
final amountRaw = humanAmountToRaw(amountHuman, _kLedgerUsdtDecimals);
if (amountRaw == '0') {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Enter a valid amount')),
);
showErrorSnackBar(context, s.enterValidAmount);
return;
}
@ -139,15 +137,10 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
_healthFailed = false;
});
// Keep bloc display in sync after forced refresh.
context.read<WalletBloc>().add(const WalletLoadRequested());
if (!preflight.health.withdrawalsEnabled) {
ScaffoldMessenger.of(this.context).showSnackBar(
const SnackBar(
content: Text('Withdrawals are temporarily disabled by the platform.'),
),
);
showErrorSnackBar(context, s.withdrawalsDisabled);
return;
}
@ -155,9 +148,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, _kLedgerUsdtDecimals);
final totalRaw = BigInt.parse(amountRaw) + feeRaw;
if (preflight.balances.isEmpty) {
ScaffoldMessenger.of(this.context).showSnackBar(
const SnackBar(content: Text('Wallet balance not loaded')),
);
showErrorSnackBar(context, s.walletBalanceNotLoaded);
return;
}
final balance = preflight.balances.firstWhere(
@ -166,12 +157,9 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
);
final available = BigInt.tryParse(balance.available) ?? BigInt.zero;
if (totalRaw > available) {
ScaffoldMessenger.of(this.context).showSnackBar(
SnackBar(
content: Text(
'Insufficient balance — need ${rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals)} USDT (amount + network fee)',
),
),
showErrorSnackBar(
context,
'${s.insufficientBalance} — ${s.withdrawTotalDebited(rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals))}',
);
return;
}
@ -179,38 +167,40 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
final feeHuman = rawAmountToHuman(feeRaw.toString(), _kLedgerUsdtDecimals);
final address = _addressController.text.trim();
final confirmed = await showDialog<bool>(
context: this.context,
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Confirm withdrawal'),
title: Text(s.confirmWithdrawal),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('You receive: $amountHuman USDT'),
Text(s.withdrawYouReceive(amountHuman)),
if (feeRaw > BigInt.zero) ...[
const SizedBox(height: 8),
Text('Network fee: $feeHuman USDT'),
Text(s.withdrawNetworkFee(feeHuman)),
Text(
'Total debited: ${rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals)} USDT',
s.withdrawTotalDebited(
rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals),
),
),
],
const SizedBox(height: 8),
Text('To: $address'),
SelectableText('To: $address'),
const SizedBox(height: 16),
const Text(
'Please confirm that the address and amount are correct. Withdrawals cannot be undone.',
style: TextStyle(fontSize: 13),
Text(
s.withdrawIrreversibleHint,
style: Theme.of(ctx).textTheme.bodySmall,
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('Cancel'),
child: Text(s.cancel),
),
FilledButton(
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('Confirm'),
child: Text(s.confirmAction),
),
],
),
@ -227,11 +217,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
}
} catch (_) {
if (!mounted) return;
ScaffoldMessenger.of(this.context).showSnackBar(
const SnackBar(
content: Text('Could not refresh balance/fees. Try again.'),
),
);
showErrorSnackBar(context, s.couldNotRefreshBalance);
} finally {
if (mounted) setState(() => _confirming = false);
}
@ -240,272 +226,367 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
@override
Widget build(BuildContext context) {
final s = context.strings;
return Scaffold(
key: const Key('withdraw_screen'),
appBar: AppBar(title: Text(s.withdraw)),
body: BlocConsumer<WalletBloc, WalletState>(
listenWhen: (prev, curr) =>
prev.errorMessage != curr.errorMessage ||
prev.withdrawTxId != curr.withdrawTxId,
listener: (context, state) {
if (state.errorMessage != null && state.errorMessage!.isNotEmpty) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.errorMessage!),
backgroundColor: Colors.red.shade700,
behavior: SnackBarBehavior.floating,
),
);
context.read<WalletBloc>().add(const WalletClearFeedback());
}
if (state.withdrawTxId != null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Withdrawal submitted')),
);
context.read<WalletBloc>().add(const WalletClearFeedback());
context.pop();
}
},
builder: (context, state) {
final loadingEmpty = !state.isLoaded && state.balances.isEmpty;
if (loadingEmpty) {
return ListView(
padding: const EdgeInsets.all(24),
children: const [
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 56),
SizedBox(height: 12),
PredSkeletonCard(height: 48),
],
);
}
final bottomInset = MediaQuery.paddingOf(context).bottom;
if (_healthFailed && state.balances.isEmpty) {
return ListView(
padding: const EdgeInsets.all(24),
children: [
SectionError(
message: 'Could not load withdrawal status.',
onRetry: () {
context.read<WalletBloc>().add(const WalletLoadRequested());
_loadHealthFresh();
},
),
],
);
}
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),
],
);
}
final types = state.walletTypes.where((t) => t.withdrawEnabled == true).toList();
final balances = state.balances;
if (types.isEmpty) {
return const Center(child: Text('No withdrawal networks enabled'));
}
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,
);
final formEnabled = _healthLoaded && !_healthFailed && eligibility.allowed && !_confirming;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_healthFailed) ...[
SectionError(
compact: true,
message: 'Could not verify fees / withdrawal status.',
onRetry: _loadHealthFresh,
),
const SizedBox(height: 16),
],
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<String>(
isExpanded: true,
value: selectedCode,
items: types
.map(
(t) => DropdownMenuItem(
value: t.code,
child: Text(
'${t.name} — ${CoinDisplay.networkLabel(t.code)}',
overflow: TextOverflow.ellipsis,
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),
),
),
)
.toList(),
onChanged: formEnabled
? (v) => setState(() => _selectedWalletType = v)
: null,
),
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.link_rounded,
size: 20, color: Theme.of(context).colorScheme.primary),
const SizedBox(width: 8),
Expanded(
child: Text(
'Network: $networkLabel (payout rail; balance is unified USDT)',
style: Theme.of(context).textTheme.bodySmall,
),
],
);
}
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,
);
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.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),
),
],
),
],
),
),
const SizedBox(height: 16),
TextField(
controller: _addressController,
enabled: formEnabled,
decoration: InputDecoration(
labelText: 'Destination address',
hintText: CoinDisplay.addressPlaceholder(selectedType.code),
prefixIcon: const Icon(Icons.account_balance_wallet),
),
),
const SizedBox(height: 16),
if (feeRaw > BigInt.zero)
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.primaryContainer
.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'Network fee: $feeHuman USDT (deducted from your balance in addition to the withdrawal amount).',
style: Theme.of(context).textTheme.bodySmall,
),
),
if (feeRaw > BigInt.zero) const SizedBox(height: 16),
TextField(
controller: _amountController,
enabled: formEnabled,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(
labelText: 'Amount to receive',
prefixIcon: Icon(Icons.attach_money),
),
),
if (spendable != null) ...[
const SizedBox(height: 8),
Text(
'Available: ${rawAmountToHuman(spendable.available, _kLedgerUsdtDecimals)} USDT',
key: const Key('withdraw_available'),
style: Theme.of(context).textTheme.bodySmall,
),
],
const SizedBox(height: 16),
const Text('2FA Code (required for withdrawal)'),
const SizedBox(height: 8),
TextField(
controller: _totpController,
enabled: formEnabled,
keyboardType: TextInputType.number,
maxLength: 6,
decoration: const InputDecoration(
labelText: '6-digit code',
prefixIcon: Icon(Icons.security),
),
),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.errorContainer
.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'Only send to addresses that support $networkLabel. Wrong network (TRC20 vs BEP20) may result in permanent loss of funds.',
style: Theme.of(context).textTheme.bodySmall,
),
),
const SizedBox(height: 24),
FilledButton(
key: const Key('withdraw_submit'),
onPressed: formEnabled ? _submitWithdraw : null,
child: _confirming
? const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Withdraw'),
),
],
);
},
),
),
);
},
],
),
),
);
}

View File

@ -223,6 +223,113 @@ class AppStrings {
'6-digit code from your authenticator app',
'Code à 6 chiffres de votre application d’authentification',
);
String get chooseDepositAsset => t('Choose asset to deposit', 'Choisir l’actif à déposer');
String get chooseDepositAssetHint => t(
'Select a deposit network (TRON TRC20 or BSC BEP20). Credits go to your single USDT balance for predictions.',
'Choisissez un réseau de dépôt (TRON TRC20 ou BSC BEP20). Les crédits rejoignent votre solde USDT unique pour les prédictions.',
);
String get noDepositOptions => t(
'No deposit options available',
'Aucune option de dépôt disponible',
);
String get depositNetworkLocked => t(
'Network is automatically selected. You cannot change it.',
'Le réseau est sélectionné automatiquement. Vous ne pouvez pas le modifier.',
);
String depositSendOnlyWarning(String network, String asset) => t(
'Send only $network — $asset to this address. Sending any other asset or using a different network may result in permanent loss.',
'Envoyez uniquement $network — $asset à cette adresse. Tout autre actif ou réseau peut entraîner une perte définitive.',
);
String depositNetworkLabel(String network) => t('Network: $network', 'Réseau : $network');
String get copyAddress => t('Copy address', 'Copier l’adresse');
String get addressCopied => t('Address copied to clipboard', 'Adresse copiée');
String depositConfirmationsHint(String asset, String network) => t(
'Deposits are credited after blockchain confirmations. Only send $asset on $network to this address.',
'Les dépôts sont crédités après confirmation blockchain. N’envoyez que $asset sur $network à cette adresse.',
);
String get payoutNetwork => t('Payout network', 'Réseau de paiement');
String get destinationAddress => t('Destination address', 'Adresse de destination');
String get amountToReceive => t('Amount to receive', 'Montant à recevoir');
String get amountLabel => t('Amount', 'Montant');
String get recipientEmail => t('Recipient email', 'E-mail du destinataire');
String get emailAddressLabel => t('Email address', 'Adresse e-mail');
String get assetLabel => t('Asset', 'Actif');
String get totpRequiredWithdraw => t(
'2FA Code (required for withdrawal)',
'Code 2FA (requis pour le retrait)',
);
String get totpSixDigit => t('6-digit code', 'Code à 6 chiffres');
String get confirmWithdrawal => t('Confirm withdrawal', 'Confirmer le retrait');
String get confirmTransfer => t('Confirm transfer', 'Confirmer le transfert');
String get confirmAction => t('Confirm', 'Confirmer');
String get withdrawalSubmitted => t('Withdrawal submitted', 'Retrait soumis');
String get withdrawalsDisabled => t(
'Withdrawals are temporarily disabled by the platform.',
'Les retraits sont temporairement désactivés par la plateforme.',
);
String get noWithdrawNetworks => t(
'No withdrawal networks enabled',
'Aucun réseau de retrait activé',
);
String get fillWithdrawFields => t(
'Fill all fields and enter 2FA code',
'Remplissez tous les champs et le code 2FA',
);
String get enterValidAmount => t('Enter a valid amount', 'Saisissez un montant valide');
String get walletBalanceNotLoaded => t(
'Wallet balance not loaded',
'Solde portefeuille non chargé',
);
String get couldNotRefreshBalance => t(
'Could not refresh balance. Try again.',
'Impossible d’actualiser le solde. Réessayez.',
);
String get couldNotVerifyWithdrawStatus => t(
'Could not verify withdrawal status. Retry.',
'Impossible de vérifier le statut des retraits. Réessayez.',
);
String get couldNotVerifyFees => t(
'Could not verify fees / withdrawal status.',
'Impossible de vérifier les frais / le statut des retraits.',
);
String get couldNotVerify2fa => t(
'Could not verify 2FA requirements.',
'Impossible de vérifier les exigences 2FA.',
);
String get withdrawIrreversibleHint => t(
'Please confirm that the address and amount are correct. Withdrawals cannot be undone.',
'Confirmez que l’adresse et le montant sont corrects. Les retraits sont irréversibles.',
);
String get transferImmediateHint => t(
'This will move balance to another user in this app. The recipient will see the balance immediately.',
'Le solde sera transféré à un autre utilisateur de l’app. Le destinataire le verra immédiatement.',
);
String withdrawYouReceive(String amount) =>
t('You receive: $amount USDT', 'Vous recevez : $amount USDT');
String withdrawNetworkFee(String fee) =>
t('Network fee: $fee USDT', 'Frais réseau : $fee USDT');
String withdrawTotalDebited(String total) =>
t('Total debited: $total USDT', 'Total débité : $total USDT');
String availableUsdt(String amount) =>
t('Available: $amount USDT', 'Disponible : $amount USDT');
String availableAsset(String amount, String code) =>
t('Available: $amount $code', 'Disponible : $amount $code');
String withdrawMaxAfterFee(String amount) => t(
'You can withdraw up to $amount USDT after the network fee.',
'Vous pouvez retirer jusqu’à $amount USDT après les frais réseau.',
);
String withdrawFeeBanner(String fee) => t(
'Network fee: $fee USDT (deducted from your balance in addition to the withdrawal amount).',
'Frais réseau : $fee USDT (déduits du solde en plus du montant retiré).',
);
String withdrawWrongNetworkWarn(String network) => t(
'Only send to addresses that support $network. Wrong network (TRC20 vs BEP20) may result in permanent loss of funds.',
'N’envoyez qu’à des adresses compatibles $network. Un mauvais réseau (TRC20 vs BEP20) peut entraîner une perte définitive.',
);
String withdrawPayoutRailHint(String network) => t(
'Network: $network (payout rail; balance is unified USDT)',
'Réseau : $network (rail de paiement ; solde USDT unifié)',
);
String get send => t('Send', 'Envoyer');
String get transactions => t('Transactions', 'Transactions');
String get quickActions => t('Quick actions', 'Actions rapides');