From e3b109a988ead4e8d44814402571006cfaf70572 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 2 Nov 2026 19:59:28 +0200 Subject: [PATCH] After adding option to prevent users to send money without any control --- backend/src/app.ts | 4 + backend/src/db/schema.sql | 4 + backend/src/models/settings.model.ts | 5 + backend/src/repositories/ledgerRepository.ts | 14 +- .../src/repositories/settingsRepository.ts | 6 + backend/src/services/settingsService.ts | 20 ++ backend/src/services/transferService.ts | 42 +++- backend/src/tests/mobileApiE2e.test.ts | 1 + backend/src/tests/withdrawalFee.test.ts | 20 +- backend/src/utils/httpError.ts | 9 +- backend/src/utils/withdrawalFee.ts | 23 ++- .../lib/core/errors/app_exception.dart | 12 ++ .../repositories/health_repository.dart | 5 + .../wallet/presentation/transfer_screen.dart | 186 +++++++++++------- prediqo_mobile/lib/l10n/app_strings.dart | 12 ++ .../src/features/settings/SettingsPage.tsx | 41 ++++ .../src/features/wallet/WalletPage.tsx | 3 +- .../wallet/components/TransferDialog.tsx | 109 ++++++---- prediqo_web/src/shared/i18n/locales/en.ts | 17 ++ prediqo_web/src/shared/i18n/locales/fr.ts | 17 ++ prediqo_web/src/shared/utils/apiError.ts | 6 + 21 files changed, 431 insertions(+), 125 deletions(-) diff --git a/backend/src/app.ts b/backend/src/app.ts index d51f3f27..e71d4467 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -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, diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index 1e71c367..887ef69d 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -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(), diff --git a/backend/src/models/settings.model.ts b/backend/src/models/settings.model.ts index 14fb0894..0b1de478 100644 --- a/backend/src/models/settings.model.ts +++ b/backend/src/models/settings.model.ts @@ -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. */ diff --git a/backend/src/repositories/ledgerRepository.ts b/backend/src/repositories/ledgerRepository.ts index d87b8ffc..8cc55072 100644 --- a/backend/src/repositories/ledgerRepository.ts +++ b/backend/src/repositories/ledgerRepository.ts @@ -278,15 +278,17 @@ export async function deductLocked(accountId: string, amount: bigint): Promise { 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', diff --git a/backend/src/repositories/settingsRepository.ts b/backend/src/repositories/settingsRepository.ts index 4f12ca35..a1575b1f 100644 --- a/backend/src/repositories/settingsRepository.ts +++ b/backend/src/repositories/settingsRepository.ts @@ -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', diff --git a/backend/src/services/settingsService.ts b/backend/src/services/settingsService.ts index 70d3ade4..13fff0d2 100644 --- a/backend/src/services/settingsService.ts +++ b/backend/src/services/settingsService.ts @@ -155,6 +155,20 @@ function validateUpdates(updates: Partial): 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): Partial { - 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' }; } diff --git a/backend/src/tests/mobileApiE2e.test.ts b/backend/src/tests/mobileApiE2e.test.ts index b3dbcac3..07ed4e61 100644 --- a/backend/src/tests/mobileApiE2e.test.ts +++ b/backend/src/tests/mobileApiE2e.test.ts @@ -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 () => { diff --git a/backend/src/tests/withdrawalFee.test.ts b/backend/src/tests/withdrawalFee.test.ts index 25859806..ea018beb 100644 --- a/backend/src/tests/withdrawalFee.test.ts +++ b/backend/src/tests/withdrawalFee.test.ts @@ -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); + }); +}); diff --git a/backend/src/utils/httpError.ts b/backend/src/utils/httpError.ts index 09679c74..4778bba8 100644 --- a/backend/src/utils/httpError.ts +++ b/backend/src/utils/httpError.ts @@ -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; diff --git a/backend/src/utils/withdrawalFee.ts b/backend/src/utils/withdrawalFee.ts index 4a9d26b5..d1edf246 100644 --- a/backend/src/utils/withdrawalFee.ts +++ b/backend/src/utils/withdrawalFee.ts @@ -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). */ diff --git a/prediqo_mobile/lib/core/errors/app_exception.dart b/prediqo_mobile/lib/core/errors/app_exception.dart index 82718380..c01912b1 100644 --- a/prediqo_mobile/lib/core/errors/app_exception.dart +++ b/prediqo_mobile/lib/core/errors/app_exception.dart @@ -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'; diff --git a/prediqo_mobile/lib/domain/repositories/health_repository.dart b/prediqo_mobile/lib/domain/repositories/health_repository.dart index 01b14b8a..9e6d58b3 100644 --- a/prediqo_mobile/lib/domain/repositories/health_repository.dart +++ b/prediqo_mobile/lib/domain/repositories/health_repository.dart @@ -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 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; diff --git a/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart index 65f2eaf2..a7961d46 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart @@ -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 { 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 { setState(() { _totpEnabled = profile.totpEnabled; _requireWithdrawal2fa = health.requireWithdrawal2fa; + _transferMinRemainingRaw = health.transferMinRemainingRaw; _securityFailed = false; }); } catch (_) { @@ -95,8 +100,7 @@ class _TransferScreenState extends State { 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 { } final state = context.read().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 { setState(() { _totpEnabled = profile.totpEnabled; _requireWithdrawal2fa = preflight.health.requireWithdrawal2fa; + _transferMinRemainingRaw = preflight.health.transferMinRemainingRaw; _securityFailed = false; }); context.read().add(const WalletLoadRequested()); @@ -145,7 +164,7 @@ class _TransferScreenState extends State { } 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 { } 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( @@ -167,7 +202,7 @@ class _TransferScreenState extends State { 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 { context.read().add( WalletTransferRequested( toEmail: email, - walletType: _selectedWalletType!, + walletType: _kTransferLedgerCode, amount: amountRaw, totpCode: totp.isEmpty ? null : totp, ), @@ -265,7 +300,7 @@ class _TransferScreenState extends State { } 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 { ], ); } - _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; + } + } + 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 selectedType = types.firstWhere( - (t) => t.code == _selectedWalletType, - ); - final networkLabel = - CoinDisplay.networkLabel(selectedType.code); final busy = _submitting || _confirming; return RefreshIndicator( @@ -382,37 +438,6 @@ class _TransferScreenState extends State { ), ), const SizedBox(height: 14), - Text( - s.assetLabel, - style: const TextStyle( - fontWeight: FontWeight.w700, - ), - ), - const SizedBox(height: 8), - DropdownButtonFormField( - 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 { 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 { ), if (balances.any( (b) => - b.walletType.code == _selectedWalletType, + b.walletType.code == + _kTransferLedgerCode, )) ...[ const SizedBox(height: 8), - Text( - s.availableAsset( - rawAmountToHuman( - balances - .firstWhere( - (b) => - b.walletType.code == - _selectedWalletType, - ) - .available, + 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, selectedType.decimals, - ), - selectedType.name, - ), - key: const Key('transfer_available'), - style: - Theme.of(context).textTheme.bodySmall, + ); + 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, + ), + 'USDT', + ); + return Text( + label, + key: const Key('transfer_available'), + style: Theme.of(context) + .textTheme + .bodySmall, + ); + }, ), ], ], diff --git a/prediqo_mobile/lib/l10n/app_strings.dart b/prediqo_mobile/lib/l10n/app_strings.dart index 0e1551d7..ab2b3fe9 100644 --- a/prediqo_mobile/lib/l10n/app_strings.dart +++ b/prediqo_mobile/lib/l10n/app_strings.dart @@ -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.', diff --git a/prediqo_web/src/features/settings/SettingsPage.tsx b/prediqo_web/src/features/settings/SettingsPage.tsx index e2f37349..536d3846 100644 --- a/prediqo_web/src/features/settings/SettingsPage.tsx +++ b/prediqo_web/src/features/settings/SettingsPage.tsx @@ -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() { + + }> + + {t('admin.settings.sections.transfers.title')} + + {t('admin.settings.sections.transfers.subtitle')} + + + + + + + { + 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 + /> + + + + + }> diff --git a/prediqo_web/src/features/wallet/WalletPage.tsx b/prediqo_web/src/features/wallet/WalletPage.tsx index 18412127..22377c80 100644 --- a/prediqo_web/src/features/wallet/WalletPage.tsx +++ b/prediqo_web/src/features/wallet/WalletPage.tsx @@ -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; diff --git a/prediqo_web/src/features/wallet/components/TransferDialog.tsx b/prediqo_web/src/features/wallet/components/TransferDialog.tsx index 8821b190..4ce3a70a 100644 --- a/prediqo_web/src/features/wallet/components/TransferDialog.tsx +++ b/prediqo_web/src/features/wallet/components/TransferDialog.tsx @@ -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 }; - onError?.(apiErrorMessage(err, t('common.transferFailed'))); + 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" /> - - {t('common.asset')} - - - }} /> @@ -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} /> {{network}} (auto-selected)', + ledgerOnly: + 'Transfers use your main USDT balance. 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: diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index 40b9e7fc..d4ee79b9 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -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 : {{network}} (sélection automatique)', + ledgerOnly: + 'Les transferts utilisent votre solde USDT principal. 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: diff --git a/prediqo_web/src/shared/utils/apiError.ts b/prediqo_web/src/shared/utils/apiError.ts index 1e6b3244..e7934643 100644 --- a/prediqo_web/src/shared/utils/apiError.ts +++ b/prediqo_web/src/shared/utils/apiError.ts @@ -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);