After adding option to prevent users to send money without any control

This commit is contained in:
Your Name 2026-11-02 19:59:28 +02:00
parent 55ddbb1c09
commit e3b109a988
21 changed files with 431 additions and 125 deletions

View File

@ -92,6 +92,10 @@ app.get('/health', async (_req, res) => {
withdrawalsEnabled: settings.allow_withdrawals,
requireWithdrawal2fa: settings.require_withdrawal_2fa,
withdrawalNetworkFeeRaw: feeRaw.toString(),
/** Min remaining after peer transfer (6-decimal micro-USDT; 0 = disabled). */
transferMinRemainingRaw: String(
Math.max(0, Math.floor(settings.transfer_min_remaining_usdt_micro || 0))
),
rpc: {
tronNodeUrl: config.blockchain.tron.nodeUrl,
bscRpcUrl: config.blockchain.bsc.rpcUrl,

View File

@ -558,6 +558,10 @@ INSERT INTO system_settings (key, value) VALUES
('withdrawal_network_fee_usdt_micro', '2000000')
ON CONFLICT (key) DO NOTHING;
INSERT INTO system_settings (key, value) VALUES
('transfer_min_remaining_usdt_micro', '0')
ON CONFLICT (key) DO NOTHING;
-- Games catalog (prediction games available on the platform)
CREATE TABLE IF NOT EXISTS games (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

View File

@ -36,6 +36,11 @@ export interface SystemSettings {
engine_audit_log_retention_days: number;
/** Network fee deducted from user USDT balance per withdrawal (6-decimal micro units). */
withdrawal_network_fee_usdt_micro: number;
/**
* Minimum USDT that must remain on the sender's main balance after a peer transfer
* (6-decimal micro units). `0` disables the limit.
*/
transfer_min_remaining_usdt_micro: number;
/** When true, admin/super_admin routes require TOTP to be enabled. */
require_admin_2fa: boolean;
/** When true, withdrawals and transfers require 2FA to be enabled and a valid code. */

View File

@ -278,15 +278,17 @@ export async function deductLocked(accountId: string, amount: bigint): Promise<v
* @param amount - Transfer amount in the smallest currency unit.
* @param referenceType - Reference entity type shared by both ledger entries.
* @param referenceId - Reference entity ID shared by both ledger entries.
* @param options.minRemaining - Optional floor that must remain on the sender after debit (peer transfers).
* @returns Resolves when both balance updates and entries have been committed.
* @throws Error if either account is not found or the sender has insufficient balance.
* @throws Error if either account is not found, the sender has insufficient balance, or minRemaining would be breached.
*/
export async function transferBetweenAccounts(
senderAccountId: string,
receiverAccountId: string,
amount: bigint,
referenceType: string,
referenceId: string
referenceId: string,
options?: { minRemaining?: bigint }
): Promise<void> {
const client = await getClient();
try {
@ -298,6 +300,14 @@ export async function transferBetweenAccounts(
if (!sender.rows[0]) throw new Error('Sender account not found');
const available = BigInt(sender.rows[0].available_balance);
if (available < amount) throw new Error('Insufficient balance');
const minRemaining = options?.minRemaining ?? 0n;
if (minRemaining > 0n && available - amount < minRemaining) {
const err = new Error(
'Transfer would leave balance below the minimum required remaining balance'
) as Error & { code?: string };
err.code = 'TRANSFER_MIN_REMAINING';
throw err;
}
const senderNew = available - amount;
await client.query(
'UPDATE ledger_accounts SET available_balance = $1, updated_at = NOW() WHERE id = $2',

View File

@ -73,6 +73,8 @@ function buildDefaults(): SystemSettings {
withdrawal_network_fee_usdt_micro: config.withdrawal.networkFeeUsdtMicro,
transfer_min_remaining_usdt_micro: 0,
require_admin_2fa: true,
require_withdrawal_2fa: true,
@ -161,6 +163,8 @@ const INTEGER_KEYS = new Set([
'withdrawal_network_fee_usdt_micro',
'transfer_min_remaining_usdt_micro',
'login_max_failed_attempts',
'login_lockout_minutes',
@ -303,6 +307,8 @@ const UPDATABLE_KEYS = [
'withdrawal_network_fee_usdt_micro',
'transfer_min_remaining_usdt_micro',
'require_admin_2fa',
'login_max_failed_attempts',

View File

@ -155,6 +155,20 @@ function validateUpdates(updates: Partial<SystemSettings>): void {
}
if (updates.transfer_min_remaining_usdt_micro !== undefined) {
updates.transfer_min_remaining_usdt_micro = clampInt(
updates.transfer_min_remaining_usdt_micro,
0,
1_000_000_000_000
);
}
if (updates.login_max_failed_attempts !== undefined) {
updates.login_max_failed_attempts = clampInt(updates.login_max_failed_attempts, 0, 50);
@ -376,6 +390,12 @@ export function parseSettingsUpdates(body: Record<string, unknown>): Partial<Sys
}
if (typeof body.transfer_min_remaining_usdt_micro === 'number') {
updates.transfer_min_remaining_usdt_micro = body.transfer_min_remaining_usdt_micro;
}
if (typeof body.require_admin_2fa === 'boolean') {
updates.require_admin_2fa = body.require_admin_2fa;

View File

@ -7,21 +7,29 @@ import { randomUUID } from 'crypto';
import { hashForIndex } from '../utils/crypto';
import * as authService from './authService';
import * as ledgerRepository from '../repositories/ledgerRepository';
import * as settingsRepository from '../repositories/settingsRepository';
import * as transactionRepository from '../repositories/transactionRepository';
import * as userRepository from '../repositories/userRepository';
import * as walletRepository from '../repositories/walletRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
import { USDT_TRC20_CODE } from './walletCapabilities';
import {
formatUsdtRawHuman,
getTransferMinRemainingRaw,
} from '../utils/withdrawalFee';
import { voidUserAdminStatsRefresh } from './userAdminStatsService';
/**
* Transfers balance from one user to another identified by email.
* Peer transfers always debit/credit the unified main ledger (USDT_TRC20).
* Deposit/withdraw rails such as USDT_BEP20 are not valid transfer assets.
* @param userId Sender user UUID
* @param toEmail Recipient email (normalized and hashed for lookup)
* @param walletTypeCode Asset code for the transfer
* @param walletTypeCode Asset code for the transfer (must be USDT_TRC20)
* @param amountRaw Amount in smallest ledger unit
* @param totpCode TOTP code when sender has 2FA enabled
* @returns Sender transaction ID and status (always completed on success)
* @throws {Error} On invalid amount, failed 2FA, recipient not found, self-transfer, or insufficient balance
* @throws {Error} On invalid amount, failed 2FA, recipient not found, self-transfer, insufficient balance, or min remaining
*/
export async function requestTransfer(
userId: string,
@ -30,7 +38,15 @@ export async function requestTransfer(
amountRaw: bigint,
totpCode?: string
): Promise<{ transactionId: string; status: string }> {
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
if (walletTypeCode !== USDT_TRC20_CODE) {
const err = new Error(
'Peer transfers use the main USDT balance only (not deposit/withdraw networks)'
) as Error & { code?: string };
err.code = 'TRANSFER_LEDGER_ONLY';
throw err;
}
const walletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
if (!walletType) throw new Error('Unknown wallet type');
if (amountRaw <= 0n) throw new Error('Invalid amount');
@ -41,10 +57,21 @@ export async function requestTransfer(
if (!recipient) throw new Error('Recipient not found');
if (recipient.id === userId) throw new Error('Cannot transfer to yourself');
const settings = await settingsRepository.getSettings();
const minRemaining = getTransferMinRemainingRaw(settings, walletType.decimals);
const senderAccount = await ledgerRepository.getOrCreateAccount(userId, walletType.id);
const recipientAccount = await ledgerRepository.getOrCreateAccount(recipient.id, walletType.id);
const available = BigInt(senderAccount.available_balance);
if (available < amountRaw) throw new Error('Insufficient balance');
if (minRemaining > 0n && available - amountRaw < minRemaining) {
const human = formatUsdtRawHuman(minRemaining, walletType.decimals);
const err = new Error(
`Transfer would leave balance below the minimum required remaining balance (${human} USDT)`
) as Error & { code?: string };
err.code = 'TRANSFER_MIN_REMAINING';
throw err;
}
const refId = randomUUID();
await ledgerRepository.transferBetweenAccounts(
@ -52,7 +79,8 @@ export async function requestTransfer(
recipientAccount.id,
amountRaw,
'transfer',
refId
refId,
{ minRemaining }
);
const senderTx = await transactionRepository.create({
@ -87,8 +115,8 @@ export async function requestTransfer(
metadata: { amount: amountRaw.toString(), from_user_id: userId },
});
queueUserAdminStatsRefresh(userId);
queueUserAdminStatsRefresh(recipient.id);
voidUserAdminStatsRefresh(userId);
voidUserAdminStatsRefresh(recipient.id);
return { transactionId: senderTx.id, status: 'completed' };
}

View File

@ -80,6 +80,7 @@ describe('mobile API E2E (mocked services)', () => {
assert.ok(typeof res.body.network === 'string');
assert.ok(typeof res.body.withdrawalsEnabled === 'boolean');
assert.ok(res.body.withdrawalNetworkFeeRaw != null);
assert.ok(res.body.transferMinRemainingRaw != null);
});
test('GET /faq/entries returns public FAQ list (no auth)', async () => {

View File

@ -1,10 +1,14 @@
import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { getWithdrawalNetworkFeeRaw } from '../utils/withdrawalFee';
import {
getTransferMinRemainingRaw,
getWithdrawalNetworkFeeRaw,
} from '../utils/withdrawalFee';
import type { SystemSettings } from '../models/settings.model';
const baseSettings = {
withdrawal_network_fee_usdt_micro: 2_000_000, // 2 USDT
transfer_min_remaining_usdt_micro: 10_000_000, // 10 USDT
} as SystemSettings;
describe('getWithdrawalNetworkFeeRaw', () => {
@ -16,3 +20,17 @@ describe('getWithdrawalNetworkFeeRaw', () => {
assert.equal(getWithdrawalNetworkFeeRaw(baseSettings, 18), 2_000_000n * 10n ** 12n);
});
});
describe('getTransferMinRemainingRaw', () => {
test('returns configured micro units for TRC20', () => {
assert.equal(getTransferMinRemainingRaw(baseSettings, 6), 10_000_000n);
});
test('returns 0 when disabled', () => {
const disabled = {
...baseSettings,
transfer_min_remaining_usdt_micro: 0,
} as SystemSettings;
assert.equal(getTransferMinRemainingRaw(disabled, 6), 0n);
});
});

View File

@ -22,7 +22,14 @@ export function httpStatusForError(error: unknown): number {
if (code === 'EMAIL_NOT_VERIFIED') return 403;
if (code === 'WITHDRAWAL_2FA_REQUIRED') return 403;
if (code === 'WITHDRAWALS_DISABLED' || code === 'WITHDRAWAL_NETWORK_DISABLED') return 403;
if (code === 'INSUFFICIENT_BALANCE' || code === 'HOT_WALLET_INSUFFICIENT_LIQUIDITY') return 400;
if (
code === 'INSUFFICIENT_BALANCE' ||
code === 'HOT_WALLET_INSUFFICIENT_LIQUIDITY' ||
code === 'TRANSFER_MIN_REMAINING' ||
code === 'TRANSFER_LEDGER_ONLY'
) {
return 400;
}
if (code === 'DAILY_WITHDRAWAL_LIMIT_EXCEEDED') return 403;
if (code === 'TOKEN_REVOKED') return 401;
if (code === 'ACCOUNT_LOCKED') return 429;

View File

@ -10,11 +10,10 @@ export const USDT_FEE_SETTING_DECIMALS = 6;
export const USDT_DECIMALS = USDT_FEE_SETTING_DECIMALS;
/**
* Returns the configured network fee in smallest units for the given wallet decimals.
* Setting is stored as 6-decimal micro-USDT; scaled when wallet decimals differ (e.g. BEP20 18).
* Scales a 6-decimal micro-USDT admin setting to wallet raw units.
* Used for withdrawal fees and transfer minimum-remaining balance.
*/
export function getWithdrawalNetworkFeeRaw(settings: SystemSettings, walletDecimals = 6): bigint {
const micro = settings.withdrawal_network_fee_usdt_micro;
export function scaleUsdtMicroToWalletRaw(micro: number, walletDecimals = 6): bigint {
if (!Number.isFinite(micro) || micro < 0) return 0n;
const base = BigInt(Math.floor(micro));
if (walletDecimals === USDT_FEE_SETTING_DECIMALS) return base;
@ -24,6 +23,22 @@ export function getWithdrawalNetworkFeeRaw(settings: SystemSettings, walletDecim
return base / 10n ** BigInt(USDT_FEE_SETTING_DECIMALS - walletDecimals);
}
/**
* Returns the configured network fee in smallest units for the given wallet decimals.
* Setting is stored as 6-decimal micro-USDT; scaled when wallet decimals differ (e.g. BEP20 18).
*/
export function getWithdrawalNetworkFeeRaw(settings: SystemSettings, walletDecimals = 6): bigint {
return scaleUsdtMicroToWalletRaw(settings.withdrawal_network_fee_usdt_micro, walletDecimals);
}
/**
* Minimum remaining main-wallet balance after a peer transfer (0 = disabled).
* Stored as 6-decimal micro-USDT; scaled to wallet decimals when needed.
*/
export function getTransferMinRemainingRaw(settings: SystemSettings, walletDecimals = 6): bigint {
return scaleUsdtMicroToWalletRaw(settings.transfer_min_remaining_usdt_micro, walletDecimals);
}
/**
* Formats a raw USDT amount for display (trims trailing zeros).
*/

View File

@ -106,6 +106,18 @@ class AppException implements Exception {
: null,
);
}
if (code == 'TRANSFER_MIN_REMAINING') {
return AppException(
msg is String && msg.toString().trim().isNotEmpty
? msg.toString().trim()
: _t(
'Transfer refused: remaining balance would fall below the minimum configured by the administrator.',
'Transfert refusé : le solde restant passerait sous le minimum configuré par l’administrateur.',
),
statusCode: status,
code: 'TRANSFER_MIN_REMAINING',
);
}
if (code == 'TEST_PREDICTION_LIMIT') {
final waitRaw = data['wait'];
final wait = waitRaw is String && waitRaw.trim().isNotEmpty ? waitRaw.trim() : '24h';

View File

@ -16,6 +16,7 @@ class HealthStatus {
required this.env,
this.requireWithdrawal2fa = true,
this.withdrawalNetworkFeeRaw = '0',
this.transferMinRemainingRaw = '0',
});
final String network;
@ -23,6 +24,8 @@ class HealthStatus {
final String env;
final bool requireWithdrawal2fa;
final String withdrawalNetworkFeeRaw;
/// Min remaining after peer transfer (6-decimal micro-USDT; 0 = disabled).
final String transferMinRemainingRaw;
factory HealthStatus.fromJson(Map<String, dynamic> json) => HealthStatus(
network: (json['network'] ?? 'unknown').toString(),
@ -31,6 +34,8 @@ class HealthStatus {
requireWithdrawal2fa: json['requireWithdrawal2fa'] != false,
withdrawalNetworkFeeRaw:
(json['withdrawalNetworkFeeRaw'] ?? '0').toString(),
transferMinRemainingRaw:
(json['transferMinRemainingRaw'] ?? '0').toString(),
);
bool get isTestnetSafe => network == 'shasta' && !withdrawalsEnabled;

View File

@ -9,6 +9,7 @@ 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';
@ -21,6 +22,9 @@ 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});
@ -34,9 +38,9 @@ class _TransferScreenState extends State<TransferScreen> {
final _emailController = TextEditingController();
final _amountController = TextEditingController();
final _totpController = TextEditingController();
String? _selectedWalletType;
bool? _totpEnabled;
bool _requireWithdrawal2fa = true;
String _transferMinRemainingRaw = '0';
bool _submitting = false;
bool _confirming = false;
bool _securityFailed = false;
@ -60,6 +64,7 @@ class _TransferScreenState extends State<TransferScreen> {
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = health.requireWithdrawal2fa;
_transferMinRemainingRaw = health.transferMinRemainingRaw;
_securityFailed = false;
});
} catch (_) {
@ -95,8 +100,7 @@ class _TransferScreenState extends State<TransferScreen> {
return;
}
if (_selectedWalletType == null ||
_emailController.text.trim().isEmpty ||
if (_emailController.text.trim().isEmpty ||
_amountController.text.isEmpty) {
setState(() => _localError = s.transferFillFields);
showErrorSnackBar(context, s.transferFillFields);
@ -110,10 +114,24 @@ class _TransferScreenState extends State<TransferScreen> {
}
final state = context.read<WalletBloc>().state;
final selectedType = state.walletTypes.firstWhere(
(t) => t.code == _selectedWalletType,
orElse: () => state.walletTypes.first,
);
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') {
@ -134,6 +152,7 @@ class _TransferScreenState extends State<TransferScreen> {
setState(() {
_totpEnabled = profile.totpEnabled;
_requireWithdrawal2fa = preflight.health.requireWithdrawal2fa;
_transferMinRemainingRaw = preflight.health.transferMinRemainingRaw;
_securityFailed = false;
});
context.read<WalletBloc>().add(const WalletLoadRequested());
@ -145,7 +164,7 @@ class _TransferScreenState extends State<TransferScreen> {
}
final match = preflight.balances
.where((b) => b.walletType.code == _selectedWalletType)
.where((b) => b.walletType.code == _kTransferLedgerCode)
.toList();
if (match.isEmpty) {
showErrorSnackBar(context, s.walletBalanceNotLoaded);
@ -153,10 +172,26 @@ class _TransferScreenState extends State<TransferScreen> {
}
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>(
@ -167,7 +202,7 @@ class _TransferScreenState extends State<TransferScreen> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('${s.amountLabel}: $amountHuman ${selectedType.name}'),
Text('${s.amountLabel}: $amountHuman USDT'),
const SizedBox(height: 8),
SelectableText('${s.recipientEmail}: $email'),
const SizedBox(height: 16),
@ -195,7 +230,7 @@ class _TransferScreenState extends State<TransferScreen> {
context.read<WalletBloc>().add(
WalletTransferRequested(
toEmail: email,
walletType: _selectedWalletType!,
walletType: _kTransferLedgerCode,
amount: amountRaw,
totpCode: totp.isEmpty ? null : totp,
),
@ -265,7 +300,7 @@ class _TransferScreenState extends State<TransferScreen> {
}
final types = state.walletTypes;
final balances = state.balances;
if (types.isEmpty) {
if (types.isEmpty && balances.isEmpty) {
return ListView(
padding: EdgeInsets.fromLTRB(
20,
@ -281,15 +316,36 @@ class _TransferScreenState extends State<TransferScreen> {
],
);
}
_selectedWalletType ??= types.first.code;
if (!types.any((t) => t.code == _selectedWalletType)) {
_selectedWalletType = types.first.code;
WalletTypeModel? selectedType;
for (final t in types) {
if (t.code == _kTransferLedgerCode) {
selectedType = t;
break;
}
final selectedType = types.firstWhere(
(t) => t.code == _selectedWalletType,
}
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,
),
],
);
final networkLabel =
CoinDisplay.networkLabel(selectedType.code);
}
final busy = _submitting || _confirming;
return RefreshIndicator(
@ -382,37 +438,6 @@ class _TransferScreenState extends State<TransferScreen> {
),
),
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: [
@ -424,7 +449,7 @@ class _TransferScreenState extends State<TransferScreen> {
const SizedBox(width: 8),
Expanded(
child: Text(
s.depositNetworkLabel(networkLabel),
s.transferLedgerOnlyHint,
style: Theme.of(context)
.textTheme
.bodySmall,
@ -448,26 +473,51 @@ class _TransferScreenState extends State<TransferScreen> {
),
if (balances.any(
(b) =>
b.walletType.code == _selectedWalletType,
b.walletType.code ==
_kTransferLedgerCode,
)) ...[
const SizedBox(height: 8),
Text(
s.availableAsset(
rawAmountToHuman(
balances
Builder(
builder: (context) {
final availableRaw = balances
.firstWhere(
(b) =>
b.walletType.code ==
_selectedWalletType,
_kTransferLedgerCode,
)
.available,
.available;
final available = BigInt.tryParse(
availableRaw,
) ??
BigInt.zero;
final minRemaining =
CoinDisplay.scaleWithdrawalFeeRaw(
_transferMinRemainingRaw,
selectedType.decimals,
);
final maxRaw = available > minRemaining
? available - minRemaining
: BigInt.zero;
final label = minRemaining > BigInt.zero
? s.transferMaxWithMinRemaining(
'${rawAmountToHuman(maxRaw.toString(), selectedType.decimals)} USDT',
'${rawAmountToHuman(minRemaining.toString(), selectedType.decimals)} USDT',
)
: s.availableAsset(
rawAmountToHuman(
availableRaw,
selectedType.decimals,
),
selectedType.name,
),
'USDT',
);
return Text(
label,
key: const Key('transfer_available'),
style:
Theme.of(context).textTheme.bodySmall,
style: Theme.of(context)
.textTheme
.bodySmall,
);
},
),
],
],

View File

@ -313,6 +313,10 @@ class AppStrings {
'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 get transferLedgerOnlyHint => t(
'Transfers use your main USDT balance. Deposit/withdraw networks (TRC20 / BEP20) are not selected here.',
'Les transferts utilisent votre solde USDT principal. Les réseaux de dépôt/retrait (TRC20 / BEP20) ne se sélectionnent pas ici.',
);
String withdrawYouReceive(String amount) =>
t('You receive: $amount USDT', 'Vous recevez : $amount USDT');
String withdrawNetworkFee(String fee) =>
@ -603,6 +607,14 @@ class AppStrings {
'Insufficient balance on the selected wallet.',
'Solde insuffisant sur le portefeuille sélectionné.',
);
String transferMaxWithMinRemaining(String amount, String min) => t(
'You can transfer up to $amount (minimum remaining: $min).',
'Vous pouvez transférer jusqu’à $amount (solde minimum restant : $min).',
);
String transferMinRemainingError(String min) => t(
'Transfer refused: you must keep at least $min USDT after the transfer.',
'Transfert refusé : vous devez conserver au moins $min USDT après le transfert.',
);
String insufficientBalanceOn(String wallet) => t(
'Insufficient balance on the $wallet wallet for this stake.',
'Solde insuffisant sur le portefeuille $wallet pour cette mise.',

View File

@ -63,6 +63,7 @@ export function SettingsPage() {
candle_predict_backfill_seed_max: number;
engine_audit_log_retention_days: number;
withdrawal_network_fee_usdt_micro: number;
transfer_min_remaining_usdt_micro: number;
support_message_edit_window_minutes: number;
support_message_delete_window_minutes: number;
};
@ -434,6 +435,46 @@ export function SettingsPage() {
</AccordionDetails>
</Accordion>
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
<Box>
<Typography sx={{ fontWeight: 900 }}>{t('admin.settings.sections.transfers.title')}</Typography>
<Typography variant="body2" sx={{ opacity: 0.7 }}>
{t('admin.settings.sections.transfers.subtitle')}
</Typography>
</Box>
</AccordionSummary>
<AccordionDetails>
<Box
sx={{
display: 'grid',
gap: 1.5,
gridTemplateColumns: { xs: '1fr', md: 'repeat(12, 1fr)' },
}}
>
<Box sx={{ gridColumn: { xs: '1 / -1', md: 'span 6' } }}>
<TextField
label={t('admin.settings.sections.transfers.minRemaining')}
type="number"
slotProps={{ htmlInput: { min: 0, step: 0.01 } }}
value={((effective.transfer_min_remaining_usdt_micro ?? 0) / 1_000_000).toFixed(2)}
onChange={(e) => {
const usdt = parseFloat(e.target.value);
set(
'transfer_min_remaining_usdt_micro',
Number.isFinite(usdt) && usdt >= 0
? Math.round(usdt * 1_000_000)
: 0
);
}}
helperText={t('admin.settings.sections.transfers.minRemainingHelper')}
fullWidth
/>
</Box>
</Box>
</AccordionDetails>
</Accordion>
<Accordion defaultExpanded={false} sx={{ borderRadius: 2, overflow: 'hidden' }}>
<AccordionSummary expandIcon={<ExpandMoreRoundedIcon />}>
<Box>

View File

@ -64,7 +64,8 @@ export function WalletPage() {
const spendable = balancesQ.data?.spendable ?? null;
const networks = balancesQ.data?.networks ?? [];
const transferBalances = balancesQ.data?.balances ?? [];
/** Peer transfers use the main USDT ledger only (never deposit/withdraw rails). */
const transferBalances = spendable ? [spendable] : [];
const transactions = txQ.data?.items ?? [];
const txTotal = txQ.data?.total ?? 0;

View File

@ -1,6 +1,7 @@
/**
* In-app transfer dialog for the wallet page.
* Sends funds to another Tloto user by email with optional 2FA.
* Peer transfers always use the main USDT ledger (USDT_TRC20), not deposit/withdraw rails.
*/
import {
Alert,
@ -9,22 +10,19 @@ import {
DialogActions,
DialogContent,
DialogTitle,
FormControl,
InputLabel,
MenuItem,
Select,
Stack,
TextField,
Typography,
} from '@mui/material';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import { api } from '../../../shared/services/api';
import { apiErrorMessage } from '../../../shared/utils/apiError';
import type { BalanceEntry } from '../types';
import { networkLabel } from '../utils/coinDisplay';
import { formatBalance, humanToRaw, shortSymbol } from '../utils/walletFormat';
import { USDT_TRC20_CODE } from '../utils/walletCapabilities';
import { scaleWithdrawalFeeRaw } from '../utils/coinDisplay';
import { formatBalance, humanToRaw, rawToHuman, shortSymbol } from '../utils/walletFormat';
type TransferDialogProps = {
open: boolean;
@ -41,42 +39,86 @@ type TransferDialogProps = {
export function TransferDialog({
open,
balances,
initialAsset,
initialAsset: _initialAsset,
onClose,
onSuccess,
onError,
}: TransferDialogProps) {
const { t } = useTranslation();
const qc = useQueryClient();
const [asset, setAsset] = useState('');
const [toEmail, setToEmail] = useState('');
const [amount, setAmount] = useState('');
const [totpCode, setTotpCode] = useState('');
const [confirmOpen, setConfirmOpen] = useState(false);
const [submitting, setSubmitting] = useState(false);
const asset = USDT_TRC20_CODE;
const policyQ = useQuery({
queryKey: ['health', 'transfer-min-remaining'],
enabled: open,
queryFn: async () => {
const res = await api.get<{ transferMinRemainingRaw?: string }>('/health');
return res.data;
},
staleTime: 30_000,
});
useEffect(() => {
if (open) {
setAsset(initialAsset ?? balances[0]?.walletType.code ?? '');
setToEmail('');
setAmount('');
setTotpCode('');
setConfirmOpen(false);
}
}, [open, initialAsset, balances]);
}, [open]);
const selected = useMemo(
() => balances.find((b) => b.walletType.code === asset),
[balances, asset]
() =>
balances.find((b) => b.walletType.code === USDT_TRC20_CODE) ??
balances.find((b) => b.walletType.code?.toUpperCase().includes('USDT')) ??
balances[0],
[balances]
);
const minRemainingRaw = useMemo(() => {
if (!selected) return 0n;
return scaleWithdrawalFeeRaw(
policyQ.data?.transferMinRemainingRaw ?? '0',
selected.walletType.decimals
);
}, [policyQ.data?.transferMinRemainingRaw, selected]);
const maxTransferableRaw = useMemo(() => {
if (!selected) return 0n;
const available = BigInt(selected.available || '0');
const max = available - minRemainingRaw;
return max > 0n ? max : 0n;
}, [selected, minRemainingRaw]);
const amountHelper = useMemo(() => {
if (!selected) return undefined;
const availableText = t('wallet.transferDialog.available', {
amount: formatBalance(selected.available, selected.walletType.decimals, asset),
});
if (minRemainingRaw <= 0n) return availableText;
return t('wallet.transferDialog.maxTransferable', {
amount: formatBalance(
maxTransferableRaw.toString(),
selected.walletType.decimals,
asset
),
min: formatBalance(minRemainingRaw.toString(), selected.walletType.decimals, asset),
});
}, [selected, asset, minRemainingRaw, maxTransferableRaw, t]);
const submit = async () => {
if (!selected) return;
setSubmitting(true);
try {
await api.post('/api/v1/transfer', {
toEmail: toEmail.trim().toLowerCase(),
walletType: asset,
walletType: USDT_TRC20_CODE,
amount: humanToRaw(amount, selected.walletType.decimals),
totpCode: totpCode.trim() || undefined,
});
@ -85,8 +127,16 @@ export function TransferDialog({
onSuccess?.(t('wallet.transferDialog.success'));
onClose();
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
const err = e as { response?: { data?: { error?: string; code?: string } }; message?: string };
if (err.response?.data?.code === 'TRANSFER_MIN_REMAINING' && selected) {
onError?.(
t('wallet.transferDialog.minRemainingError', {
min: rawToHuman(minRemainingRaw.toString(), selected.walletType.decimals),
})
);
} else {
onError?.(apiErrorMessage(err, t('common.transferFailed')));
}
} finally {
setSubmitting(false);
setConfirmOpen(false);
@ -118,26 +168,9 @@ export function TransferDialog({
autoComplete="email"
/>
<FormControl fullWidth>
<InputLabel id="transfer-asset-label">{t('common.asset')}</InputLabel>
<Select
labelId="transfer-asset-label"
label={t('common.asset')}
value={asset}
onChange={(e) => setAsset(e.target.value)}
>
{balances.map((b) => (
<MenuItem key={b.walletType.code} value={b.walletType.code}>
{b.walletType.name} — {networkLabel(b.walletType.code)}
</MenuItem>
))}
</Select>
</FormControl>
<Alert severity="info" sx={{ borderRadius: 2 }}>
<Trans
i18nKey="wallet.transferDialog.networkAuto"
values={{ network: networkLabel(asset) }}
i18nKey="wallet.transferDialog.ledgerOnly"
components={{ b: <b /> }}
/>
</Alert>
@ -148,13 +181,7 @@ export function TransferDialog({
value={amount}
onChange={(e) => setAmount(e.target.value)}
inputMode="decimal"
helperText={
selected
? t('wallet.transferDialog.available', {
amount: formatBalance(selected.available, selected.walletType.decimals, asset),
})
: undefined
}
helperText={amountHelper}
/>
<TextField

View File

@ -417,7 +417,16 @@ export const en = {
subtitle: 'Transfer to another Tloto account instantly. On-chain fees do not apply.',
recipientEmail: 'Recipient email',
networkAuto: 'Network: <b>{{network}}</b> (auto-selected)',
ledgerOnly:
'Transfers use your <b>main USDT balance</b>. Deposit/withdraw networks (TRC20 / BEP20) are not selected here.',
ledgerOnlyError:
'Peer transfers use the main USDT balance only (not deposit/withdraw networks).',
available: 'Available: {{amount}}',
maxTransferable: 'You can transfer up to {{amount}} (minimum remaining balance: {{min}}).',
minRemainingError:
'Transfer refused: you must keep at least {{min}} USDT on your account after the transfer.',
minRemainingGeneric:
'Transfer refused: remaining balance would fall below the minimum configured by the administrator.',
totpCode: '2FA code',
totpPlaceholder: '6-digit code',
totpRequired: 'Required if 2FA is enabled on your account',
@ -2178,6 +2187,14 @@ export const en = {
networkFeeHelper:
"Deducted from the user's USDT balance per withdrawal (scaled per network decimals; covers on-chain gas).",
},
transfers: {
title: 'User transfers',
subtitle:
'Minimum balance that must remain after a peer-to-peer transfer. Does not affect deposits or withdrawals.',
minRemaining: 'Minimum remaining balance after transfer (USDT)',
minRemainingHelper:
'Sender must keep at least this amount after each transfer. Set to 0 to disable (full balance can be transferred).',
},
rateLimiting: {
title: 'Rate limiting',
subtitle:

View File

@ -425,7 +425,16 @@ export const fr = {
subtitle: 'Transférez vers un autre compte Tloto instantanément. Pas de frais on-chain.',
recipientEmail: 'E-mail du destinataire',
networkAuto: 'Réseau : <b>{{network}}</b> (sélection automatique)',
ledgerOnly:
'Les transferts utilisent votre <b>solde USDT principal</b>. Les réseaux de dépôt/retrait (TRC20 / BEP20) ne se sélectionnent pas ici.',
ledgerOnlyError:
'Les transferts entre utilisateurs utilisent uniquement le solde USDT principal (pas les réseaux de dépôt/retrait).',
available: 'Disponible : {{amount}}',
maxTransferable: 'Vous pouvez transférer jusqu’à {{amount}} (solde minimum restant : {{min}}).',
minRemainingError:
'Transfert refusé : vous devez conserver au moins {{min}} USDT sur votre compte après le transfert.',
minRemainingGeneric:
'Transfert refusé : le solde restant passerait sous le minimum configuré par l’administrateur.',
totpCode: 'Code 2FA',
totpPlaceholder: 'Code à 6 chiffres',
totpRequired: 'Requis si la 2FA est activée sur votre compte',
@ -2197,6 +2206,14 @@ export const fr = {
networkFeeHelper:
'Déduit du solde USDT de l’utilisateur par retrait (adapté aux décimales du réseau ; couvre le gas on-chain).',
},
transfers: {
title: 'Transferts entre utilisateurs',
subtitle:
'Solde minimum à conserver après un transfert entre utilisateurs. N’affecte ni les dépôts ni les retraits.',
minRemaining: 'Solde minimum restant après transfert (USDT)',
minRemainingHelper:
'L’expéditeur doit conserver au moins ce montant après chaque transfert. Mettre 0 pour désactiver (transfert du solde total autorisé).',
},
rateLimiting: {
title: 'Limitation de débit',
subtitle:

View File

@ -45,6 +45,12 @@ export function apiErrorMessage(error: unknown, fallback?: string): string {
const wait = typeof data.wait === 'string' && data.wait.trim() ? data.wait : '24h';
return i18n.t('wallet.testCard.predictionLimitReached', { wait });
}
if (data?.code === 'TRANSFER_MIN_REMAINING') {
return i18n.t('wallet.transferDialog.minRemainingGeneric');
}
if (data?.code === 'TRANSFER_LEDGER_ONLY') {
return i18n.t('wallet.transferDialog.ledgerOnlyError');
}
const apiMsg = data?.error ?? data?.message;
if (typeof apiMsg === 'string' && apiMsg.trim()) {
return sanitizeApiText(apiMsg, fb);