After changing about commission dispatch and adding sharing card8

This commit is contained in:
Your Name 2026-08-02 15:24:32 +02:00
parent 704bee9bd6
commit 2d9b3ff5a7
17 changed files with 483 additions and 12 deletions

View File

@ -5,6 +5,7 @@ import { AuthRequest } from '../middleware/auth';
import { hasAdminAccess } from '../utils/roleAccess';
import * as candlePredictService from '../services/candlePredictService';
import { TestWalletError } from '../services/testWalletService';
import { parseStakeAmountFromBody } from '../utils/stakeAmountValidation';
import { readIdempotencyKey, sendPlaceBetResult } from '../utils/placeBetResponse';
import {
@ -12,6 +13,16 @@ import {
getStateVersions,
} from '../realtime/redis/stateVersions';
function placeBetErrorBody(e: unknown, fallback: string): { error: string; code?: string; wait?: string } {
if (e instanceof TestWalletError) {
return {
error: e.message,
...(e.code ? { code: e.code } : {}),
...(e.waitLabel ? { wait: e.waitLabel } : {}),
};
}
return { error: e instanceof Error ? e.message : fallback };
}
const STATE_CACHE_TTL_MS = 1200;
const STATE_CACHE_MAX_ENTRIES = 500;
@ -352,12 +363,12 @@ export async function placeBet(req: AuthRequest, res: Response): Promise<void> {
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to place prediction';
console.warn('[candle-predict] placeBet rejected:', msg, {
const body = placeBetErrorBody(e, 'Failed to place prediction');
console.warn('[candle-predict] placeBet rejected:', body.error, {
userId: req.user?.userId,
});
res.status(400).json({ error: msg });
res.status(400).json(body);
}
@ -745,9 +756,7 @@ export async function placeMultiBet(req: AuthRequest, res: Response): Promise<vo
} catch (e) {
const msg = e instanceof Error ? e.message : 'Failed to place multi-candle prediction';
res.status(400).json({ error: msg });
res.status(400).json(placeBetErrorBody(e, 'Failed to place multi-candle prediction'));
}

View File

@ -38,6 +38,9 @@ export async function updateAdminConfig(req: AuthRequest, res: Response): Promis
maxRequestsPerUser?: number;
cooldownHours?: number;
walletTypeId?: number;
predictionLimitEnabled?: boolean;
maxTestPredictionsPerWindow?: number;
testPredictionWindowHours?: number;
};
const config = await testWalletService.updateSettings(body);
res.json(config);

View File

@ -1130,6 +1130,9 @@ CREATE TABLE IF NOT EXISTS test_wallet_settings (
max_requests_per_user INTEGER NOT NULL DEFAULT 5 CHECK (max_requests_per_user >= 0),
cooldown_hours INTEGER NOT NULL DEFAULT 24 CHECK (cooldown_hours >= 0),
wallet_type_id INTEGER NOT NULL REFERENCES wallet_types(id),
prediction_limit_enabled BOOLEAN NOT NULL DEFAULT FALSE,
max_test_predictions_per_window INTEGER NOT NULL DEFAULT 10 CHECK (max_test_predictions_per_window >= 0),
test_prediction_window_hours INTEGER NOT NULL DEFAULT 24 CHECK (test_prediction_window_hours >= 1),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
@ -1137,6 +1140,27 @@ INSERT INTO test_wallet_settings (id, wallet_type_id)
SELECT 1, id FROM wallet_types WHERE code = 'USDT_TRC20'
ON CONFLICT (id) DO NOTHING;
-- Existing DBs: add Test Wallet prediction-rate-limit columns
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'test_wallet_settings'
AND column_name = 'prediction_limit_enabled'
) THEN
ALTER TABLE test_wallet_settings
ADD COLUMN prediction_limit_enabled BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN max_test_predictions_per_window INTEGER NOT NULL DEFAULT 10,
ADD COLUMN test_prediction_window_hours INTEGER NOT NULL DEFAULT 24;
ALTER TABLE test_wallet_settings
ADD CONSTRAINT test_wallet_settings_max_test_predictions_per_window_check
CHECK (max_test_predictions_per_window >= 0);
ALTER TABLE test_wallet_settings
ADD CONSTRAINT test_wallet_settings_test_prediction_window_hours_check
CHECK (test_prediction_window_hours >= 1);
END IF;
END $$;
CREATE TABLE IF NOT EXISTS test_wallet_credits (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
@ -1147,6 +1171,9 @@ CREATE TABLE IF NOT EXISTS test_wallet_credits (
CREATE INDEX IF NOT EXISTS idx_test_wallet_credits_user ON test_wallet_credits(user_id);
CREATE INDEX IF NOT EXISTS idx_test_wallet_credits_created ON test_wallet_credits(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_candle_predict_bets_user_test_created
ON candle_predict_bets (user_id, created_at DESC)
WHERE stake_account_kind = 'test';
DO $$
DECLARE

View File

@ -25,6 +25,7 @@ import {
isMaturityBoundaryForInterval,
} from '../../services/gameTimingService';
import * as multiService from '../../services/candlePredictMultiService';
import * as testWalletService from '../../services/testWalletService';
import {
pickRandomDirectionalOutcome,
projectMajorityWinSettlement,
@ -1977,6 +1978,9 @@ export async function executePlaceBetInternal(
const stakeRaw = stakeToRaw(input.stakeDisplay);
const stakeAccountKind = parseStakeAccountKind(input.stakeAccountKind);
if (stakeAccountKind === 'test') {
await testWalletService.assertTestPredictionAllowed(userId);
}
const { debitAccountId } = await resolveDebitAccount(
userId,
walletType.id,
@ -2402,6 +2406,9 @@ export async function placeMultiCandleBet(
const stakeRaw = stakeToRaw(input.stakeDisplay);
const stakeAccountKind = parseStakeAccountKind(input.stakeAccountKind);
if (stakeAccountKind === 'test') {
await testWalletService.assertTestPredictionAllowed(userId);
}
const { debitAccountId } = await resolveDebitAccount(
userId,
walletType.id,

View File

@ -11,6 +11,9 @@ export type TestWalletSettingsRow = {
max_requests_per_user: number;
cooldown_hours: number;
wallet_type_id: number;
prediction_limit_enabled: boolean;
max_test_predictions_per_window: number;
test_prediction_window_hours: number;
updated_at: Date;
};
@ -27,10 +30,13 @@ export type TestWalletCreditListRow = TestWalletCreditRow & {
wallet_code: string;
};
const SETTINGS_SELECT = `id, enabled, credit_amount_raw::text, max_requests_per_user, cooldown_hours,
wallet_type_id, prediction_limit_enabled, max_test_predictions_per_window,
test_prediction_window_hours, updated_at`;
export async function getSettings(): Promise<TestWalletSettingsRow> {
const rows = await query<TestWalletSettingsRow[]>(
`SELECT id, enabled, credit_amount_raw::text, max_requests_per_user, cooldown_hours,
wallet_type_id, updated_at
`SELECT ${SETTINGS_SELECT}
FROM test_wallet_settings WHERE id = 1`
);
if (!rows[0]) {
@ -45,6 +51,9 @@ export async function updateSettings(input: {
maxRequestsPerUser?: number;
cooldownHours?: number;
walletTypeId?: number;
predictionLimitEnabled?: boolean;
maxTestPredictionsPerWindow?: number;
testPredictionWindowHours?: number;
}): Promise<TestWalletSettingsRow> {
const current = await getSettings();
const rows = await query<TestWalletSettingsRow[]>(
@ -54,16 +63,21 @@ export async function updateSettings(input: {
max_requests_per_user = COALESCE($3, max_requests_per_user),
cooldown_hours = COALESCE($4, cooldown_hours),
wallet_type_id = COALESCE($5, wallet_type_id),
prediction_limit_enabled = COALESCE($6, prediction_limit_enabled),
max_test_predictions_per_window = COALESCE($7, max_test_predictions_per_window),
test_prediction_window_hours = COALESCE($8, test_prediction_window_hours),
updated_at = NOW()
WHERE id = 1
RETURNING id, enabled, credit_amount_raw::text, max_requests_per_user, cooldown_hours,
wallet_type_id, updated_at`,
RETURNING ${SETTINGS_SELECT}`,
[
input.enabled ?? null,
input.creditAmountRaw ?? null,
input.maxRequestsPerUser ?? null,
input.cooldownHours ?? null,
input.walletTypeId ?? null,
input.predictionLimitEnabled ?? null,
input.maxTestPredictionsPerWindow ?? null,
input.testPredictionWindowHours ?? null,
]
);
return rows[0] ?? current;
@ -88,6 +102,26 @@ export async function getLastCreditAt(userId: string): Promise<Date | null> {
return rows[0]?.created_at ?? null;
}
/** Sliding-window count of Test Wallet predictions (single + multi + auto). */
export async function countTestPredictionsInWindow(
userId: string,
windowHours: number
): Promise<{ count: number; oldestInWindowAt: Date | null }> {
const hours = Math.max(1, Math.floor(windowHours));
const rows = await query<Array<{ count: string; oldest: Date | null }>>(
`SELECT COUNT(*)::text AS count, MIN(created_at) AS oldest
FROM candle_predict_bets
WHERE user_id = $1
AND stake_account_kind = 'test'
AND created_at >= NOW() - make_interval(hours => $2)`,
[userId, hours]
);
return {
count: parseInt(rows[0]?.count ?? '0', 10) || 0,
oldestInWindowAt: rows[0]?.oldest ?? null,
};
}
export async function createCreditRecord(input: {
userId: string;
walletTypeId: number;

View File

@ -10,9 +10,14 @@ import * as auditLogRepository from '../repositories/auditLogRepository';
import { decrypt } from '../utils/crypto';
export class TestWalletError extends Error {
constructor(message: string) {
readonly code?: string;
readonly waitLabel?: string;
constructor(message: string, opts?: { code?: string; waitLabel?: string }) {
super(message);
this.name = 'TestWalletError';
this.code = opts?.code;
this.waitLabel = opts?.waitLabel;
}
}
@ -31,6 +36,9 @@ export async function getSettingsForAdmin() {
cooldownHours: settings.cooldown_hours,
walletTypeId: settings.wallet_type_id,
walletCode: walletType?.code ?? null,
predictionLimitEnabled: settings.prediction_limit_enabled,
maxTestPredictionsPerWindow: settings.max_test_predictions_per_window,
testPredictionWindowHours: settings.test_prediction_window_hours,
updatedAt: settings.updated_at,
};
}
@ -41,6 +49,9 @@ export async function updateSettings(input: {
maxRequestsPerUser?: number;
cooldownHours?: number;
walletTypeId?: number;
predictionLimitEnabled?: boolean;
maxTestPredictionsPerWindow?: number;
testPredictionWindowHours?: number;
}) {
if (input.creditAmountRaw !== undefined) {
const amount = BigInt(input.creditAmountRaw);
@ -52,6 +63,12 @@ export async function updateSettings(input: {
if (input.cooldownHours !== undefined && input.cooldownHours < 0) {
throw new TestWalletError('cooldownHours cannot be negative');
}
if (input.maxTestPredictionsPerWindow !== undefined && input.maxTestPredictionsPerWindow < 0) {
throw new TestWalletError('maxTestPredictionsPerWindow cannot be negative');
}
if (input.testPredictionWindowHours !== undefined && input.testPredictionWindowHours < 1) {
throw new TestWalletError('testPredictionWindowHours must be at least 1');
}
if (input.walletTypeId !== undefined) {
const wt = await resolveWalletType(input.walletTypeId);
if (!wt) throw new TestWalletError('Wallet type not found');
@ -62,10 +79,104 @@ export async function updateSettings(input: {
maxRequestsPerUser: input.maxRequestsPerUser,
cooldownHours: input.cooldownHours,
walletTypeId: input.walletTypeId,
predictionLimitEnabled: input.predictionLimitEnabled,
maxTestPredictionsPerWindow: input.maxTestPredictionsPerWindow,
testPredictionWindowHours: input.testPredictionWindowHours,
});
return getSettingsForAdmin();
}
function formatRemainingDuration(ms: number): string {
const totalMinutes = Math.max(1, Math.ceil(ms / 60_000));
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
const parts: string[] = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0 && days === 0) parts.push(`${minutes}m`);
if (parts.length === 0) parts.push('1m');
return parts.join(' ');
}
export type TestPredictionLimitStatus = {
enabled: boolean;
maxPerWindow: number;
windowHours: number;
usedInWindow: number;
remaining: number;
resetsAt: string | null;
canPredict: boolean;
reason: string | null;
};
export async function getTestPredictionLimitStatus(
userId: string
): Promise<TestPredictionLimitStatus> {
const settings = await testWalletRepository.getSettings();
const max = settings.max_test_predictions_per_window;
const windowHours = settings.test_prediction_window_hours;
if (!settings.prediction_limit_enabled || max <= 0) {
return {
enabled: false,
maxPerWindow: max,
windowHours,
usedInWindow: 0,
remaining: max > 0 ? max : Number.MAX_SAFE_INTEGER,
resetsAt: null,
canPredict: true,
reason: null,
};
}
const { count, oldestInWindowAt } = await testWalletRepository.countTestPredictionsInWindow(
userId,
windowHours
);
const remaining = Math.max(0, max - count);
if (count < max) {
return {
enabled: true,
maxPerWindow: max,
windowHours,
usedInWindow: count,
remaining,
resetsAt: null,
canPredict: true,
reason: null,
};
}
const resetsAt = oldestInWindowAt
? new Date(oldestInWindowAt.getTime() + windowHours * 60 * 60 * 1000)
: new Date(Date.now() + windowHours * 60 * 60 * 1000);
const remainingMs = Math.max(0, resetsAt.getTime() - Date.now());
const wait = formatRemainingDuration(remainingMs);
return {
enabled: true,
maxPerWindow: max,
windowHours,
usedInWindow: count,
remaining: 0,
resetsAt: resetsAt.toISOString(),
canPredict: false,
reason: `You have reached the maximum number of Test Wallet uses allowed (${max} per ${windowHours}h). Please try again in ${wait}.`,
};
}
/** Throws when the user may not place another Test Wallet prediction. */
export async function assertTestPredictionAllowed(userId: string): Promise<void> {
const status = await getTestPredictionLimitStatus(userId);
if (!status.canPredict) {
throw new TestWalletError(status.reason ?? 'Test Wallet prediction limit reached.', {
code: 'TEST_PREDICTION_LIMIT',
waitLabel: status.resetsAt
? formatRemainingDuration(Math.max(0, new Date(status.resetsAt).getTime() - Date.now()))
: `${status.windowHours}h`,
});
}
}
async function evaluateEligibility(userId: string) {
const settings = await testWalletRepository.getSettings();
if (!settings.enabled) {
@ -117,6 +228,7 @@ export async function getUserTestWalletStatus(userId: string) {
const { settings } = eligibility;
const walletType = await resolveWalletType(settings.wallet_type_id);
const testAccount = await ledgerRepository.getAccount(userId, settings.wallet_type_id, 'test');
const predictionLimit = await getTestPredictionLimitStatus(userId);
return {
enabled: settings.enabled,
@ -130,6 +242,7 @@ export async function getUserTestWalletStatus(userId: string) {
canRequest: eligibility.canRequest,
reason: eligibility.reason,
cooldownEndsAt: eligibility.cooldownEndsAt,
predictionLimit,
};
}

View File

@ -184,6 +184,9 @@ export const testWalletConfigBodySchema = atLeastOneField(
maxRequestsPerUser: z.number().int().min(0).max(1000).optional(),
cooldownHours: z.number().int().min(0).max(8760).optional(),
walletTypeId: z.number().int().positive().optional(),
predictionLimitEnabled: z.boolean().optional(),
maxTestPredictionsPerWindow: z.number().int().min(0).max(100_000).optional(),
testPredictionWindowHours: z.number().int().min(1).max(8760).optional(),
})
);

View File

@ -84,6 +84,18 @@ class AppException implements Exception {
retryAfterMinutes: retryAfterMinutes,
);
}
if (code == 'TEST_PREDICTION_LIMIT') {
final waitRaw = data['wait'];
final wait = waitRaw is String && waitRaw.trim().isNotEmpty ? waitRaw.trim() : '24h';
return AppException(
_t(
'You have reached the maximum number of Test Wallet uses allowed. Please try again in $wait.',
'Vous avez atteint le nombre maximal d’utilisations autorisées du compte Test. Veuillez réessayer dans $wait.',
),
statusCode: status,
code: 'TEST_PREDICTION_LIMIT',
);
}
if (msg is String && msg.isNotEmpty) {
return AppException(
sanitizeApiMessage(msg, fallback: fallback),

View File

@ -1,6 +1,51 @@
/// Status and credit-request payload for the play-money test wallet.
library;
class TestPredictionLimitModel {
const TestPredictionLimitModel({
required this.enabled,
required this.maxPerWindow,
required this.windowHours,
required this.usedInWindow,
required this.remaining,
required this.canPredict,
this.resetsAt,
this.reason,
});
final bool enabled;
final int maxPerWindow;
final int windowHours;
final int usedInWindow;
final int remaining;
final bool canPredict;
final String? resetsAt;
final String? reason;
factory TestPredictionLimitModel.fromJson(Map<String, dynamic>? json) {
if (json == null) {
return const TestPredictionLimitModel(
enabled: false,
maxPerWindow: 0,
windowHours: 24,
usedInWindow: 0,
remaining: 0,
canPredict: true,
);
}
return TestPredictionLimitModel(
enabled: json['enabled'] == true,
maxPerWindow: (json['maxPerWindow'] as num?)?.toInt() ?? 0,
windowHours: (json['windowHours'] as num?)?.toInt() ?? 24,
usedInWindow: (json['usedInWindow'] as num?)?.toInt() ?? 0,
remaining: (json['remaining'] as num?)?.toInt() ?? 0,
canPredict: json['canPredict'] != false,
resetsAt: json['resetsAt'] as String?,
reason: json['reason'] as String?,
);
}
}
class TestWalletStatusModel {
const TestWalletStatusModel({
required this.enabled,
@ -14,6 +59,7 @@ class TestWalletStatusModel {
required this.canRequest,
this.reason,
this.cooldownEndsAt,
this.predictionLimit,
});
final bool enabled;
@ -27,8 +73,10 @@ class TestWalletStatusModel {
final bool canRequest;
final String? reason;
final String? cooldownEndsAt;
final TestPredictionLimitModel? predictionLimit;
factory TestWalletStatusModel.fromJson(Map<String, dynamic> json) {
final limitRaw = json['predictionLimit'];
return TestWalletStatusModel(
enabled: json['enabled'] == true,
balanceRaw: (json['balanceRaw'] ?? '0').toString(),
@ -41,6 +89,9 @@ class TestWalletStatusModel {
canRequest: json['canRequest'] == true,
reason: json['reason'] as String?,
cooldownEndsAt: json['cooldownEndsAt'] as String?,
predictionLimit: limitRaw is Map<String, dynamic>
? TestPredictionLimitModel.fromJson(limitRaw)
: null,
);
}
}

View File

@ -820,6 +820,40 @@ class _TestWalletRequestFooter extends StatelessWidget {
),
],
],
if (status?.predictionLimit?.enabled == true &&
(status!.predictionLimit!.maxPerWindow > 0)) ...[
const SizedBox(height: 8),
Text(
s.testPredictionsUsed(
status!.predictionLimit!.usedInWindow,
status!.predictionLimit!.maxPerWindow,
status!.predictionLimit!.windowHours,
),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.textMuted,
),
),
if (status!.predictionLimit!.canPredict == false) ...[
const SizedBox(height: 8),
Text(
[
s.testPredictionLimitReached(
_formatWaitUntil(
status!.predictionLimit!.resetsAt,
status!.predictionLimit!.windowHours,
),
),
if (status!.predictionLimit!.resetsAt != null)
s.testPredictionResetsAt(
_formatDateTime(status!.predictionLimit!.resetsAt!),
),
].join(' '),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: AppColors.warning,
),
),
],
],
],
);
}
@ -1147,6 +1181,26 @@ bool _listEquals(List<String> a, List<String> b) {
return true;
}
String _formatWaitUntil(String? resetsAt, int windowHours) {
if (resetsAt != null) {
final end = DateTime.tryParse(resetsAt)?.toLocal();
if (end != null) {
final ms = end.difference(DateTime.now()).inMilliseconds;
final totalMinutes = ms <= 0 ? 1 : ((ms + 59999) ~/ 60000);
final days = totalMinutes ~/ (60 * 24);
final hours = (totalMinutes % (60 * 24)) ~/ 60;
final minutes = totalMinutes % 60;
final parts = <String>[];
if (days > 0) parts.add('${days}d');
if (hours > 0) parts.add('${hours}h');
if (minutes > 0 && days == 0) parts.add('${minutes}m');
if (parts.isEmpty) parts.add('1m');
return parts.join(' ');
}
}
return '${windowHours}h';
}
String _formatDateTime(String iso) {
final dt = DateTime.tryParse(iso)?.toLocal();
if (dt == null) return iso;

View File

@ -196,6 +196,18 @@ class AppStrings {
'Test wallet requests are currently disabled by the platform.',
'Les demandes de portefeuille test sont actuellement désactivées par la plateforme.',
);
String testPredictionsUsed(int used, int max, int hours) => t(
'Test predictions used: $used / $max (per ${hours}h)',
'Prédictions Test utilisées : $used / $max (par ${hours}h)',
);
String testPredictionLimitReached(String wait) => t(
'You have reached the maximum number of Test Wallet uses allowed. Please try again in $wait.',
'Vous avez atteint le nombre maximal d’utilisations autorisées du compte Test. Veuillez réessayer dans $wait.',
);
String testPredictionResetsAt(String date) => t(
'Resets at $date.',
'Réinitialisation à $date.',
);
String get hideBalance => t('Hide balance', 'Masquer le solde');
String get showBalance => t('Show balance', 'Afficher le solde');
String get lockedBalance => t('Locked', 'Bloqué');

View File

@ -315,6 +315,8 @@ export function usePlaceCandleBet() {
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
await qc.invalidateQueries({ queryKey: ['test-wallet-status'] });
},
});
@ -351,6 +353,8 @@ export function usePlaceMultiCandleBet() {
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
await qc.invalidateQueries({ queryKey: ['test-wallet-status'] });
},
});

View File

@ -34,6 +34,9 @@ type TestWalletConfig = {
cooldownHours: number;
walletTypeId: number;
walletCode: string | null;
predictionLimitEnabled: boolean;
maxTestPredictionsPerWindow: number;
testPredictionWindowHours: number;
updatedAt: string;
};
@ -91,6 +94,9 @@ export function TestWalletAdminPage() {
maxRequestsPerUser: form.maxRequestsPerUser,
cooldownHours: form.cooldownHours,
walletTypeId: form.walletTypeId,
predictionLimitEnabled: form.predictionLimitEnabled,
maxTestPredictionsPerWindow: form.maxTestPredictionsPerWindow,
testPredictionWindowHours: form.testPredictionWindowHours,
});
return res.data;
},
@ -164,6 +170,53 @@ export function TestWalletAdminPage() {
helperText={t('admin.testWallet.cooldownHelper')}
fullWidth
/>
<Typography variant="subtitle1" sx={{ fontWeight: 800, pt: 1 }}>
{t('admin.testWallet.predictionLimitTitle')}
</Typography>
<Typography variant="body2" sx={{ opacity: 0.7, mt: -1 }}>
{t('admin.testWallet.predictionLimitSubtitle')}
</Typography>
<FormControlLabel
control={
<Switch
checked={form.predictionLimitEnabled ?? false}
onChange={(e) =>
setForm({ ...form, predictionLimitEnabled: e.target.checked })
}
/>
}
label={t('admin.testWallet.predictionLimitEnabled')}
/>
<TextField
label={t('admin.testWallet.maxTestPredictions')}
type="number"
value={form.maxTestPredictionsPerWindow ?? 10}
onChange={(e) =>
setForm({
...form,
maxTestPredictionsPerWindow: Math.max(0, Number(e.target.value) || 0),
})
}
helperText={t('admin.testWallet.maxTestPredictionsHelper')}
fullWidth
disabled={!(form.predictionLimitEnabled ?? false)}
/>
<TextField
label={t('admin.testWallet.windowHours')}
type="number"
value={form.testPredictionWindowHours ?? 24}
onChange={(e) =>
setForm({
...form,
testPredictionWindowHours: Math.max(1, Number(e.target.value) || 1),
})
}
helperText={t('admin.testWallet.windowHoursHelper')}
fullWidth
disabled={!(form.predictionLimitEnabled ?? false)}
/>
{saveMut.isError && (
<Alert severity="error">
{(saveMut.error as { response?: { data?: { error?: string } } })?.response?.data

View File

@ -21,6 +21,17 @@ import type { BalanceEntry } from '../types';
import { USDT_WALLET_CODE } from '../utils/walletCapabilities';
import { formatBalance, rawToHuman } from '../utils/walletFormat';
type TestPredictionLimit = {
enabled: boolean;
maxPerWindow: number;
windowHours: number;
usedInWindow: number;
remaining: number;
resetsAt: string | null;
canPredict: boolean;
reason: string | null;
};
type TestWalletStatus = {
enabled: boolean;
balanceRaw: string;
@ -33,8 +44,26 @@ type TestWalletStatus = {
canRequest: boolean;
reason: string | null;
cooldownEndsAt: string | null;
predictionLimit?: TestPredictionLimit;
};
function formatWaitUntil(resetsAt: string | null, windowHours: number): string {
if (resetsAt) {
const ms = Math.max(0, new Date(resetsAt).getTime() - Date.now());
const totalMinutes = Math.max(1, Math.ceil(ms / 60_000));
const days = Math.floor(totalMinutes / (60 * 24));
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
const minutes = totalMinutes % 60;
const parts: string[] = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0 && days === 0) parts.push(`${minutes}m`);
if (parts.length === 0) parts.push('1m');
return parts.join(' ');
}
return `${windowHours}h`;
}
type TestWalletCardProps = {
balance: BalanceEntry;
onSuccess?: (message: string) => void;
@ -171,6 +200,36 @@ export function TestWalletCard({ balance, onSuccess, onError }: TestWalletCardPr
{t('wallet.testCard.disabled')}
</Alert>
)}
{status?.predictionLimit?.enabled && status.predictionLimit.maxPerWindow > 0 && (
<Stack spacing={1} sx={{ mt: 2 }}>
<Typography variant="caption" sx={{ opacity: 0.65 }}>
{t('wallet.testCard.predictionsUsed', {
used: status.predictionLimit.usedInWindow,
max: status.predictionLimit.maxPerWindow,
hours: status.predictionLimit.windowHours,
})}
</Typography>
{!status.predictionLimit.canPredict && (
<Alert severity="warning" variant="outlined" sx={{ borderRadius: 2 }}>
{t('wallet.testCard.predictionLimitReached', {
wait: formatWaitUntil(
status.predictionLimit.resetsAt,
status.predictionLimit.windowHours
),
})}
{status.predictionLimit.resetsAt && (
<>
{' '}
{t('wallet.testCard.resetsAt', {
date: new Date(status.predictionLimit.resetsAt).toLocaleString(),
})}
</>
)}
</Alert>
)}
</Stack>
)}
</CardContent>
</Card>
);

View File

@ -379,6 +379,10 @@ export const en = {
requestsUsed: 'Requests used: {{used}} / {{max}}',
availableAfter: 'Available after {{date}}.',
disabled: 'Test wallet requests are currently disabled by the platform.',
predictionsUsed: 'Test predictions used: {{used}} / {{max}} (per {{hours}}h)',
predictionLimitReached:
'You have reached the maximum number of Test Wallet uses allowed. Please try again in {{wait}}.',
resetsAt: 'Resets at {{date}}.',
},
transactions: {
empty: {
@ -1732,6 +1736,14 @@ export const en = {
maxRequestsHelper: '0 = unlimited',
cooldown: 'Cooldown between requests (hours)',
cooldownHelper: '0 = no waiting period',
predictionLimitTitle: 'Test prediction usage limit',
predictionLimitSubtitle:
'Limit how many Test Wallet predictions each user can place in a rolling time window.',
predictionLimitEnabled: 'Enable Test Wallet prediction limit',
maxTestPredictions: 'Max Test predictions per window',
maxTestPredictionsHelper: '0 = unlimited (even when the limit feature is on)',
windowHours: 'Reset window (hours)',
windowHoursHelper: 'e.g. 12, 24, or 168 (7 days). Oldest use falls out of the window automatically.',
saveFailed: 'Save failed',
saved: 'Settings saved.',
save: 'Save settings',

View File

@ -387,6 +387,10 @@ export const fr = {
requestsUsed: 'Demandes utilisées : {{used}} / {{max}}',
availableAfter: 'Disponible après {{date}}.',
disabled: 'Les demandes de portefeuille test sont actuellement désactivées par la plateforme.',
predictionsUsed: 'Prédictions Test utilisées : {{used}} / {{max}} (par {{hours}}h)',
predictionLimitReached:
'Vous avez atteint le nombre maximal d’utilisations autorisées du compte Test. Veuillez réessayer dans {{wait}}.',
resetsAt: 'Réinitialisation à {{date}}.',
},
transactions: {
empty: {
@ -1748,6 +1752,14 @@ export const fr = {
maxRequestsHelper: '0 = illimité',
cooldown: 'Délai entre demandes (heures)',
cooldownHelper: '0 = pas d’attente',
predictionLimitTitle: 'Limite d’utilisation des prédictions Test',
predictionLimitSubtitle:
'Limitez le nombre de prédictions avec le portefeuille Test par utilisateur sur une fenêtre glissante.',
predictionLimitEnabled: 'Activer la limite de prédictions Test',
maxTestPredictions: 'Prédictions Test max par fenêtre',
maxTestPredictionsHelper: '0 = illimité (même si la limite est activée)',
windowHours: 'Fenêtre de réinitialisation (heures)',
windowHoursHelper: 'ex. 12, 24 ou 168 (7 jours). Les utilisations les plus anciennes sortent automatiquement de la fenêtre.',
saveFailed: 'Échec de l’enregistrement',
saved: 'Paramètres enregistrés.',
save: 'Enregistrer les paramètres',

View File

@ -38,7 +38,13 @@ export function apiErrorMessage(error: unknown, fallback?: string): string {
return serviceUnavailable;
}
const data = error.response.data as { error?: unknown; message?: unknown } | undefined;
const data = error.response.data as
| { error?: unknown; message?: unknown; code?: unknown; wait?: unknown }
| undefined;
if (data?.code === 'TEST_PREDICTION_LIMIT') {
const wait = typeof data.wait === 'string' && data.wait.trim() ? data.wait : '24h';
return i18n.t('wallet.testCard.predictionLimitReached', { wait });
}
const apiMsg = data?.error ?? data?.message;
if (typeof apiMsg === 'string' && apiMsg.trim()) {
return sanitizeApiText(apiMsg, fb);