After correcting the issue for bonus fund credit for BEP201

This commit is contained in:
Your Name 2026-10-29 13:51:03 +02:00
parent ad17999faf
commit ba47a99134
8 changed files with 137 additions and 139 deletions

View File

@ -103,8 +103,11 @@ export async function updateAdminReferralSettings(req: AuthRequest, res: Respons
withdrawalCommissionsEnabled?: boolean;
predictionCommissionsEnabled?: boolean;
minFirstDepositRaw?: string;
/** Ignored — commission wallet is always the USDT_TRC20 ledger. */
commissionWalletTypeId?: number;
};
const { walletTypeId: commissionWalletTypeId } =
await bonusPoolRepository.lockCommissionLedgerPool();
await referralRepository.updateSettings({
enabled: body.enabled,
defaultReferrerUserId: body.defaultReferrerUserId,
@ -126,11 +129,8 @@ export async function updateAdminReferralSettings(req: AuthRequest, res: Respons
withdrawalCommissionsEnabled: body.withdrawalCommissionsEnabled,
predictionCommissionsEnabled: body.predictionCommissionsEnabled,
minFirstDepositRaw: body.minFirstDepositRaw,
commissionWalletTypeId: body.commissionWalletTypeId,
commissionWalletTypeId,
});
if (body.commissionWalletTypeId != null) {
await bonusPoolRepository.ensurePool(body.commissionWalletTypeId);
}
const config = await referralService.getProgramSettingsForAdmin();
res.json(config);
} catch (e) {
@ -195,9 +195,9 @@ export async function getReferralStats(_req: AuthRequest, res: Response): Promis
export async function fundBonusPool(req: AuthRequest, res: Response): Promise<void> {
try {
const { walletTypeId, amountRaw } = req.body as { walletTypeId?: number; amountRaw?: string };
if (!walletTypeId || !amountRaw) {
res.status(400).json({ error: 'walletTypeId and amountRaw are required' });
const { amountRaw } = req.body as { walletTypeId?: number; amountRaw?: string };
if (!amountRaw) {
res.status(400).json({ error: 'amountRaw is required' });
return;
}
const amount = BigInt(amountRaw);
@ -206,18 +206,9 @@ export async function fundBonusPool(req: AuthRequest, res: Response): Promise<vo
return;
}
// Commissions debit the commission wallet pool only (unified USDT ledger = USDT_TRC20).
// Custody rails (e.g. USDT_BEP20) must not be fundable here — there is no pool row for them.
const settings = await referralRepository.getSettings();
if (walletTypeId !== settings.commission_wallet_type_id) {
res.status(400).json({
error:
'Bonus pool can only be funded for the referral commission wallet type (USDT ledger). ' +
'BEP20/TRC20 deposit rails are not separate bonus pools.',
});
return;
}
await bonusPoolRepository.ensurePool(walletTypeId);
// Always fund the single USDT_TRC20 ledger pool (ignore any client walletTypeId).
const { walletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
await referralRepository.updateSettings({ commissionWalletTypeId: walletTypeId });
const { createFundRequest } = await import('../services/fundApprovalService');
const result = await createFundRequest({

View File

@ -1112,6 +1112,16 @@ INSERT INTO platform_bonus_pools (wallet_type_id)
SELECT id FROM wallet_types WHERE code = 'USDT_TRC20'
ON CONFLICT DO NOTHING;
-- Referral commissions use a single ledger pool (USDT_TRC20). Drop stray custody-rail pools.
DELETE FROM platform_bonus_pools p
USING wallet_types wt
WHERE p.wallet_type_id = wt.id AND wt.code <> 'USDT_TRC20';
UPDATE referral_program_settings
SET commission_wallet_type_id = wt.id
FROM wallet_types wt
WHERE referral_program_settings.id = 1 AND wt.code = 'USDT_TRC20';
-- Extend exchange_funding for cold ↔ hot treasury moves (manual confirm workflow)
DO $$
BEGIN

View File

@ -1,5 +1,8 @@
import { query, getClient, beginAuthorizedTransaction } from '../db/connection';
/** Unified spendable USDT ledger code — sole referral commission / bonus pool wallet. */
const COMMISSION_LEDGER_CODE = 'USDT_TRC20';
export async function getPoolBalance(walletTypeId: number): Promise<string> {
const rows = await query<{ available_balance: string }[]>(
'SELECT available_balance::text FROM platform_bonus_pools WHERE wallet_type_id = $1',
@ -14,6 +17,20 @@ export async function listPools(): Promise<Array<{ wallet_type_id: number; avail
);
}
/** Single fundable pool = unified USDT ledger (USDT_TRC20). */
export async function listCommissionPools(): Promise<
Array<{ wallet_type_id: number; available_balance: string }>
> {
return query(
`SELECT p.wallet_type_id, p.available_balance::text
FROM platform_bonus_pools p
INNER JOIN wallet_types wt ON wt.id = p.wallet_type_id
WHERE wt.code = $1
ORDER BY p.wallet_type_id`,
[COMMISSION_LEDGER_CODE]
);
}
export async function hasPool(walletTypeId: number): Promise<boolean> {
const rows = await query<{ wallet_type_id: number }[]>(
'SELECT wallet_type_id FROM platform_bonus_pools WHERE wallet_type_id = $1',
@ -32,6 +49,29 @@ export async function ensurePool(walletTypeId: number): Promise<void> {
);
}
/**
* Resolve the fixed commission ledger wallet (USDT_TRC20), ensure its pool exists,
* and drop stray pools for custody rails (e.g. USDT_BEP20) so only one pool remains.
*/
export async function lockCommissionLedgerPool(): Promise<{ walletTypeId: number }> {
const rows = await query<{ id: number }[]>(
'SELECT id FROM wallet_types WHERE code = $1 LIMIT 1',
[COMMISSION_LEDGER_CODE]
);
const walletTypeId = rows[0]?.id;
if (!walletTypeId) {
throw new Error('USDT_TRC20 wallet type not configured — cannot lock referral commission pool');
}
await ensurePool(walletTypeId);
await query(
`DELETE FROM platform_bonus_pools p
USING wallet_types wt
WHERE p.wallet_type_id = wt.id AND wt.code <> $1`,
[COMMISSION_LEDGER_CODE]
);
return { walletTypeId };
}
/** Admin funds the platform bonus pool (off-chain treasury allocation). */
export async function fundPool(walletTypeId: number, amount: bigint): Promise<void> {
const client = await getClient();

View File

@ -208,23 +208,17 @@ export async function executeApprovedRequest(
});
}
case 'bonus_pool_fund': {
const { walletTypeId, amountRaw } = request.payload as {
walletTypeId: number;
const { amountRaw } = request.payload as {
walletTypeId?: number;
amountRaw: string;
};
const amount = BigInt(amountRaw);
const settings = await (
await import('../repositories/referralRepository')
).getSettings();
if (walletTypeId !== settings.commission_wallet_type_id) {
throw new Error(
'Bonus pool fund must target the referral commission wallet type (USDT ledger). ' +
'Reject this request and re-fund using USDT_TRC20 — custody rails like USDT_BEP20 have no bonus pool.'
);
}
await bonusPoolRepository.ensurePool(walletTypeId);
// Always credit the locked USDT_TRC20 ledger pool (ignore payload walletTypeId).
const { walletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
const referralRepository = await import('../repositories/referralRepository');
await referralRepository.updateSettings({ commissionWalletTypeId: walletTypeId });
await bonusPoolRepository.fundPool(walletTypeId, amount);
const pools = await bonusPoolRepository.listPools();
const pools = await bonusPoolRepository.listCommissionPools();
return { message: 'Pool funded', pools };
}
case 'sweep_manual': {

View File

@ -1521,13 +1521,20 @@ export async function getUserReferralInfo(userId: string): Promise<{
}
export async function getProgramSettingsForAdmin() {
const settings = await referralRepository.getSettings();
// Hard-lock: one commission wallet + one bonus pool = unified USDT ledger (USDT_TRC20).
const { walletTypeId: commissionWalletTypeId } = await bonusPoolRepository.lockCommissionLedgerPool();
let settings = await referralRepository.getSettings();
if (settings.commission_wallet_type_id !== commissionWalletTypeId) {
settings = await referralRepository.updateSettings({ commissionWalletTypeId });
}
const levels = await referralRepository.listLevels();
const [pools, walletTypes] = await Promise.all([
bonusPoolRepository.listPools(),
bonusPoolRepository.listCommissionPools(),
walletRepository.getWalletTypes(),
]);
const walletTypeById = new Map(walletTypes.map((wt) => [wt.id, wt]));
const ledgerWt = walletTypeById.get(commissionWalletTypeId);
const formatWalletLabel = (wt: { code: string; name: string; network: string }) =>
`${wt.name} (${wt.code}${wt.network ? ` · ${wt.network}` : ''})`;
@ -1554,7 +1561,11 @@ export async function getProgramSettingsForAdmin() {
withdrawalCommissionsEnabled: settings.withdrawal_commissions_enabled,
predictionCommissionsEnabled: settings.prediction_commissions_enabled,
minFirstDepositRaw: settings.min_first_deposit_raw,
commissionWalletTypeId: settings.commission_wallet_type_id,
commissionWalletTypeId,
commissionWalletCode: ledgerWt?.code ?? 'USDT_TRC20',
commissionWalletLabel: ledgerWt
? formatWalletLabel(ledgerWt)
: 'USDT (TRC20) · unified ledger',
updatedAt: settings.updated_at,
},
levels: levels.map((l) => ({
@ -1564,13 +1575,18 @@ export async function getProgramSettingsForAdmin() {
monthlyMaxAmountRaw: l.monthly_max_amount_raw,
monthlyMaxCount: l.monthly_max_count,
})),
walletTypes: walletTypes.map((wt) => ({
id: wt.id,
code: wt.code,
name: wt.name,
network: wt.network,
label: formatWalletLabel(wt),
})),
/** @deprecated Kept for older clients — always the single ledger type. */
walletTypes: ledgerWt
? [
{
id: ledgerWt.id,
code: ledgerWt.code,
name: ledgerWt.name,
network: ledgerWt.network,
label: formatWalletLabel(ledgerWt),
},
]
: [],
pools: pools.map((p) => {
const wt = walletTypeById.get(p.wallet_type_id);
return {

View File

@ -8,11 +8,7 @@ import {
Card,
CardContent,
Chip,
FormControl,
FormControlLabel,
InputLabel,
MenuItem,
Select,
Stack,
Switch,
Table,
@ -26,7 +22,7 @@ import {
import GroupAddRoundedIcon from '@mui/icons-material/GroupAddRounded';
import { Link as RouterLink } from 'react-router-dom';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { api } from '../../shared/services/api';
import { ScrollableTable } from '../../shared/components/ScrollableTable';
@ -41,14 +37,6 @@ function formatUsdtRaw(raw: string | number | null | undefined): string {
return `${rawToHuman(value, USDT_DECIMALS)} USDT`;
}
type WalletTypeOption = {
id: number;
code: string;
name: string;
network: string;
label: string;
};
type ReferralConfig = {
settings: {
enabled: boolean;
@ -72,6 +60,8 @@ type ReferralConfig = {
predictionCommissionsEnabled: boolean;
minFirstDepositRaw: string;
commissionWalletTypeId: number;
commissionWalletCode?: string;
commissionWalletLabel?: string;
};
levels: Array<{
levelNumber: number;
@ -80,7 +70,13 @@ type ReferralConfig = {
monthlyMaxAmountRaw: string;
monthlyMaxCount: number;
}>;
walletTypes: WalletTypeOption[];
walletTypes: Array<{
id: number;
code: string;
name: string;
network: string;
label: string;
}>;
pools: Array<{
walletTypeId: number;
availableBalance: string;
@ -131,7 +127,7 @@ export function ReferralAdminPage() {
monthlyMaxAmountRaw: '0',
monthlyMaxCount: '0',
});
const [fundForm, setFundForm] = useState({ walletTypeId: '', amountDisplay: '' });
const [fundForm, setFundForm] = useState({ amountDisplay: '' });
const [settingsForm, setSettingsForm] = useState<ReferralConfig['settings'] | null>(null);
const [rejectReasons, setRejectReasons] = useState<Record<string, string>>({});
const [fundPendingMsg, setFundPendingMsg] = useState<string | null>(null);
@ -145,25 +141,6 @@ export function ReferralAdminPage() {
},
});
useEffect(() => {
if (!configQ.data) return;
setFundForm((f) => {
const cfg = configQ.data;
const allowedIds = new Set(
(cfg.pools.length ? cfg.pools.map((p) => p.walletTypeId) : [cfg.settings.commissionWalletTypeId]).filter(
Boolean
)
);
const currentOk = f.walletTypeId && allowedIds.has(Number(f.walletTypeId));
if (currentOk) return f;
const preferred =
cfg.settings.commissionWalletTypeId ||
cfg.pools[0]?.walletTypeId ||
[...allowedIds][0];
return preferred ? { ...f, walletTypeId: String(preferred) } : f;
});
}, [configQ.data]);
const statsQ = useQuery({
queryKey: ['admin-referral-stats'],
queryFn: async () => {
@ -261,7 +238,6 @@ export function ReferralAdminPage() {
const frac = (parts[1] ?? '').padEnd(decimals, '0').slice(0, decimals);
const amountRaw = (BigInt(whole) * 10n ** 6n + BigInt(frac || '0')).toString();
return api.post<{ message?: string }>('/api/v1/admin/referral/pool/fund', {
walletTypeId: Number(fundForm.walletTypeId),
amountRaw,
});
},
@ -276,7 +252,7 @@ export function ReferralAdminPage() {
const config = configQ.data;
const stats = statsQ.data;
const s = settingsForm ?? config?.settings;
const walletTypeOptions = config?.walletTypes ?? [];
const commissionPool = config?.pools?.[0] ?? null;
const predictionOn = Boolean(s?.predictionCommissionsEnabled);
const depositOn = Boolean(s?.depositCommissionsEnabled);
const withdrawalOn = Boolean(s?.withdrawalCommissionsEnabled);
@ -739,27 +715,15 @@ export function ReferralAdminPage() {
helperText={t('admin.referralAdmin.defaultReferrerHelper')}
/>
{showModeConfig && (
<FormControl fullWidth>
<InputLabel id="commission-wallet-type-label">
<Box>
<Typography variant="subtitle2" sx={{ fontWeight: 700 }}>
{t('admin.referralAdmin.commissionWalletType')}
</InputLabel>
<Select
labelId="commission-wallet-type-label"
label={t('admin.referralAdmin.commissionWalletType')}
value={s.commissionWalletTypeId || ''}
onChange={(e) =>
setSettingsForm({
...s,
commissionWalletTypeId: Number(e.target.value),
})
}
>
{walletTypeOptions.map((wt) => (
<MenuItem key={wt.id} value={wt.id}>
{wt.label}
</MenuItem>
))}
</Select>
</Typography>
<Typography variant="body2" sx={{ mt: 0.5 }}>
{s.commissionWalletLabel ??
config?.settings.commissionWalletLabel ??
'USDT (TRC20) · unified ledger'}
</Typography>
<Typography
variant="caption"
color="text.secondary"
@ -767,7 +731,7 @@ export function ReferralAdminPage() {
>
{t('admin.referralAdmin.commissionWalletHelper')}
</Typography>
</FormControl>
</Box>
)}
</>
)}
@ -906,19 +870,22 @@ export function ReferralAdminPage() {
{showModeConfig && (
<Card sx={{ borderRadius: 2, mb: 2 }}>
<CardContent>
<Typography variant="h6" sx={{ fontWeight: 800, mb: 2 }}>
<Typography variant="h6" sx={{ fontWeight: 800, mb: 1 }}>
{t('admin.referralAdmin.bonusPoolTitle')}
</Typography>
<Stack spacing={1} sx={{ mb: 2 }}>
{(config?.pools ?? []).map((p) => (
<Typography key={p.walletTypeId} variant="body2">
{t('admin.referralAdmin.walletTypeBalance', {
label: p.label,
amount: formatUsdtRaw(p.availableBalance),
})}
</Typography>
))}
</Stack>
<Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
{t('admin.referralAdmin.bonusPoolHelper')}
</Typography>
<Typography variant="body2" sx={{ mb: 2 }}>
{t('admin.referralAdmin.walletTypeBalance', {
label:
commissionPool?.label ??
s?.commissionWalletLabel ??
config?.settings.commissionWalletLabel ??
'USDT (TRC20)',
amount: formatUsdtRaw(commissionPool?.availableBalance ?? '0'),
})}
</Typography>
<Stack
direction={{ xs: 'column', sm: 'row' }}
spacing={1}
@ -926,32 +893,6 @@ export function ReferralAdminPage() {
disabled={!canManageReferral}
sx={{ alignItems: { sm: 'flex-start' }, border: 0, m: 0, p: 0, minWidth: 0 }}
>
<FormControl sx={{ flex: 1, minWidth: 220 }}>
<InputLabel id="fund-wallet-type-label">
{t('admin.referralAdmin.walletType')}
</InputLabel>
<Select
labelId="fund-wallet-type-label"
label={t('admin.referralAdmin.walletType')}
value={fundForm.walletTypeId}
onChange={(e) => setFundForm((f) => ({ ...f, walletTypeId: String(e.target.value) }))}
>
{/* Only pool rows (commission ledger) — not custody rails like BEP20 */}
{(config?.pools?.length
? config.pools.map((p) => ({
id: p.walletTypeId,
label: p.label,
}))
: walletTypeOptions
.filter((wt) => wt.id === config?.settings.commissionWalletTypeId)
.map((wt) => ({ id: wt.id, label: wt.label }))
).map((wt) => (
<MenuItem key={wt.id} value={String(wt.id)}>
{wt.label}
</MenuItem>
))}
</Select>
</FormControl>
<TextField
label={t('admin.referralAdmin.amountDisplay')}
value={fundForm.amountDisplay}
@ -962,7 +903,7 @@ export function ReferralAdminPage() {
<Button
variant="contained"
onClick={() => fundMut.mutate()}
disabled={fundMut.isPending || !fundForm.walletTypeId}
disabled={fundMut.isPending || !fundForm.amountDisplay.trim()}
sx={{ whiteSpace: 'nowrap' }}
>
{t('admin.referralAdmin.fundPool')}

View File

@ -2354,7 +2354,8 @@ export const en = {
defaultReferrerHelper: 'Used when no referral code is provided at signup',
minFirstDeposit: 'Min first deposit (raw units)',
commissionWalletType: 'Commission wallet',
commissionWalletHelper: 'Asset used for referral commission credits (e.g. USDT TRC20)',
commissionWalletHelper:
'Fixed to the unified USDT ledger (USDT_TRC20). Deposit/withdraw rails like BEP20 are separate and cannot be selected.',
saveSettings: 'Save settings',
levelsTitle: 'Commission levels',
level: 'Level',
@ -2371,6 +2372,8 @@ export const en = {
maxCountField: 'Max count / month (0=global)',
addUpdateLevel: 'Add / update level',
bonusPoolTitle: 'Bonus pool (treasury for referral payouts)',
bonusPoolHelper:
'One pool only — the USDT_TRC20 ledger. This is internal accounting, not an on-chain Tron treasury.',
walletTypeBalance: '{{label}}: {{amount}}',
walletTypeId: 'Wallet type ID',
walletType: 'Wallet',

View File

@ -2377,7 +2377,8 @@ export const fr = {
defaultReferrerHelper: 'Utilisé quand aucun code parrain n’est fourni à l’inscription',
minFirstDeposit: 'Premier dépôt min (unités brutes)',
commissionWalletType: 'Wallet de commission',
commissionWalletHelper: 'Actif utilisé pour créditer les commissions (ex. USDT TRC20)',
commissionWalletHelper:
'Fixé sur le ledger USDT unifié (USDT_TRC20). Les rails dépôt/retrait comme BEP20 sont séparés et ne peuvent pas être choisis.',
saveSettings: 'Enregistrer les paramètres',
levelsTitle: 'Niveaux de commission',
level: 'Niveau',
@ -2394,6 +2395,8 @@ export const fr = {
maxCountField: 'Nombre max / mois (0=global)',
addUpdateLevel: 'Ajouter / mettre à jour le niveau',
bonusPoolTitle: 'Pool bonus (trésorerie pour paiements parrainage)',
bonusPoolHelper:
'Un seul pool — le ledger USDT_TRC20. Comptabilité interne, pas une trésorerie Tron on-chain.',
walletTypeBalance: '{{label}} : {{amount}}',
walletTypeId: 'ID type wallet',
walletType: 'Wallet',