402 lines
16 KiB
Dart
402 lines
16 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/network/api_client.dart';
|
|
import '../../../core/utils/amount_utils.dart';
|
|
import '../../../core/utils/coin_display.dart';
|
|
import '../bloc/wallet_bloc.dart';
|
|
import '../utils/withdraw_eligibility.dart';
|
|
|
|
/// Unified spendable ledger decimals (USDT_TRC20). Payout rail may be BEP20 (18 on-chain)
|
|
/// but API amounts and fees are always 6-decimal micro-USDT.
|
|
const int _kLedgerUsdtDecimals = 6;
|
|
const String _kLedgerUsdtCode = 'USDT_TRC20';
|
|
|
|
/// Form to withdraw crypto to an external address; requires TOTP and confirmation dialog.
|
|
class WithdrawScreen extends StatefulWidget {
|
|
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;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
context.read<WalletBloc>().add(const WalletLoadRequested(ifStale: true));
|
|
_loadNetworkFee();
|
|
}
|
|
|
|
Future<void> _loadNetworkFee() async {
|
|
try {
|
|
final api = context.read<ApiClient>();
|
|
final res = await api.dio.get<Map<String, dynamic>>('/health');
|
|
final fee = res.data?['withdrawalNetworkFeeRaw']?.toString() ?? '0';
|
|
final enabled = res.data?['withdrawalsEnabled'] == true;
|
|
if (mounted) {
|
|
setState(() {
|
|
_networkFeeRaw = fee;
|
|
_withdrawalsEnabled = enabled;
|
|
_healthLoaded = true;
|
|
});
|
|
}
|
|
} catch (_) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_withdrawalsEnabled = false;
|
|
_healthLoaded = true;
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_addressController.dispose();
|
|
_amountController.dispose();
|
|
_totpController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
/// Validates form fields, confirms with the user, and submits the withdrawal.
|
|
void _submitWithdraw(BuildContext context) {
|
|
if (!_withdrawalsEnabled) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(
|
|
content: Text('Withdrawals are temporarily disabled by the platform.'),
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
if (_addressController.text.isEmpty ||
|
|
_amountController.text.isEmpty ||
|
|
_totpController.text.length != 6) {
|
|
ScaffoldMessenger.of(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();
|
|
// Always ledger micro-USDT (6), even when payout rail is BEP20.
|
|
final amountRaw = humanAmountToRaw(amountHuman, _kLedgerUsdtDecimals);
|
|
if (amountRaw == '0') {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('Enter a valid amount')),
|
|
);
|
|
return;
|
|
}
|
|
final feeRaw = CoinDisplay.scaleWithdrawalFeeRaw(_networkFeeRaw, _kLedgerUsdtDecimals);
|
|
final totalRaw = BigInt.parse(amountRaw) + feeRaw;
|
|
if (state.balances.isEmpty) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('Wallet balance not loaded')),
|
|
);
|
|
return;
|
|
}
|
|
final balance = state.balances.firstWhere(
|
|
(b) => b.walletType.code == _kLedgerUsdtCode,
|
|
orElse: () => state.balances.first,
|
|
);
|
|
final available = BigInt.tryParse(balance.available) ?? BigInt.zero;
|
|
if (totalRaw > available) {
|
|
ScaffoldMessenger.of(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();
|
|
showDialog<bool>(
|
|
context: 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'),
|
|
),
|
|
],
|
|
),
|
|
).then((confirmed) {
|
|
if (confirmed == true && context.mounted) {
|
|
context.read<WalletBloc>().add(
|
|
WalletWithdrawRequested(
|
|
walletType: railCode,
|
|
toAddress: address,
|
|
amount: amountRaw,
|
|
totpCode: _totpController.text,
|
|
),
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(title: const Text('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) {
|
|
if (!state.isLoaded && state.balances.isEmpty) {
|
|
return const Center(child: CircularProgressIndicator());
|
|
}
|
|
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 && eligibility.allowed;
|
|
return SingleChildScrollView(
|
|
padding: const EdgeInsets.all(24),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
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>(
|
|
value: selectedCode,
|
|
items: types
|
|
.map(
|
|
(t) => DropdownMenuItem(
|
|
value: t.code,
|
|
child: Text('${t.name} — ${CoinDisplay.networkLabel(t.code)}'),
|
|
),
|
|
)
|
|
.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',
|
|
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(
|
|
onPressed: formEnabled ? () => _submitWithdraw(context) : null,
|
|
child: const Text('Withdraw'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
}
|