605 lines
25 KiB
Dart
605 lines
25 KiB
Dart
/// Wallet presentation: in-app transfer to another user by email.
|
|
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/models/wallet_type_model.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';
|
|
|
|
/// Peer transfers always use the unified main USDT ledger (not deposit/withdraw rails).
|
|
const String _kTransferLedgerCode = 'USDT_TRC20';
|
|
|
|
/// Form to transfer balance to another registered user; requires TOTP and confirmation.
|
|
class TransferScreen extends StatefulWidget {
|
|
const TransferScreen({super.key});
|
|
|
|
@override
|
|
State<TransferScreen> createState() => _TransferScreenState();
|
|
}
|
|
|
|
/// Validates inputs, shows a confirmation dialog, and dispatches [WalletTransferRequested].
|
|
class _TransferScreenState extends State<TransferScreen> {
|
|
final _emailController = TextEditingController();
|
|
final _amountController = TextEditingController();
|
|
final _totpController = TextEditingController();
|
|
bool? _totpEnabled;
|
|
bool _requireWithdrawal2fa = true;
|
|
bool _transfersSuspended = false;
|
|
String _transferMinRemainingRaw = '0';
|
|
bool _submitting = false;
|
|
bool _confirming = false;
|
|
bool _securityFailed = false;
|
|
String? _localError;
|
|
|
|
bool get _needs2faSetup => _requireWithdrawal2fa && _totpEnabled == false;
|
|
bool get _formEnabled =>
|
|
!_transfersSuspended && !_needs2faSetup && !_confirming && !_submitting;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
|
|
_loadSecurityContext();
|
|
}
|
|
|
|
Future<void> _loadSecurityContext({bool forceProfile = false}) async {
|
|
try {
|
|
final profile =
|
|
await sl<AuthRepository>().getProfile(force: forceProfile);
|
|
final health = await sl<HealthRepository>().getHealth();
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_totpEnabled = profile.totpEnabled;
|
|
_transfersSuspended = profile.withdrawalsSuspended;
|
|
_requireWithdrawal2fa = health.requireWithdrawal2fa;
|
|
_transferMinRemainingRaw = health.transferMinRemainingRaw;
|
|
_securityFailed = false;
|
|
});
|
|
} catch (_) {
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_totpEnabled ??= false;
|
|
_securityFailed = true;
|
|
});
|
|
}
|
|
}
|
|
|
|
Future<void> _refreshAll() async {
|
|
context.read<WalletBloc>().add(const WalletLoadRequested());
|
|
await _loadSecurityContext(forceProfile: true);
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_emailController.dispose();
|
|
_amountController.dispose();
|
|
_totpController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
Future<void> _submitTransfer() async {
|
|
if (_confirming || _submitting) return;
|
|
final s = context.strings;
|
|
setState(() => _localError = null);
|
|
|
|
if (_transfersSuspended) {
|
|
setState(() => _localError = s.transfersSuspendedAccount);
|
|
showErrorSnackBar(context, s.transfersSuspendedAccount);
|
|
return;
|
|
}
|
|
|
|
if (_needs2faSetup) {
|
|
setState(() => _localError = s.transferTwoFaRequiredBody);
|
|
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
|
|
return;
|
|
}
|
|
|
|
if (_emailController.text.trim().isEmpty ||
|
|
_amountController.text.isEmpty) {
|
|
setState(() => _localError = s.transferFillFields);
|
|
showErrorSnackBar(context, s.transferFillFields);
|
|
return;
|
|
}
|
|
|
|
if (_requireWithdrawal2fa && _totpController.text.trim().length != 6) {
|
|
setState(() => _localError = s.transferFillFields);
|
|
showErrorSnackBar(context, s.transferFillFields);
|
|
return;
|
|
}
|
|
|
|
final state = context.read<WalletBloc>().state;
|
|
WalletTypeModel? selectedType;
|
|
for (final t in state.walletTypes) {
|
|
if (t.code == _kTransferLedgerCode) {
|
|
selectedType = t;
|
|
break;
|
|
}
|
|
}
|
|
selectedType ??= state.balances
|
|
.where((b) => b.walletType.code == _kTransferLedgerCode)
|
|
.map((b) => b.walletType)
|
|
.firstOrNull;
|
|
selectedType ??=
|
|
state.balances.isNotEmpty ? state.balances.first.walletType : null;
|
|
if (selectedType == null) {
|
|
setState(() => _localError = s.walletBalanceNotLoaded);
|
|
showErrorSnackBar(context, s.walletBalanceNotLoaded);
|
|
return;
|
|
}
|
|
final amountHuman = _amountController.text.trim();
|
|
final amountRaw = humanAmountToRaw(amountHuman, selectedType.decimals);
|
|
if (amountRaw == '0') {
|
|
setState(() => _localError = s.enterValidAmount);
|
|
showErrorSnackBar(context, s.enterValidAmount);
|
|
return;
|
|
}
|
|
|
|
setState(() => _confirming = true);
|
|
try {
|
|
final preflight = await fetchMoneyConfirmPreflight(
|
|
walletRepo: sl<WalletRepository>(),
|
|
healthRepo: sl<HealthRepository>(),
|
|
);
|
|
final profile = await sl<AuthRepository>().getProfile(force: true);
|
|
if (!mounted) return;
|
|
|
|
setState(() {
|
|
_totpEnabled = profile.totpEnabled;
|
|
_requireWithdrawal2fa = preflight.health.requireWithdrawal2fa;
|
|
_transferMinRemainingRaw = preflight.health.transferMinRemainingRaw;
|
|
_securityFailed = false;
|
|
});
|
|
context.read<WalletBloc>().add(const WalletLoadRequested());
|
|
|
|
if (_requireWithdrawal2fa && _totpEnabled == false) {
|
|
setState(() => _localError = s.transferTwoFaRequiredBody);
|
|
showErrorSnackBar(context, s.transferTwoFaRequiredBody);
|
|
return;
|
|
}
|
|
|
|
final match = preflight.balances
|
|
.where((b) => b.walletType.code == _kTransferLedgerCode)
|
|
.toList();
|
|
if (match.isEmpty) {
|
|
showErrorSnackBar(context, s.walletBalanceNotLoaded);
|
|
return;
|
|
}
|
|
final available = BigInt.tryParse(match.first.available) ?? BigInt.zero;
|
|
final need = BigInt.tryParse(amountRaw) ?? BigInt.zero;
|
|
final minRemaining = CoinDisplay.scaleWithdrawalFeeRaw(
|
|
preflight.health.transferMinRemainingRaw,
|
|
selectedType.decimals,
|
|
);
|
|
final maxTransferable =
|
|
available > minRemaining ? available - minRemaining : BigInt.zero;
|
|
if (need > available) {
|
|
showErrorSnackBar(context, s.insufficientBalance);
|
|
return;
|
|
}
|
|
if (minRemaining > BigInt.zero && need > maxTransferable) {
|
|
final minHuman = rawAmountToHuman(
|
|
minRemaining.toString(),
|
|
selectedType.decimals,
|
|
);
|
|
final msg = s.transferMinRemainingError(minHuman);
|
|
setState(() => _localError = msg);
|
|
showErrorSnackBar(context, msg);
|
|
return;
|
|
}
|
|
|
|
final email = _emailController.text.trim().toLowerCase();
|
|
final confirmed = await showDialog<bool>(
|
|
context: context,
|
|
builder: (ctx) => AlertDialog(
|
|
title: Text(s.confirmTransfer),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text('${s.amountLabel}: $amountHuman USDT'),
|
|
const SizedBox(height: 8),
|
|
SelectableText('${s.recipientEmail}: $email'),
|
|
const SizedBox(height: 16),
|
|
Text(
|
|
s.transferImmediateHint,
|
|
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) {
|
|
setState(() => _submitting = true);
|
|
final totp = _totpController.text.trim();
|
|
context.read<WalletBloc>().add(
|
|
WalletTransferRequested(
|
|
toEmail: email,
|
|
walletType: _kTransferLedgerCode,
|
|
amount: amountRaw,
|
|
totpCode: totp.isEmpty ? null : totp,
|
|
),
|
|
);
|
|
}
|
|
} 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('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 && balances.isEmpty) {
|
|
return ListView(
|
|
padding: EdgeInsets.fromLTRB(
|
|
20,
|
|
16,
|
|
20,
|
|
24 + bottomInset,
|
|
),
|
|
children: [
|
|
SectionError(
|
|
message: state.errorMessage ?? s.walletBalanceNotLoaded,
|
|
onRetry: _refreshAll,
|
|
),
|
|
],
|
|
);
|
|
}
|
|
WalletTypeModel? selectedType;
|
|
for (final t in types) {
|
|
if (t.code == _kTransferLedgerCode) {
|
|
selectedType = t;
|
|
break;
|
|
}
|
|
}
|
|
selectedType ??= balances
|
|
.where((b) => b.walletType.code == _kTransferLedgerCode)
|
|
.map((b) => b.walletType)
|
|
.firstOrNull;
|
|
selectedType ??=
|
|
balances.isNotEmpty ? balances.first.walletType : null;
|
|
if (selectedType == null) {
|
|
return ListView(
|
|
padding: EdgeInsets.fromLTRB(
|
|
20,
|
|
16,
|
|
20,
|
|
24 + bottomInset,
|
|
),
|
|
children: [
|
|
SectionError(
|
|
message:
|
|
state.errorMessage ?? s.walletBalanceNotLoaded,
|
|
onRetry: _refreshAll,
|
|
),
|
|
],
|
|
);
|
|
}
|
|
// Non-null local so closures (e.g. Builder) keep promotion.
|
|
final ledgerType = selectedType;
|
|
final busy = _submitting || _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 (_securityFailed) ...[
|
|
SectionError(
|
|
compact: true,
|
|
message: s.couldNotVerify2fa,
|
|
onRetry: () =>
|
|
_loadSecurityContext(forceProfile: true),
|
|
),
|
|
const SizedBox(height: 12),
|
|
],
|
|
if (_transfersSuspended) ...[
|
|
PredCard(
|
|
padding: const EdgeInsets.all(14),
|
|
child: Text(
|
|
s.transfersSuspendedAccount,
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
),
|
|
const SizedBox(height: 12),
|
|
],
|
|
if (_needs2faSetup && !_transfersSuspended) ...[
|
|
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: _formEnabled,
|
|
decoration: InputDecoration(
|
|
labelText: s.emailAddressLabel,
|
|
prefixIcon:
|
|
const Icon(Icons.email_outlined),
|
|
),
|
|
),
|
|
const SizedBox(height: 14),
|
|
Row(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Icon(
|
|
Icons.info_outline,
|
|
size: 20,
|
|
color: AppColors.primary,
|
|
),
|
|
const SizedBox(width: 8),
|
|
Expanded(
|
|
child: Text(
|
|
s.transferLedgerOnlyHint,
|
|
style: Theme.of(context)
|
|
.textTheme
|
|
.bodySmall,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 14),
|
|
TextField(
|
|
controller: _amountController,
|
|
enabled: _formEnabled,
|
|
keyboardType:
|
|
const TextInputType.numberWithOptions(
|
|
decimal: true,
|
|
),
|
|
decoration: InputDecoration(
|
|
labelText: s.amountLabel,
|
|
prefixIcon:
|
|
const Icon(Icons.attach_money),
|
|
),
|
|
),
|
|
if (balances.any(
|
|
(b) =>
|
|
b.walletType.code ==
|
|
_kTransferLedgerCode,
|
|
)) ...[
|
|
const SizedBox(height: 8),
|
|
Builder(
|
|
builder: (context) {
|
|
final availableRaw = balances
|
|
.firstWhere(
|
|
(b) =>
|
|
b.walletType.code ==
|
|
_kTransferLedgerCode,
|
|
)
|
|
.available;
|
|
final available = BigInt.tryParse(
|
|
availableRaw,
|
|
) ??
|
|
BigInt.zero;
|
|
final minRemaining =
|
|
CoinDisplay.scaleWithdrawalFeeRaw(
|
|
_transferMinRemainingRaw,
|
|
ledgerType.decimals,
|
|
);
|
|
final maxRaw = available > minRemaining
|
|
? available - minRemaining
|
|
: BigInt.zero;
|
|
final label = minRemaining > BigInt.zero
|
|
? s.transferMaxWithMinRemaining(
|
|
'${rawAmountToHuman(maxRaw.toString(), ledgerType.decimals)} USDT',
|
|
'${rawAmountToHuman(minRemaining.toString(), ledgerType.decimals)} USDT',
|
|
)
|
|
: s.availableAsset(
|
|
rawAmountToHuman(
|
|
availableRaw,
|
|
ledgerType.decimals,
|
|
),
|
|
'USDT',
|
|
);
|
|
return Text(
|
|
label,
|
|
key: const Key('transfer_available'),
|
|
style: Theme.of(context)
|
|
.textTheme
|
|
.bodySmall,
|
|
);
|
|
},
|
|
),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
if (!_needs2faSetup && !_transfersSuspended) ...[
|
|
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: _formEnabled,
|
|
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: _formEnabled ? _submitTransfer : null,
|
|
child: busy
|
|
? const SizedBox(
|
|
width: 22,
|
|
height: 22,
|
|
child: CircularProgressIndicator(
|
|
strokeWidth: 2,
|
|
color: Colors.white,
|
|
),
|
|
)
|
|
: Text(s.transfer),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
},
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|