513 lines
20 KiB
Dart
513 lines
20 KiB
Dart
/// Wallet presentation: on-chain withdrawal form with 2FA confirmation.
|
|
library;
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import '../../../core/di/injection.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/pred_skeleton.dart';
|
|
import '../../../shared/widgets/section_error.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 _healthLoaded = false;
|
|
bool _healthFailed = false;
|
|
bool _confirming = false;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
|
|
_loadHealthFresh();
|
|
}
|
|
|
|
/// Health/fees must always come from the network (never display-cache alone).
|
|
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;
|
|
});
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_addressController.dispose();
|
|
_amountController.dispose();
|
|
_totpController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
/// Validates form fields, force-refreshes balance+health, confirms, then submits.
|
|
Future<void> _submitWithdraw() async {
|
|
if (_confirming) return;
|
|
if (!_healthLoaded || _healthFailed) {
|
|
ScaffoldMessenger.of(this.context).showSnackBar(
|
|
const SnackBar(content: Text('Could not verify withdrawal status. Retry.')),
|
|
);
|
|
await _loadHealthFresh();
|
|
return;
|
|
}
|
|
if (!_withdrawalsEnabled) {
|
|
ScaffoldMessenger.of(this.context).showSnackBar(
|
|
const SnackBar(
|
|
content: Text('Withdrawals are temporarily disabled by the platform.'),
|
|
),
|
|
);
|
|
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')),
|
|
);
|
|
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) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('No withdrawal network is enabled right now.')),
|
|
);
|
|
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')),
|
|
);
|
|
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;
|
|
});
|
|
|
|
// 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.'),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
|
|
final feeRaw =
|
|
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')),
|
|
);
|
|
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) {
|
|
ScaffoldMessenger.of(this.context).showSnackBar(
|
|
SnackBar(
|
|
content: Text(
|
|
'Insufficient balance — need ${rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals)} USDT (amount + network fee)',
|
|
),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
|
|
final feeHuman = rawAmountToHuman(feeRaw.toString(), _kLedgerUsdtDecimals);
|
|
final address = _addressController.text.trim();
|
|
final confirmed = await showDialog<bool>(
|
|
context: this.context,
|
|
builder: (ctx) => AlertDialog(
|
|
title: const Text('Confirm withdrawal'),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text('You receive: $amountHuman USDT'),
|
|
if (feeRaw > BigInt.zero) ...[
|
|
const SizedBox(height: 8),
|
|
Text('Network fee: $feeHuman USDT'),
|
|
Text(
|
|
'Total debited: ${rawAmountToHuman(totalRaw.toString(), _kLedgerUsdtDecimals)} USDT',
|
|
),
|
|
],
|
|
const SizedBox(height: 8),
|
|
Text('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),
|
|
),
|
|
],
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(ctx).pop(false),
|
|
child: const Text('Cancel'),
|
|
),
|
|
FilledButton(
|
|
onPressed: () => Navigator.of(ctx).pop(true),
|
|
child: const Text('Confirm'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
if (confirmed == true && mounted) {
|
|
context.read<WalletBloc>().add(
|
|
WalletWithdrawRequested(
|
|
walletType: railCode,
|
|
toAddress: address,
|
|
amount: amountRaw,
|
|
totpCode: _totpController.text,
|
|
),
|
|
);
|
|
}
|
|
} catch (_) {
|
|
if (!mounted) return;
|
|
ScaffoldMessenger.of(this.context).showSnackBar(
|
|
const SnackBar(
|
|
content: Text('Could not refresh balance/fees. Try again.'),
|
|
),
|
|
);
|
|
} finally {
|
|
if (mounted) setState(() => _confirming = false);
|
|
}
|
|
}
|
|
|
|
@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),
|
|
],
|
|
);
|
|
}
|
|
|
|
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();
|
|
},
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
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,
|
|
),
|
|
),
|
|
)
|
|
.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,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
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'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|