After adding the BSC option4
This commit is contained in:
parent
90842c0b74
commit
d8f94f8650
@ -207,6 +207,17 @@ CREATE INDEX IF NOT EXISTS idx_user_wallets_user ON user_wallets(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_wallets_address ON user_wallets(address);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_wallets_type ON user_wallets(wallet_type_id);
|
||||
|
||||
-- Per-network deposit inventory (ops telemetry; micro-USDT 6 decimals). Not a withdrawal cap.
|
||||
CREATE TABLE IF NOT EXISTS user_network_inventory (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
network VARCHAR(16) NOT NULL CHECK (network IN ('TRON', 'BSC')),
|
||||
amount BIGINT NOT NULL DEFAULT 0 CHECK (amount >= 0),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
PRIMARY KEY (user_id, network)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_user_network_inventory_user ON user_network_inventory(user_id);
|
||||
|
||||
-- Hot wallet addresses (platform signs withdrawals from these)
|
||||
CREATE TABLE IF NOT EXISTS hot_wallets (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
|
||||
90
backend/src/repositories/networkInventoryRepository.ts
Normal file
90
backend/src/repositories/networkInventoryRepository.ts
Normal file
@ -0,0 +1,90 @@
|
||||
/**
|
||||
* Per-network USDT deposit inventory (ops telemetry; not a withdrawal cap).
|
||||
*/
|
||||
|
||||
import { PoolClient } from 'pg';
|
||||
import { query } from '../db/connection';
|
||||
import type { CustodyNetwork } from '../utils/usdtUnits';
|
||||
|
||||
export async function getAmount(userId: string, network: CustodyNetwork): Promise<bigint> {
|
||||
const rows = await query<{ amount: string }[]>(
|
||||
`SELECT amount::text AS amount FROM user_network_inventory WHERE user_id = $1 AND network = $2`,
|
||||
[userId, network]
|
||||
);
|
||||
return BigInt(rows[0]?.amount ?? '0');
|
||||
}
|
||||
|
||||
export async function getAllForUser(userId: string): Promise<{ TRON: bigint; BSC: bigint }> {
|
||||
const rows = await query<{ network: CustodyNetwork; amount: string }[]>(
|
||||
`SELECT network, amount::text AS amount FROM user_network_inventory WHERE user_id = $1`,
|
||||
[userId]
|
||||
);
|
||||
const out = { TRON: 0n, BSC: 0n };
|
||||
for (const row of rows) {
|
||||
if (row.network === 'TRON' || row.network === 'BSC') {
|
||||
out[row.network] = BigInt(row.amount);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Credit inventory inside an open DB transaction. */
|
||||
export async function creditUsingClient(
|
||||
client: PoolClient,
|
||||
userId: string,
|
||||
network: CustodyNetwork,
|
||||
amount: bigint
|
||||
): Promise<void> {
|
||||
if (amount <= 0n) return;
|
||||
await client.query(
|
||||
`INSERT INTO user_network_inventory (user_id, network, amount, updated_at)
|
||||
VALUES ($1, $2, $3, NOW())
|
||||
ON CONFLICT (user_id, network) DO UPDATE
|
||||
SET amount = user_network_inventory.amount + EXCLUDED.amount,
|
||||
updated_at = NOW()`,
|
||||
[userId, network, amount.toString()]
|
||||
);
|
||||
}
|
||||
|
||||
/** Debit inventory inside an open DB transaction; throws if insufficient. */
|
||||
export async function debitUsingClient(
|
||||
client: PoolClient,
|
||||
userId: string,
|
||||
network: CustodyNetwork,
|
||||
amount: bigint
|
||||
): Promise<void> {
|
||||
if (amount <= 0n) return;
|
||||
const res = await client.query(
|
||||
`UPDATE user_network_inventory
|
||||
SET amount = amount - $3, updated_at = NOW()
|
||||
WHERE user_id = $1 AND network = $2 AND amount >= $3
|
||||
RETURNING amount`,
|
||||
[userId, network, amount.toString()]
|
||||
);
|
||||
if (res.rowCount === 0) {
|
||||
const err = new Error(`Insufficient ${network} network inventory for withdrawal`) as Error & {
|
||||
code?: string;
|
||||
};
|
||||
err.code = 'INSUFFICIENT_NETWORK_INVENTORY';
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Debit inventory (own connection). */
|
||||
export async function debit(userId: string, network: CustodyNetwork, amount: bigint): Promise<void> {
|
||||
if (amount <= 0n) return;
|
||||
const rows = await query<{ amount: string }[]>(
|
||||
`UPDATE user_network_inventory
|
||||
SET amount = amount - $3, updated_at = NOW()
|
||||
WHERE user_id = $1 AND network = $2 AND amount >= $3
|
||||
RETURNING amount::text AS amount`,
|
||||
[userId, network, amount.toString()]
|
||||
);
|
||||
if (rows.length === 0) {
|
||||
const err = new Error(`Insufficient ${network} network inventory for withdrawal`) as Error & {
|
||||
code?: string;
|
||||
};
|
||||
err.code = 'INSUFFICIENT_NETWORK_INVENTORY';
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@ -93,14 +93,15 @@ export async function insertDepositIfNew(
|
||||
toAddress: string;
|
||||
confirmations: number;
|
||||
requiredConfirmations: number;
|
||||
metadata?: Record<string, unknown> | null;
|
||||
}
|
||||
): Promise<Transaction | null> {
|
||||
const res = await client.query<Transaction>(
|
||||
`INSERT INTO transactions (
|
||||
user_id, wallet_type_id, type, amount, fee, status,
|
||||
blockchain_tx_id, from_address, to_address, confirmations, required_confirmations
|
||||
blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata
|
||||
)
|
||||
VALUES ($1, $2, 'deposit', $3, 0, 'completed', $4, $5, $6, $7, $8)
|
||||
VALUES ($1, $2, 'deposit', $3, 0, 'completed', $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (blockchain_tx_id) WHERE blockchain_tx_id IS NOT NULL
|
||||
DO NOTHING
|
||||
RETURNING id, user_id, wallet_type_id, type, amount::text, fee::text, status,
|
||||
@ -115,6 +116,7 @@ export async function insertDepositIfNew(
|
||||
data.toAddress,
|
||||
data.confirmations,
|
||||
data.requiredConfirmations,
|
||||
data.metadata ? JSON.stringify(data.metadata) : null,
|
||||
]
|
||||
);
|
||||
return res.rows[0] ?? null;
|
||||
|
||||
@ -548,6 +548,15 @@ export async function getUserDetails(userId: string): Promise<{
|
||||
available: string;
|
||||
locked: string;
|
||||
}>;
|
||||
inventory: { TRON: string; BSC: string };
|
||||
networks: Array<{
|
||||
code: string;
|
||||
network: string;
|
||||
depositEnabled: boolean;
|
||||
withdrawEnabled: boolean;
|
||||
inventory: string;
|
||||
withdrawable: string;
|
||||
}>;
|
||||
}> {
|
||||
const row = await userRepository.getForAdmin(userId);
|
||||
if (!row) {
|
||||
@ -572,12 +581,14 @@ export async function getUserDetails(userId: string): Promise<{
|
||||
security_suspended_at: row.security_suspended_at,
|
||||
created_at: row.created_at,
|
||||
},
|
||||
balances: balances.map((b) => ({
|
||||
balances: balances.balances.map((b) => ({
|
||||
wallet_type: b.walletType.code,
|
||||
wallet_name: b.walletType.name,
|
||||
available: b.available,
|
||||
locked: b.locked,
|
||||
})),
|
||||
inventory: balances.inventory,
|
||||
networks: balances.networks,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
/**
|
||||
* Deposit scanner and crediting service.
|
||||
* Polls TRON for incoming USDT (TRC20) transfers and credits user ledger accounts.
|
||||
* Credits a unified USDT ledger (USDT_TRC20, 6 decimals) and per-network inventory.
|
||||
* Custody scans remain on TRON (TRC20) and BSC (BEP20) deposit addresses.
|
||||
*/
|
||||
|
||||
import { config } from '../config';
|
||||
@ -9,6 +10,7 @@ import * as walletRepository from '../repositories/walletRepository';
|
||||
import * as ledgerRepository from '../repositories/ledgerRepository';
|
||||
import * as transactionRepository from '../repositories/transactionRepository';
|
||||
import * as depositScannerRepository from '../repositories/depositScannerRepository';
|
||||
import * as networkInventoryRepository from '../repositories/networkInventoryRepository';
|
||||
import * as auditLogRepository from '../repositories/auditLogRepository';
|
||||
import { enqueueSweepAfterDeposit } from './sweepService';
|
||||
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
|
||||
@ -17,6 +19,12 @@ import { USDT_BEP20_CODE, USDT_TRC20_CODE } from './walletCapabilities';
|
||||
import * as tronService from './blockchain/tronService';
|
||||
import * as bscService from './blockchain/bscService';
|
||||
import * as settingsRepository from '../repositories/settingsRepository';
|
||||
import {
|
||||
BEP20_USDT_DECIMALS,
|
||||
LEDGER_USDT_DECIMALS,
|
||||
scaleChainToLedger,
|
||||
type CustodyNetwork,
|
||||
} from '../utils/usdtUnits';
|
||||
|
||||
const TRON_CONFIRMATIONS = config.blockchain.tron.confirmations;
|
||||
const BSC_CONFIRMATIONS = config.blockchain.bsc.confirmations;
|
||||
@ -32,11 +40,12 @@ export async function processTronDeposits(): Promise<void> {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
if (!settings.network_usdt_trc20_deposit_enabled) return;
|
||||
|
||||
const walletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
if (!walletType) return;
|
||||
const custodyType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
const ledgerType = custodyType;
|
||||
if (!custodyType || !ledgerType) return;
|
||||
|
||||
const currentBlock = await tronService.getCurrentBlock();
|
||||
const state = await depositScannerRepository.getState(walletType.id);
|
||||
const state = await depositScannerRepository.getState(custodyType.id);
|
||||
let fromBlock = state ? BigInt(state.last_block) + 1n : 0n;
|
||||
if (fromBlock > BigInt(currentBlock)) {
|
||||
fromBlock = 0n;
|
||||
@ -44,13 +53,13 @@ export async function processTronDeposits(): Promise<void> {
|
||||
|
||||
const userWallets = await query<Array<{ address: string; user_id: string; created_at: Date }>>(
|
||||
'SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1',
|
||||
[walletType.id]
|
||||
[custodyType.id]
|
||||
);
|
||||
|
||||
if (userWallets.length > 0) {
|
||||
const hasAnyUsdtDeposit = await query<{ n: string }[]>(
|
||||
`SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 AND type = 'deposit' LIMIT 1`,
|
||||
[walletType.id]
|
||||
[ledgerType.id]
|
||||
).then((r) => r.length > 0);
|
||||
if (!hasAnyUsdtDeposit && fromBlock > 0n) {
|
||||
fromBlock = 0n;
|
||||
@ -67,12 +76,12 @@ export async function processTronDeposits(): Promise<void> {
|
||||
}
|
||||
|
||||
const trc20Contract =
|
||||
config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || '';
|
||||
config.blockchain.tron.usdtTrc20Contract || custodyType.contract_address || '';
|
||||
if (!trc20Contract) return;
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(
|
||||
`[deposit] USDT_TRC20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
|
||||
`[deposit] USDT_TRC20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
|
||||
);
|
||||
}
|
||||
|
||||
@ -92,16 +101,20 @@ export async function processTronDeposits(): Promise<void> {
|
||||
if (amount == null) continue;
|
||||
if (t.confirmations >= TRON_CONFIRMATIONS) {
|
||||
try {
|
||||
await creditDeposit(
|
||||
user_id,
|
||||
walletType.id,
|
||||
amount,
|
||||
t.txId,
|
||||
t.from,
|
||||
address,
|
||||
t.confirmations,
|
||||
TRON_CONFIRMATIONS
|
||||
);
|
||||
await creditDeposit({
|
||||
userId: user_id,
|
||||
ledgerWalletTypeId: ledgerType.id,
|
||||
custodyWalletTypeId: custodyType.id,
|
||||
network: 'TRON',
|
||||
sourceWalletCode: USDT_TRC20_CODE,
|
||||
ledgerAmount: amount,
|
||||
chainAmount: amount,
|
||||
blockchainTxId: t.txId,
|
||||
fromAddress: t.from,
|
||||
toAddress: address,
|
||||
confirmations: t.confirmations,
|
||||
requiredConfirmations: TRON_CONFIRMATIONS,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(`[deposit] TRC20 credit failed tx=${t.txId}:`, e);
|
||||
}
|
||||
@ -109,41 +122,41 @@ export async function processTronDeposits(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
|
||||
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
|
||||
}
|
||||
|
||||
/** Scans BSC for new USDT BEP20 deposits and credits confirmed transfers. */
|
||||
/** Scans BSC for new USDT BEP20 deposits; credits unified ledger (6 dec) + BSC inventory. */
|
||||
export async function processBscDeposits(): Promise<void> {
|
||||
const settings = await settingsRepository.getSettings();
|
||||
if (!settings.network_usdt_bep20_deposit_enabled) return;
|
||||
|
||||
const walletType = await walletRepository.getWalletTypeByCode(USDT_BEP20_CODE);
|
||||
if (!walletType) return;
|
||||
const custodyType = await walletRepository.getWalletTypeByCode(USDT_BEP20_CODE);
|
||||
const ledgerType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
if (!custodyType || !ledgerType) return;
|
||||
|
||||
const currentBlock = await bscService.getCurrentBlock();
|
||||
const state = await depositScannerRepository.getState(walletType.id);
|
||||
const state = await depositScannerRepository.getState(custodyType.id);
|
||||
let fromBlock = state ? Number(state.last_block) + 1 : 0;
|
||||
if (fromBlock > currentBlock) fromBlock = 0;
|
||||
|
||||
const userWallets = await query<Array<{ address: string; user_id: string; created_at: Date }>>(
|
||||
'SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1',
|
||||
[walletType.id]
|
||||
[custodyType.id]
|
||||
);
|
||||
|
||||
if (userWallets.length === 0) {
|
||||
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
|
||||
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
|
||||
return;
|
||||
}
|
||||
|
||||
if (fromBlock === 0) {
|
||||
// Avoid full-chain scan: start a safe lookback window
|
||||
fromBlock = Math.max(0, currentBlock - 5_000);
|
||||
}
|
||||
|
||||
const contract = bscService.resolveUsdtContract(walletType.contract_address);
|
||||
const contract = bscService.resolveUsdtContract(custodyType.contract_address);
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(
|
||||
`[deposit] USDT_BEP20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
|
||||
`[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
|
||||
);
|
||||
}
|
||||
|
||||
@ -157,50 +170,70 @@ export async function processBscDeposits(): Promise<void> {
|
||||
for (const t of transfers) {
|
||||
const confirmations = currentBlock - t.blockNumber + 1;
|
||||
if (confirmations < BSC_CONFIRMATIONS) continue;
|
||||
const ledgerAmount = scaleChainToLedger(t.value, BEP20_USDT_DECIMALS, LEDGER_USDT_DECIMALS);
|
||||
if (ledgerAmount <= 0n) continue;
|
||||
try {
|
||||
await creditDeposit(
|
||||
user_id,
|
||||
walletType.id,
|
||||
t.value,
|
||||
t.txHash,
|
||||
t.from,
|
||||
address,
|
||||
await creditDeposit({
|
||||
userId: user_id,
|
||||
ledgerWalletTypeId: ledgerType.id,
|
||||
custodyWalletTypeId: custodyType.id,
|
||||
network: 'BSC',
|
||||
sourceWalletCode: USDT_BEP20_CODE,
|
||||
ledgerAmount,
|
||||
chainAmount: t.value,
|
||||
blockchainTxId: t.txHash,
|
||||
fromAddress: t.from,
|
||||
toAddress: address,
|
||||
confirmations,
|
||||
BSC_CONFIRMATIONS
|
||||
);
|
||||
requiredConfirmations: BSC_CONFIRMATIONS,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
|
||||
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
|
||||
}
|
||||
|
||||
async function creditDeposit(
|
||||
userId: string,
|
||||
walletTypeId: number,
|
||||
amount: bigint,
|
||||
blockchainTxId: string,
|
||||
fromAddress: string,
|
||||
toAddress: string,
|
||||
block: number,
|
||||
requiredConfirmations: number
|
||||
): Promise<void> {
|
||||
const account = await ledgerRepository.getOrCreateAccount(userId, walletTypeId, 'main');
|
||||
async function creditDeposit(opts: {
|
||||
userId: string;
|
||||
ledgerWalletTypeId: number;
|
||||
custodyWalletTypeId: number;
|
||||
network: CustodyNetwork;
|
||||
sourceWalletCode: string;
|
||||
ledgerAmount: bigint;
|
||||
chainAmount: bigint;
|
||||
blockchainTxId: string;
|
||||
fromAddress: string;
|
||||
toAddress: string;
|
||||
confirmations: number;
|
||||
requiredConfirmations: number;
|
||||
}): Promise<void> {
|
||||
const account = await ledgerRepository.getOrCreateAccount(
|
||||
opts.userId,
|
||||
opts.ledgerWalletTypeId,
|
||||
'main'
|
||||
);
|
||||
const client = await getClient();
|
||||
let tx: Awaited<ReturnType<typeof transactionRepository.insertDepositIfNew>> = null;
|
||||
try {
|
||||
await beginAuthorizedTransaction(client);
|
||||
tx = await transactionRepository.insertDepositIfNew(client, {
|
||||
userId,
|
||||
walletTypeId,
|
||||
amount,
|
||||
blockchainTxId,
|
||||
fromAddress,
|
||||
toAddress,
|
||||
confirmations: block,
|
||||
requiredConfirmations,
|
||||
userId: opts.userId,
|
||||
walletTypeId: opts.ledgerWalletTypeId,
|
||||
amount: opts.ledgerAmount,
|
||||
blockchainTxId: opts.blockchainTxId,
|
||||
fromAddress: opts.fromAddress,
|
||||
toAddress: opts.toAddress,
|
||||
confirmations: opts.confirmations,
|
||||
requiredConfirmations: opts.requiredConfirmations,
|
||||
metadata: {
|
||||
network: opts.network,
|
||||
source_wallet_type: opts.sourceWalletCode,
|
||||
chain_amount: opts.chainAmount.toString(),
|
||||
ledger_amount: opts.ledgerAmount.toString(),
|
||||
},
|
||||
});
|
||||
if (!tx) {
|
||||
await client.query('COMMIT');
|
||||
@ -209,11 +242,17 @@ async function creditDeposit(
|
||||
await ledgerRepository.creditUsingClient(
|
||||
client,
|
||||
account.id,
|
||||
amount,
|
||||
opts.ledgerAmount,
|
||||
'deposit',
|
||||
'transaction',
|
||||
tx.id
|
||||
);
|
||||
await networkInventoryRepository.creditUsingClient(
|
||||
client,
|
||||
opts.userId,
|
||||
opts.network,
|
||||
opts.ledgerAmount
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK');
|
||||
@ -225,18 +264,30 @@ async function creditDeposit(
|
||||
if (!tx) return;
|
||||
|
||||
await referralService.processFirstDepositReferralCommissions({
|
||||
userId,
|
||||
userId: opts.userId,
|
||||
depositTransactionId: tx.id,
|
||||
depositAmount: amount,
|
||||
walletTypeId,
|
||||
depositAmount: opts.ledgerAmount,
|
||||
walletTypeId: opts.ledgerWalletTypeId,
|
||||
});
|
||||
await auditLogRepository.create({
|
||||
userId,
|
||||
userId: opts.userId,
|
||||
action: 'deposit_confirmed',
|
||||
resourceType: 'transaction',
|
||||
resourceId: tx.id,
|
||||
metadata: { amount: amount.toString(), blockchainTxId },
|
||||
metadata: {
|
||||
amount: opts.ledgerAmount.toString(),
|
||||
chainAmount: opts.chainAmount.toString(),
|
||||
network: opts.network,
|
||||
sourceWalletType: opts.sourceWalletCode,
|
||||
blockchainTxId: opts.blockchainTxId,
|
||||
},
|
||||
});
|
||||
await enqueueSweepAfterDeposit(userId, walletTypeId, amount, tx.id);
|
||||
queueUserAdminStatsRefresh(userId);
|
||||
// Sweep uses custody type + on-chain amount
|
||||
await enqueueSweepAfterDeposit(
|
||||
opts.userId,
|
||||
opts.custodyWalletTypeId,
|
||||
opts.chainAmount,
|
||||
tx.id
|
||||
);
|
||||
queueUserAdminStatsRefresh(opts.userId);
|
||||
}
|
||||
|
||||
125
backend/src/services/hotLiquidityService.ts
Normal file
125
backend/src/services/hotLiquidityService.ts
Normal file
@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Pre-flight checks: platform hot wallet has enough USDT + native gas
|
||||
* to pay a withdrawal on the chosen rail (cross-network float model).
|
||||
*/
|
||||
|
||||
import { config } from '../config';
|
||||
import * as tronService from './blockchain/tronService';
|
||||
import * as bscService from './blockchain/bscService';
|
||||
import {
|
||||
BEP20_USDT_DECIMALS,
|
||||
scaleLedgerToChain,
|
||||
} from '../utils/usdtUnits';
|
||||
|
||||
/** ~3 TRX — enough for a typical TRC20 transfer under energy rental / burned TRX. */
|
||||
export const MIN_TRX_SUN_FOR_WITHDRAWAL = 3_000_000n;
|
||||
/** ~0.001 BNB — buffer above a simple ERC-20 transfer on BSC. */
|
||||
export const MIN_BNB_WEI_FOR_WITHDRAWAL = 1_000_000_000_000_000n;
|
||||
|
||||
export type HotLiquidityVerdict =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: 'usdt' | 'gas'; needed: string; available: string };
|
||||
|
||||
/**
|
||||
* Pure comparison of hot balances vs required payout (ledger amount is always 6-dec micro-USDT).
|
||||
*/
|
||||
export function evaluateHotLiquidity(input: {
|
||||
network: 'TRON' | 'BSC';
|
||||
usdtBalanceRaw: bigint;
|
||||
nativeBalanceRaw: bigint;
|
||||
ledgerAmountRaw: bigint;
|
||||
}): HotLiquidityVerdict {
|
||||
const { network, usdtBalanceRaw, nativeBalanceRaw, ledgerAmountRaw } = input;
|
||||
if (ledgerAmountRaw <= 0n) {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
if (network === 'TRON') {
|
||||
if (usdtBalanceRaw < ledgerAmountRaw) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'usdt',
|
||||
needed: ledgerAmountRaw.toString(),
|
||||
available: usdtBalanceRaw.toString(),
|
||||
};
|
||||
}
|
||||
if (nativeBalanceRaw < MIN_TRX_SUN_FOR_WITHDRAWAL) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'gas',
|
||||
needed: MIN_TRX_SUN_FOR_WITHDRAWAL.toString(),
|
||||
available: nativeBalanceRaw.toString(),
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
const chainUsdt = scaleLedgerToChain(ledgerAmountRaw, BEP20_USDT_DECIMALS);
|
||||
if (usdtBalanceRaw < chainUsdt) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'usdt',
|
||||
needed: chainUsdt.toString(),
|
||||
available: usdtBalanceRaw.toString(),
|
||||
};
|
||||
}
|
||||
if (nativeBalanceRaw < MIN_BNB_WEI_FOR_WITHDRAWAL) {
|
||||
return {
|
||||
ok: false,
|
||||
reason: 'gas',
|
||||
needed: MIN_BNB_WEI_FOR_WITHDRAWAL.toString(),
|
||||
available: nativeBalanceRaw.toString(),
|
||||
};
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
function liquidityError(message: string): Error & { code: string } {
|
||||
const err = new Error(message) as Error & { code: string };
|
||||
err.code = 'HOT_WALLET_INSUFFICIENT_LIQUIDITY';
|
||||
return err;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads on-chain hot balances and throws if the platform cannot pay `ledgerAmountRaw` on `network`.
|
||||
*/
|
||||
export async function assertHotWalletCanPay(params: {
|
||||
network: 'TRON' | 'BSC';
|
||||
hotAddress: string;
|
||||
ledgerAmountRaw: bigint;
|
||||
usdtContract: string;
|
||||
}): Promise<void> {
|
||||
const { network, hotAddress, ledgerAmountRaw, usdtContract } = params;
|
||||
|
||||
let usdtBalanceRaw: bigint;
|
||||
let nativeBalanceRaw: bigint;
|
||||
|
||||
if (network === 'TRON') {
|
||||
const contract = config.blockchain.tron.usdtTrc20Contract || usdtContract;
|
||||
if (!contract) throw new Error('USDT TRC20 contract not configured');
|
||||
usdtBalanceRaw = await tronService.getTrc20BalanceRaw(hotAddress, contract);
|
||||
nativeBalanceRaw = await tronService.getTrxBalanceSun(hotAddress);
|
||||
} else {
|
||||
const contract = bscService.resolveUsdtContract(usdtContract);
|
||||
usdtBalanceRaw = await bscService.getUsdtBalanceRaw(hotAddress, contract);
|
||||
nativeBalanceRaw = await bscService.getNativeBalanceWei(hotAddress);
|
||||
}
|
||||
|
||||
const verdict = evaluateHotLiquidity({
|
||||
network,
|
||||
usdtBalanceRaw,
|
||||
nativeBalanceRaw,
|
||||
ledgerAmountRaw,
|
||||
});
|
||||
|
||||
if (verdict.ok) return;
|
||||
|
||||
if (verdict.reason === 'usdt') {
|
||||
throw liquidityError(
|
||||
`Platform hot wallet has insufficient USDT on ${network} to complete this withdrawal. Try again later or choose another network.`
|
||||
);
|
||||
}
|
||||
throw liquidityError(
|
||||
`Platform hot wallet has insufficient ${network === 'TRON' ? 'TRX' : 'BNB'} for gas on ${network}. Try again later or choose another network.`
|
||||
);
|
||||
}
|
||||
@ -1,6 +1,8 @@
|
||||
/**
|
||||
* User wallet and deposit address service.
|
||||
* Derives TRON (TRC20) and BSC (BEP20) deposit addresses for USDT.
|
||||
* Spendable ledger is always USDT_TRC20 (6 decimals). Inventory is deposit-sourced
|
||||
* ops telemetry per network; withdrawals are capped by ledger + hot float, not inventory.
|
||||
*/
|
||||
|
||||
import * as bip39 from 'bip39';
|
||||
@ -8,9 +10,11 @@ import { deriveEvmFromMnemonic, deriveTronFromMnemonic } from './hdWallet';
|
||||
import { query } from '../db/connection';
|
||||
import * as walletRepository from '../repositories/walletRepository';
|
||||
import * as transactionRepository from '../repositories/transactionRepository';
|
||||
import * as networkInventoryRepository from '../repositories/networkInventoryRepository';
|
||||
import { Transaction } from '../models';
|
||||
import {
|
||||
assertUsdtWalletType,
|
||||
enrichWalletType,
|
||||
enrichWalletTypeAsync,
|
||||
USDT_BEP20_CODE,
|
||||
USDT_TRC20_CODE,
|
||||
@ -33,7 +37,7 @@ function getMnemonic(): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates a USDT deposit address for a user (TRC20 or BEP20).
|
||||
* Gets or creates a USDT deposit address for a user (TRC20 or BEP20 custody rail).
|
||||
*/
|
||||
export async function getOrCreateDepositAddress(
|
||||
userId: string,
|
||||
@ -84,45 +88,89 @@ export async function getWalletTypes(): Promise<WalletTypeCapabilities[]> {
|
||||
const types = await walletRepository.getWalletTypes();
|
||||
const { getSettings } = await import('../repositories/settingsRepository');
|
||||
const settings = await getSettings();
|
||||
const { enrichWalletType } = await import('./walletCapabilities');
|
||||
return types.map((wt) => enrichWalletType(wt, settings));
|
||||
}
|
||||
|
||||
export async function getUserBalances(userId: string): Promise<
|
||||
Array<{
|
||||
export type NetworkBalanceInfo = {
|
||||
code: string;
|
||||
network: string;
|
||||
depositEnabled: boolean;
|
||||
withdrawEnabled: boolean;
|
||||
/** Cumulative deposits credited on this network (ops / reporting; not a withdrawal cap). */
|
||||
inventory: string;
|
||||
/** Max withdrawable on this rail when enabled = full spendable available (ledger units). */
|
||||
withdrawable: string;
|
||||
};
|
||||
|
||||
export type UserBalancesResponse = {
|
||||
/** Unified spendable USDT ledger (USDT_TRC20, 6 decimals). */
|
||||
spendable: {
|
||||
walletType: WalletTypeCapabilities;
|
||||
available: string;
|
||||
locked: string;
|
||||
bonusAvailable: string;
|
||||
testAvailable: string;
|
||||
}>
|
||||
> {
|
||||
const types = await walletRepository.getWalletTypes();
|
||||
};
|
||||
inventory: { TRON: string; BSC: string };
|
||||
networks: NetworkBalanceInfo[];
|
||||
/**
|
||||
* @deprecated Prefer `spendable` + `networks`. Kept for older clients:
|
||||
* single spendable row only (no separate BEP20 ledger balance).
|
||||
*/
|
||||
balances: Array<{
|
||||
walletType: WalletTypeCapabilities;
|
||||
available: string;
|
||||
locked: string;
|
||||
bonusAvailable: string;
|
||||
testAvailable: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
export async function getUserBalances(userId: string): Promise<UserBalancesResponse> {
|
||||
const { getOrCreateAccount, getAccount } = await import('../repositories/ledgerRepository');
|
||||
const { getSettings } = await import('../repositories/settingsRepository');
|
||||
const { enrichWalletType } = await import('./walletCapabilities');
|
||||
const settings = await getSettings();
|
||||
const result: Array<{
|
||||
walletType: WalletTypeCapabilities;
|
||||
available: string;
|
||||
locked: string;
|
||||
bonusAvailable: string;
|
||||
testAvailable: string;
|
||||
}> = [];
|
||||
|
||||
const ledgerType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
if (!ledgerType) throw new Error('USDT_TRC20 wallet type not configured');
|
||||
|
||||
const account = await getOrCreateAccount(userId, ledgerType.id, 'main');
|
||||
const bonus = await getAccount(userId, ledgerType.id, 'bonus');
|
||||
const test = await getAccount(userId, ledgerType.id, 'test');
|
||||
const available = BigInt(account.available_balance);
|
||||
const inv = await networkInventoryRepository.getAllForUser(userId);
|
||||
|
||||
const spendable = {
|
||||
walletType: enrichWalletType(ledgerType, settings),
|
||||
available: account.available_balance,
|
||||
locked: account.locked_balance,
|
||||
bonusAvailable: bonus?.available_balance ?? '0',
|
||||
testAvailable: test?.available_balance ?? '0',
|
||||
};
|
||||
|
||||
const types = await walletRepository.getWalletTypes();
|
||||
const networks: NetworkBalanceInfo[] = [];
|
||||
for (const wt of types) {
|
||||
if (wt.code !== USDT_TRC20_CODE && wt.code !== USDT_BEP20_CODE) continue;
|
||||
const account = await getOrCreateAccount(userId, wt.id, 'main');
|
||||
const bonus = await getAccount(userId, wt.id, 'bonus');
|
||||
const test = await getAccount(userId, wt.id, 'test');
|
||||
result.push({
|
||||
walletType: enrichWalletType(wt, settings),
|
||||
available: account.available_balance,
|
||||
locked: account.locked_balance,
|
||||
bonusAvailable: bonus?.available_balance ?? '0',
|
||||
testAvailable: test?.available_balance ?? '0',
|
||||
const caps = enrichWalletType(wt, settings);
|
||||
const networkInv = wt.network === 'BSC' ? inv.BSC : inv.TRON;
|
||||
const withdrawable = caps.withdrawEnabled ? available : 0n;
|
||||
networks.push({
|
||||
code: wt.code,
|
||||
network: wt.network,
|
||||
depositEnabled: caps.depositEnabled,
|
||||
withdrawEnabled: caps.withdrawEnabled,
|
||||
inventory: networkInv.toString(),
|
||||
withdrawable: withdrawable.toString(),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
|
||||
return {
|
||||
spendable,
|
||||
inventory: { TRON: inv.TRON.toString(), BSC: inv.BSC.toString() },
|
||||
networks,
|
||||
balances: [spendable],
|
||||
};
|
||||
}
|
||||
|
||||
export async function listUserTransactions(
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
/**
|
||||
* On-chain withdrawal service.
|
||||
* Locks ledger balance, broadcasts via hot wallet, finalizes ledger atomically after broadcast.
|
||||
* Debits unified USDT ledger (USDT_TRC20, 6 decimals); pays from the chosen
|
||||
* rail hot wallet (TRC20 or BEP20). Network need not match deposit history —
|
||||
* liquidity is gated by hot float (USDT + gas), not user inventory.
|
||||
*/
|
||||
|
||||
import { config } from '../config';
|
||||
@ -27,17 +29,28 @@ import * as referralService from './referralService';
|
||||
import { rawAmountToUsdApprox } from '../utils/withdrawalLimits';
|
||||
import type { SystemSettings } from '../models/settings.model';
|
||||
import type { WalletType } from '../models/wallet.model';
|
||||
import { enrichWalletType, isSupportedUsdtCode } from './walletCapabilities';
|
||||
import {
|
||||
enrichWalletType,
|
||||
isSupportedUsdtCode,
|
||||
USDT_TRC20_CODE,
|
||||
} from './walletCapabilities';
|
||||
import {
|
||||
BEP20_USDT_DECIMALS,
|
||||
LEDGER_USDT_DECIMALS,
|
||||
networkForWalletCode,
|
||||
scaleLedgerToChain,
|
||||
} from '../utils/usdtUnits';
|
||||
import { assertHotWalletCanPay } from './hotLiquidityService';
|
||||
|
||||
async function assertWithdrawalWithinLimits(
|
||||
userId: string,
|
||||
walletType: WalletType,
|
||||
railWalletType: WalletType,
|
||||
amountRaw: bigint,
|
||||
feeRaw: bigint,
|
||||
settings: SystemSettings
|
||||
): Promise<void> {
|
||||
const amountUsd = rawAmountToUsdApprox(walletType.code, amountRaw, walletType.decimals);
|
||||
const feeUsd = rawAmountToUsdApprox(walletType.code, feeRaw, walletType.decimals);
|
||||
const amountUsd = rawAmountToUsdApprox(USDT_TRC20_CODE, amountRaw, LEDGER_USDT_DECIMALS);
|
||||
const feeUsd = rawAmountToUsdApprox(USDT_TRC20_CODE, feeRaw, LEDGER_USDT_DECIMALS);
|
||||
const totalUsd = amountUsd + feeUsd;
|
||||
|
||||
const startOfUtcDay = new Date();
|
||||
@ -64,7 +77,7 @@ async function assertWithdrawalWithinLimits(
|
||||
metadata: {
|
||||
amountUsd,
|
||||
thresholdUsd: settings.large_withdrawal_threshold_usd,
|
||||
walletType: walletType.code,
|
||||
walletType: railWalletType.code,
|
||||
amount: amountRaw.toString(),
|
||||
},
|
||||
});
|
||||
@ -77,7 +90,7 @@ async function assertWithdrawalWithinLimits(
|
||||
metadata: {
|
||||
amountUsd,
|
||||
thresholdUsd: settings.large_withdrawal_threshold_usd,
|
||||
walletType: walletType.code,
|
||||
walletType: railWalletType.code,
|
||||
},
|
||||
}).catch((e) => console.error('[withdrawal] large withdrawal alert failed:', e));
|
||||
}
|
||||
@ -92,8 +105,9 @@ export type WithdrawalResult = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Submits a withdrawal: locks funds (amount + network fee), sends amount on-chain from hot wallet.
|
||||
* If on-chain succeeds but ledger finalization fails, funds stay locked and security is alerted.
|
||||
* Submits a withdrawal: locks unified ledger, verifies hot float, pays from rail hot wallet.
|
||||
* `walletTypeCode` selects the payout rail (USDT_TRC20 or USDT_BEP20).
|
||||
* `amountRaw` is always in ledger micro-USDT (6 decimals).
|
||||
*/
|
||||
export async function requestWithdrawal(
|
||||
userId: string,
|
||||
@ -110,25 +124,31 @@ export async function requestWithdrawal(
|
||||
await authService.assertWithdrawalSecondFactor(userId, totpCode);
|
||||
await assertUserCanWithdraw(userId);
|
||||
|
||||
const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
|
||||
if (!walletType) throw new Error('Unknown wallet type');
|
||||
const railWalletType = await walletRepository.getWalletTypeByCode(walletTypeCode);
|
||||
if (!railWalletType) throw new Error('Unknown wallet type');
|
||||
if (!isSupportedUsdtCode(walletTypeCode)) {
|
||||
throw new Error(`Withdrawals are only supported for USDT networks`);
|
||||
}
|
||||
const caps = enrichWalletType(walletType, settings);
|
||||
const network = networkForWalletCode(walletTypeCode);
|
||||
if (!network) throw new Error('Unsupported withdrawal network');
|
||||
|
||||
const caps = enrichWalletType(railWalletType, settings);
|
||||
if (!caps.withdrawEnabled) {
|
||||
throw new Error(`Withdrawals are disabled for ${walletTypeCode}`);
|
||||
}
|
||||
if (amountRaw <= 0n) throw new Error('Invalid amount');
|
||||
|
||||
const feeRaw = getWithdrawalNetworkFeeRaw(settings, walletType.decimals);
|
||||
const ledgerWalletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
|
||||
if (!ledgerWalletType) throw new Error('USDT ledger wallet type not configured');
|
||||
|
||||
const feeRaw = getWithdrawalNetworkFeeRaw(settings, LEDGER_USDT_DECIMALS);
|
||||
const totalDebit = amountRaw + feeRaw;
|
||||
|
||||
await assertWithdrawalWithinLimits(userId, walletType, amountRaw, feeRaw, settings);
|
||||
await assertWithdrawalWithinLimits(userId, railWalletType, amountRaw, feeRaw, settings);
|
||||
|
||||
const account = await ledgerRepository.getOrCreateAccount(userId, walletType.id);
|
||||
const account = await ledgerRepository.getOrCreateAccount(userId, ledgerWalletType.id);
|
||||
const available = BigInt(account.available_balance);
|
||||
const locked = await withdrawalLockRepository.getLockedAmount(userId, walletType.id);
|
||||
const locked = await withdrawalLockRepository.getLockedAmount(userId, ledgerWalletType.id);
|
||||
if (available < totalDebit + locked) {
|
||||
throw new Error(
|
||||
feeRaw > 0n
|
||||
@ -137,28 +157,44 @@ export async function requestWithdrawal(
|
||||
);
|
||||
}
|
||||
|
||||
const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id);
|
||||
if (!hotWallet) throw new Error('Withdrawal temporarily unavailable');
|
||||
|
||||
if (network === 'TRON' || network === 'BSC') {
|
||||
await assertHotWalletCanPay({
|
||||
network,
|
||||
hotAddress: hotWallet.address,
|
||||
ledgerAmountRaw: amountRaw,
|
||||
usdtContract: railWalletType.contract_address || '',
|
||||
});
|
||||
}
|
||||
|
||||
await ledgerRepository.lockBalance(account.id, totalDebit);
|
||||
queueUserAdminStatsRefresh(userId);
|
||||
|
||||
const tx = await transactionRepository.create({
|
||||
userId,
|
||||
walletTypeId: walletType.id,
|
||||
walletTypeId: ledgerWalletType.id,
|
||||
type: 'withdrawal',
|
||||
amount: amountRaw,
|
||||
fee: feeRaw,
|
||||
status: 'pending',
|
||||
toAddress,
|
||||
requiredConfirmations:
|
||||
walletType.network === 'TRON'
|
||||
railWalletType.network === 'TRON'
|
||||
? config.blockchain.tron.confirmations
|
||||
: walletType.network === 'BSC'
|
||||
: railWalletType.network === 'BSC'
|
||||
? config.blockchain.bsc.confirmations
|
||||
: config.blockchain.polygon.confirmations,
|
||||
metadata: {
|
||||
rail_wallet_type: walletTypeCode,
|
||||
network,
|
||||
},
|
||||
});
|
||||
|
||||
await withdrawalLockRepository.create({
|
||||
userId,
|
||||
walletTypeId: walletType.id,
|
||||
walletTypeId: ledgerWalletType.id,
|
||||
transactionId: tx.id,
|
||||
amount: totalDebit,
|
||||
});
|
||||
@ -173,33 +209,27 @@ export async function requestWithdrawal(
|
||||
fee: feeRaw.toString(),
|
||||
toAddress,
|
||||
walletType: walletTypeCode,
|
||||
network,
|
||||
},
|
||||
});
|
||||
|
||||
let blockchainTxId: string | null = null;
|
||||
|
||||
try {
|
||||
const hotWallet = await hotWalletRepository.getActiveHotWallet(walletType.id);
|
||||
if (!hotWallet) throw new Error('Withdrawal temporarily unavailable');
|
||||
|
||||
const privateKey = decryptPrivateKey(hotWallet.encrypted_private_key);
|
||||
|
||||
await transactionRepository.updateStatus(tx.id, 'broadcasting');
|
||||
|
||||
if (walletType.network === 'TRON') {
|
||||
if (railWalletType.network === 'TRON') {
|
||||
const trc20Contract =
|
||||
walletType.code === 'USDT_TRC20' && config.blockchain.tron.usdtTrc20Contract
|
||||
? config.blockchain.tron.usdtTrc20Contract
|
||||
: walletType.contract_address;
|
||||
if (trc20Contract) {
|
||||
blockchainTxId = await tronService.sendTrc20(privateKey, trc20Contract, toAddress, amountRaw);
|
||||
} else {
|
||||
blockchainTxId = await tronService.sendTrx(privateKey, toAddress, amountRaw);
|
||||
}
|
||||
} else if (walletType.network === 'BSC') {
|
||||
const contract = bscService.resolveUsdtContract(walletType.contract_address);
|
||||
blockchainTxId = await bscService.sendUsdt(privateKey, contract, toAddress, amountRaw);
|
||||
} else if (walletType.network === 'POLYGON') {
|
||||
config.blockchain.tron.usdtTrc20Contract || railWalletType.contract_address;
|
||||
if (!trc20Contract) throw new Error('USDT TRC20 contract not configured');
|
||||
blockchainTxId = await tronService.sendTrc20(privateKey, trc20Contract, toAddress, amountRaw);
|
||||
} else if (railWalletType.network === 'BSC') {
|
||||
const contract = bscService.resolveUsdtContract(railWalletType.contract_address);
|
||||
const chainAmount = scaleLedgerToChain(amountRaw, BEP20_USDT_DECIMALS);
|
||||
blockchainTxId = await bscService.sendUsdt(privateKey, contract, toAddress, chainAmount);
|
||||
} else if (railWalletType.network === 'POLYGON') {
|
||||
blockchainTxId = await polygonService.sendUsdc(privateKey, toAddress, amountRaw);
|
||||
} else {
|
||||
throw new Error('Unsupported network');
|
||||
@ -243,6 +273,7 @@ export async function requestWithdrawal(
|
||||
totalDebited: totalDebit.toString(),
|
||||
toAddress,
|
||||
blockchainTxId,
|
||||
network,
|
||||
},
|
||||
});
|
||||
queueUserAdminStatsRefresh(userId);
|
||||
@ -252,7 +283,7 @@ export async function requestWithdrawal(
|
||||
userId,
|
||||
withdrawalTransactionId: tx.id,
|
||||
withdrawalAmount: amountRaw,
|
||||
walletTypeId: walletType.id,
|
||||
walletTypeId: ledgerWalletType.id,
|
||||
});
|
||||
} catch (referralErr) {
|
||||
console.error('[referral] Withdrawal commission processing failed:', referralErr);
|
||||
|
||||
73
backend/src/tests/hotLiquidity.test.ts
Normal file
73
backend/src/tests/hotLiquidity.test.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
evaluateHotLiquidity,
|
||||
MIN_BNB_WEI_FOR_WITHDRAWAL,
|
||||
MIN_TRX_SUN_FOR_WITHDRAWAL,
|
||||
} from '../services/hotLiquidityService';
|
||||
|
||||
describe('evaluateHotLiquidity', () => {
|
||||
test('TRON: allows when USDT + TRX sufficient (cross-network, no inventory)', () => {
|
||||
const v = evaluateHotLiquidity({
|
||||
network: 'TRON',
|
||||
usdtBalanceRaw: 1_000_000_000n, // 1000 USDT
|
||||
nativeBalanceRaw: MIN_TRX_SUN_FOR_WITHDRAWAL,
|
||||
ledgerAmountRaw: 1_000_000_000n,
|
||||
});
|
||||
assert.equal(v.ok, true);
|
||||
});
|
||||
|
||||
test('TRON: rejects when hot USDT below payout', () => {
|
||||
const v = evaluateHotLiquidity({
|
||||
network: 'TRON',
|
||||
usdtBalanceRaw: 999_999_999n,
|
||||
nativeBalanceRaw: MIN_TRX_SUN_FOR_WITHDRAWAL,
|
||||
ledgerAmountRaw: 1_000_000_000n,
|
||||
});
|
||||
assert.equal(v.ok, false);
|
||||
if (!v.ok) assert.equal(v.reason, 'usdt');
|
||||
});
|
||||
|
||||
test('TRON: rejects when TRX below gas floor', () => {
|
||||
const v = evaluateHotLiquidity({
|
||||
network: 'TRON',
|
||||
usdtBalanceRaw: 1_000_000_000n,
|
||||
nativeBalanceRaw: MIN_TRX_SUN_FOR_WITHDRAWAL - 1n,
|
||||
ledgerAmountRaw: 1n,
|
||||
});
|
||||
assert.equal(v.ok, false);
|
||||
if (!v.ok) assert.equal(v.reason, 'gas');
|
||||
});
|
||||
|
||||
test('BSC: scales ledger 6-dec to 18-dec USDT requirement', () => {
|
||||
const ledger = 5_000_000n; // 5 USDT
|
||||
const chainNeeded = ledger * 10n ** 12n;
|
||||
const ok = evaluateHotLiquidity({
|
||||
network: 'BSC',
|
||||
usdtBalanceRaw: chainNeeded,
|
||||
nativeBalanceRaw: MIN_BNB_WEI_FOR_WITHDRAWAL,
|
||||
ledgerAmountRaw: ledger,
|
||||
});
|
||||
assert.equal(ok.ok, true);
|
||||
|
||||
const short = evaluateHotLiquidity({
|
||||
network: 'BSC',
|
||||
usdtBalanceRaw: chainNeeded - 1n,
|
||||
nativeBalanceRaw: MIN_BNB_WEI_FOR_WITHDRAWAL,
|
||||
ledgerAmountRaw: ledger,
|
||||
});
|
||||
assert.equal(short.ok, false);
|
||||
if (!short.ok) assert.equal(short.reason, 'usdt');
|
||||
});
|
||||
|
||||
test('BSC: rejects when BNB below gas floor', () => {
|
||||
const v = evaluateHotLiquidity({
|
||||
network: 'BSC',
|
||||
usdtBalanceRaw: 10n ** 18n,
|
||||
nativeBalanceRaw: MIN_BNB_WEI_FOR_WITHDRAWAL - 1n,
|
||||
ledgerAmountRaw: 1_000_000n,
|
||||
});
|
||||
assert.equal(v.ok, false);
|
||||
if (!v.ok) assert.equal(v.reason, 'gas');
|
||||
});
|
||||
});
|
||||
30
backend/src/tests/usdtUnits.test.ts
Normal file
30
backend/src/tests/usdtUnits.test.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
BEP20_USDT_DECIMALS,
|
||||
LEDGER_USDT_DECIMALS,
|
||||
scaleChainToLedger,
|
||||
scaleLedgerToChain,
|
||||
} from '../utils/usdtUnits';
|
||||
|
||||
describe('usdtUnits', () => {
|
||||
test('scales 100 USDT BEP20 (18) down to ledger (6)', () => {
|
||||
const chain = 100n * 10n ** 18n;
|
||||
assert.equal(scaleChainToLedger(chain, BEP20_USDT_DECIMALS), 100n * 10n ** 6n);
|
||||
});
|
||||
|
||||
test('truncates dust below 6 decimals', () => {
|
||||
// 1 wei of BEP20 USDT
|
||||
assert.equal(scaleChainToLedger(1n, BEP20_USDT_DECIMALS), 0n);
|
||||
});
|
||||
|
||||
test('scales ledger amount up for BEP20 send', () => {
|
||||
const ledger = 5n * 10n ** 6n; // 5 USDT
|
||||
assert.equal(scaleLedgerToChain(ledger, BEP20_USDT_DECIMALS), 5n * 10n ** 18n);
|
||||
});
|
||||
|
||||
test('identity when decimals match', () => {
|
||||
assert.equal(scaleChainToLedger(123n, LEDGER_USDT_DECIMALS), 123n);
|
||||
assert.equal(scaleLedgerToChain(123n, LEDGER_USDT_DECIMALS), 123n);
|
||||
});
|
||||
});
|
||||
34
backend/src/utils/usdtUnits.ts
Normal file
34
backend/src/utils/usdtUnits.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* USDT unit helpers: platform ledger uses 6 decimals; BEP20 chain uses 18.
|
||||
*/
|
||||
|
||||
export const LEDGER_USDT_DECIMALS = 6;
|
||||
export const BEP20_USDT_DECIMALS = 18;
|
||||
|
||||
export type CustodyNetwork = 'TRON' | 'BSC';
|
||||
|
||||
/** Truncate chain (18) amount down to ledger micro-USDT (6). */
|
||||
export function scaleChainToLedger(amount: bigint, fromDecimals: number, toDecimals = LEDGER_USDT_DECIMALS): bigint {
|
||||
if (amount < 0n) return 0n;
|
||||
if (fromDecimals === toDecimals) return amount;
|
||||
if (fromDecimals > toDecimals) {
|
||||
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
||||
}
|
||||
return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
||||
}
|
||||
|
||||
/** Scale ledger micro-USDT (6) up to chain units (e.g. BEP20 18). */
|
||||
export function scaleLedgerToChain(amount: bigint, toDecimals: number, fromDecimals = LEDGER_USDT_DECIMALS): bigint {
|
||||
if (amount < 0n) return 0n;
|
||||
if (fromDecimals === toDecimals) return amount;
|
||||
if (toDecimals > fromDecimals) {
|
||||
return amount * 10n ** BigInt(toDecimals - fromDecimals);
|
||||
}
|
||||
return amount / 10n ** BigInt(fromDecimals - toDecimals);
|
||||
}
|
||||
|
||||
export function networkForWalletCode(code: string): CustodyNetwork | null {
|
||||
if (code === 'USDT_TRC20') return 'TRON';
|
||||
if (code === 'USDT_BEP20') return 'BSC';
|
||||
return null;
|
||||
}
|
||||
@ -143,8 +143,9 @@ npm run seed-hot-wallets
|
||||
|
||||
Une seule fois suffit : si un hot wallet existe déjà pour un réseau, le script affiche `Skipping` pour ce type. Le seed crée **deux** hot wallets : `USDT_TRC20` (TRON, index `1000000`) et `USDT_BEP20` (BSC, index `1000001`).
|
||||
|
||||
- Hot **TRON** : financer en **TRX** (gas) + USDT TRC20 avant retraits TRC20.
|
||||
- Hot **BSC** : financer en **BNB** (gas) + USDT BEP20 avant retraits BEP20.
|
||||
- Hot **TRON** : financer en **TRX** (gas) + USDT TRC20 — float plateforme pour **tous** les retraits TRC20 (même si le user a déposé en BEP20).
|
||||
- Hot **BSC** : financer en **BNB** (gas) + USDT BEP20 — float pour **tous** les retraits BEP20.
|
||||
- Dimensionnez les deux hots comme **trésorerie de payout** (gains inclus), pas seulement comme miroir des dépôts du même réseau.
|
||||
|
||||
#### Rotation des adresses de dépôt (après changement de `PLATFORM_MNEMONIC`)
|
||||
|
||||
@ -397,12 +398,14 @@ Cette section regroupe les commandes lorsque PostgreSQL est **vide** (base cré
|
||||
### Test argent réel — ordre BEP20 d’abord
|
||||
|
||||
1. Admin → Settings → **USDT networks** : activer dépôt (et plus tard retrait) **BEP20** ; TRC20 selon besoin.
|
||||
2. Financer le hot BSC avec un peu de **BNB** + USDT BEP20 (pour retraits).
|
||||
2. Financer le hot BSC avec **BNB** + USDT BEP20 (float retraits). Pour les retraits cross-réseau TRC20, financer aussi le hot TRON (TRX + USDT).
|
||||
3. User test → Receive → réseau **BSC (BEP20)** → copier l’adresse `0x…`.
|
||||
4. Depuis Binance (ou wallet) : retirer USDT en réseau **BEP20 / BSC** uniquement (pas TRC20).
|
||||
5. Attendre confirmations → solde ledger `USDT_BEP20` crédité.
|
||||
6. Micro-retrait : activer kill-switch global + flag withdraw BEP20 → retirer vers une adresse BSC contrôlée.
|
||||
7. (Optionnel) répéter sur TRC20 avec adresse `T…` et réseau TRON.
|
||||
5. Attendre confirmations → **solde USDT unifié** crédité (Candle Predict utilise ce solde).
|
||||
6. Micro-retrait : activer kill-switch global + flag withdraw BEP20 → retirer vers une adresse BSC (plafond = solde ledger ; le hot doit avoir assez d’USDT + BNB).
|
||||
7. (Optionnel) activer withdraw TRC20 → même solde retirable en TRC20 si le hot TRON a assez d’USDT + TRX (indépendant du réseau de dépôt).
|
||||
|
||||
> **Ledger unifié + float hot :** dépôts TRC20 et BEP20 alimentent le même solde jouable (`USDT_TRC20` en DB, 6 décimales). Le réseau de retrait n’a **pas** à correspondre au dépôt ; l’API refuse un retrait si le hot du rail choisi n’a pas assez d’USDT ou de gas (`HOT_WALLET_INSUFFICIENT_LIQUIDITY`). L’inventaire par réseau reste un compteur ops (dépôts), pas un plafond joueur.
|
||||
|
||||
### Prérequis communs
|
||||
|
||||
|
||||
@ -23,12 +23,28 @@ class WalletRepositoryImpl {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Returns the authenticated user's balances across all wallet types.
|
||||
/// Returns the authenticated user's balances (unified ledger payload).
|
||||
Future<List<BalanceModel>> getBalances() async {
|
||||
final res = await _api.dio.get<List<dynamic>>('/api/v1/balances');
|
||||
return (res.data ?? [])
|
||||
.map((e) => BalanceModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
final res = await _api.dio.get<dynamic>('/api/v1/balances');
|
||||
final data = res.data;
|
||||
if (data is List) {
|
||||
return data
|
||||
.map((e) => BalanceModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
if (data is Map<String, dynamic>) {
|
||||
final list = data['balances'];
|
||||
if (list is List) {
|
||||
return list
|
||||
.map((e) => BalanceModel.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
final spendable = data['spendable'];
|
||||
if (spendable is Map<String, dynamic>) {
|
||||
return [BalanceModel.fromJson(spendable)];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/// Retrieves a blockchain deposit address for the given [walletType] code.
|
||||
|
||||
@ -75,7 +75,7 @@ class _DepositAssetSelectScreenState extends State<DepositAssetSelectScreen> {
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Select USDT on TRON (TRC20) or BSC (BEP20). You will then see the matching deposit address and QR code.',
|
||||
'Select a deposit network (TRON TRC20 or BSC BEP20). Credits go to your single USDT balance for predictions.',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Player wallet page — USDT on TRC20 and/or BEP20 (separate ledgers).
|
||||
* Player wallet page — unified USDT ledger + per-network deposit/withdraw flags.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -33,8 +33,8 @@ import { TransactionList } from './components/TransactionList';
|
||||
import { DEFAULT_TX_PAGE_SIZE, useBalances, useTransactions } from './hooks/useWalletData';
|
||||
import type { WalletActivityCategory } from './types';
|
||||
import { networkLabel } from './utils/coinDisplay';
|
||||
import { USDT_WALLET_CODE, isSupportedUsdtCode } from './utils/walletCapabilities';
|
||||
import { rawToHuman, shortSymbol } from './utils/walletFormat';
|
||||
import { USDT_WALLET_CODE } from './utils/walletCapabilities';
|
||||
import { rawToHuman } from './utils/walletFormat';
|
||||
|
||||
type DialogKind = 'receive' | 'transfer' | 'withdraw' | null;
|
||||
|
||||
@ -60,36 +60,14 @@ export function WalletPage() {
|
||||
},
|
||||
});
|
||||
|
||||
const balances = balancesQ.data ?? [];
|
||||
const usdtBalances = useMemo(
|
||||
() => balances.filter((b) => isSupportedUsdtCode(b.walletType.code)),
|
||||
[balances]
|
||||
);
|
||||
const depositableBalances = useMemo(
|
||||
() => usdtBalances.filter((b) => b.walletType.depositEnabled === true),
|
||||
[usdtBalances]
|
||||
);
|
||||
const withdrawableBalances = useMemo(
|
||||
() => usdtBalances.filter((b) => b.walletType.withdrawEnabled === true),
|
||||
[usdtBalances]
|
||||
);
|
||||
const spendable = balancesQ.data?.spendable ?? null;
|
||||
const networks = balancesQ.data?.networks ?? [];
|
||||
const transferBalances = balancesQ.data?.balances ?? [];
|
||||
const transactions = txQ.data?.items ?? [];
|
||||
const txTotal = txQ.data?.total ?? 0;
|
||||
const primaryBalance =
|
||||
usdtBalances.find((b) => b.walletType.code === USDT_WALLET_CODE) ?? usdtBalances[0];
|
||||
|
||||
const portfolioSummary = useMemo(() => {
|
||||
if (usdtBalances.length === 0) return null;
|
||||
const lines = usdtBalances.map((b) => ({
|
||||
code: b.walletType.code,
|
||||
human: rawToHuman(b.available, b.walletType.decimals),
|
||||
locked: rawToHuman(b.locked, b.walletType.decimals),
|
||||
hasLocked: BigInt(b.locked || '0') > 0n,
|
||||
network: networkLabel(b.walletType.code),
|
||||
depositEnabled: b.walletType.depositEnabled === true,
|
||||
}));
|
||||
return { lines };
|
||||
}, [usdtBalances]);
|
||||
const depositable = useMemo(() => networks.filter((n) => n.depositEnabled), [networks]);
|
||||
const withdrawable = useMemo(() => networks.filter((n) => n.withdrawEnabled), [networks]);
|
||||
|
||||
const refreshAll = async () => {
|
||||
await Promise.all([balancesQ.refetch(), txQ.refetch(), healthQ.refetch()]);
|
||||
@ -98,24 +76,22 @@ export function WalletPage() {
|
||||
|
||||
const openDialog = (kind: DialogKind, asset?: string) => {
|
||||
if (kind === 'receive') {
|
||||
if (depositableBalances.length === 0) {
|
||||
if (depositable.length === 0) {
|
||||
setToast(t('wallet.receiveDialog.noNetworks'));
|
||||
return;
|
||||
}
|
||||
const ok =
|
||||
!asset || depositableBalances.some((b) => b.walletType.code === asset);
|
||||
setDialogAsset(ok ? asset ?? null : depositableBalances[0]?.walletType.code ?? null);
|
||||
const ok = !asset || depositable.some((n) => n.code === asset);
|
||||
setDialogAsset(ok ? asset ?? null : depositable[0]?.code ?? null);
|
||||
setDialog('receive');
|
||||
return;
|
||||
}
|
||||
if (kind === 'withdraw') {
|
||||
if (withdrawableBalances.length === 0) {
|
||||
if (withdrawable.length === 0) {
|
||||
setToast(t('wallet.withdrawDialog.noNetworks'));
|
||||
return;
|
||||
}
|
||||
const ok =
|
||||
!asset || withdrawableBalances.some((b) => b.walletType.code === asset);
|
||||
setDialogAsset(ok ? asset ?? null : withdrawableBalances[0]?.walletType.code ?? null);
|
||||
const ok = !asset || withdrawable.some((n) => n.code === asset);
|
||||
setDialogAsset(ok ? asset ?? null : withdrawable[0]?.code ?? null);
|
||||
setDialog('withdraw');
|
||||
return;
|
||||
}
|
||||
@ -163,21 +139,34 @@ export function WalletPage() {
|
||||
</Typography>
|
||||
{loading ? (
|
||||
<Skeleton variant="text" width={200} height={48} sx={{ mt: 1 }} />
|
||||
) : portfolioSummary ? (
|
||||
) : spendable ? (
|
||||
<Stack spacing={1} sx={{ mt: 1 }}>
|
||||
{portfolioSummary.lines.map((line) => (
|
||||
<Stack key={line.code} spacing={0.5}>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900 }}>
|
||||
{line.human} {shortSymbol(line.code)}
|
||||
<Typography variant="h4" sx={{ fontWeight: 900 }}>
|
||||
{rawToHuman(spendable.available, spendable.walletType.decimals)} USDT
|
||||
</Typography>
|
||||
{BigInt(spendable.locked || '0') > 0n && (
|
||||
<Chip
|
||||
size="small"
|
||||
variant="outlined"
|
||||
label={t('wallet.locked', {
|
||||
amount: rawToHuman(spendable.locked, spendable.walletType.decimals),
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
<Stack spacing={0.5}>
|
||||
{networks.map((n) => (
|
||||
<Typography key={n.code} variant="body2" sx={{ opacity: 0.75 }}>
|
||||
{networkLabel(n.code)} —{' '}
|
||||
{n.depositEnabled
|
||||
? t('wallet.mainCard.depositsOn')
|
||||
: t('wallet.mainCard.depositsOff')}
|
||||
{' · '}
|
||||
{n.withdrawEnabled
|
||||
? t('wallet.mainCard.withdrawalsOn')
|
||||
: t('wallet.mainCard.withdrawalsOff')}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
{line.network}
|
||||
</Typography>
|
||||
{line.hasLocked && (
|
||||
<Chip size="small" variant="outlined" label={t('wallet.locked', { amount: line.locked })} />
|
||||
)}
|
||||
</Stack>
|
||||
))}
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
) : (
|
||||
<Typography sx={{ opacity: 0.7, mt: 1 }}>{t('wallet.noBalance')}</Typography>
|
||||
@ -188,7 +177,7 @@ export function WalletPage() {
|
||||
variant="contained"
|
||||
startIcon={<CallReceivedRoundedIcon />}
|
||||
onClick={() => openDialog('receive')}
|
||||
disabled={depositableBalances.length === 0}
|
||||
disabled={depositable.length === 0}
|
||||
sx={{ flex: 1 }}
|
||||
>
|
||||
{t('wallet.receiveUsdt')}
|
||||
@ -206,7 +195,7 @@ export function WalletPage() {
|
||||
color="warning"
|
||||
startIcon={<SouthWestRoundedIcon />}
|
||||
onClick={() => openDialog('withdraw')}
|
||||
disabled={withdrawableBalances.length === 0 || !(healthQ.data?.withdrawalsEnabled ?? false)}
|
||||
disabled={withdrawable.length === 0 || !(healthQ.data?.withdrawalsEnabled ?? false)}
|
||||
sx={{ flex: 1 }}
|
||||
>
|
||||
{t('wallet.withdraw')}
|
||||
@ -241,32 +230,18 @@ export function WalletPage() {
|
||||
<Skeleton variant="rounded" height={220} sx={{ borderRadius: 2 }} />
|
||||
<Skeleton variant="rounded" height={220} sx={{ borderRadius: 2 }} />
|
||||
</>
|
||||
) : (
|
||||
) : spendable ? (
|
||||
<>
|
||||
{usdtBalances.map((b) => (
|
||||
<MainAssetCard
|
||||
key={b.walletType.code}
|
||||
balance={b}
|
||||
onReceive={() => openDialog('receive', b.walletType.code)}
|
||||
onSend={() => openDialog('transfer', b.walletType.code)}
|
||||
/>
|
||||
))}
|
||||
{primaryBalance ? (
|
||||
<>
|
||||
<BonusWalletCard
|
||||
balance={primaryBalance}
|
||||
onSuccess={setToast}
|
||||
onError={setToast}
|
||||
/>
|
||||
<TestWalletCard
|
||||
balance={primaryBalance}
|
||||
onSuccess={setToast}
|
||||
onError={setToast}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
<MainAssetCard
|
||||
balance={spendable}
|
||||
networks={networks}
|
||||
onReceive={() => openDialog('receive')}
|
||||
onSend={() => openDialog('transfer', USDT_WALLET_CODE)}
|
||||
/>
|
||||
<BonusWalletCard balance={spendable} onSuccess={setToast} onError={setToast} />
|
||||
<TestWalletCard balance={spendable} onSuccess={setToast} onError={setToast} />
|
||||
</>
|
||||
)}
|
||||
) : null}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@ -290,7 +265,7 @@ export function WalletPage() {
|
||||
</Tabs>
|
||||
<TransactionList
|
||||
transactions={transactions}
|
||||
balances={balances}
|
||||
balances={transferBalances}
|
||||
loading={txQ.isLoading}
|
||||
page={txPage}
|
||||
pageSize={DEFAULT_TX_PAGE_SIZE}
|
||||
@ -311,8 +286,8 @@ export function WalletPage() {
|
||||
|
||||
<TransferDialog
|
||||
open={dialog === 'transfer'}
|
||||
balances={usdtBalances}
|
||||
initialAsset={dialogAsset ?? USDT_WALLET_CODE}
|
||||
balances={transferBalances}
|
||||
initialAsset={USDT_WALLET_CODE}
|
||||
onClose={() => setDialog(null)}
|
||||
onSuccess={setToast}
|
||||
onError={setToast}
|
||||
@ -320,10 +295,11 @@ export function WalletPage() {
|
||||
|
||||
<WithdrawDialog
|
||||
open={dialog === 'withdraw'}
|
||||
balances={usdtBalances}
|
||||
spendable={spendable}
|
||||
networks={networks}
|
||||
withdrawalsEnabled={healthQ.data?.withdrawalsEnabled ?? false}
|
||||
networkFeeRaw={healthQ.data?.withdrawalNetworkFeeRaw ?? '0'}
|
||||
initialAsset={dialogAsset}
|
||||
initialRail={dialogAsset}
|
||||
onClose={() => setDialog(null)}
|
||||
onSuccess={setToast}
|
||||
onError={setToast}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Main USDT wallet card (one network / ledger).
|
||||
* Unified USDT spendable ledger card.
|
||||
*/
|
||||
import {
|
||||
Box,
|
||||
@ -13,26 +13,26 @@ import {
|
||||
} from '@mui/material';
|
||||
import QrCode2RoundedIcon from '@mui/icons-material/QrCode2Rounded';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { BalanceEntry } from '../types';
|
||||
import type { BalanceEntry, NetworkBalanceInfo } from '../types';
|
||||
import { coinColors, coinSymbol, networkLabel } from '../utils/coinDisplay';
|
||||
import { formatBalance } from '../utils/walletFormat';
|
||||
import { formatBalance, rawToHuman } from '../utils/walletFormat';
|
||||
|
||||
type MainAssetCardProps = {
|
||||
balance: BalanceEntry;
|
||||
networks: NetworkBalanceInfo[];
|
||||
onReceive: () => void;
|
||||
onSend: () => void;
|
||||
};
|
||||
|
||||
export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps) {
|
||||
export function MainAssetCard({ balance, networks, onReceive, onSend }: MainAssetCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const code = balance.walletType.code;
|
||||
const [c1, c2] = coinColors(code);
|
||||
const hasLocked = BigInt(balance.locked || '0') > 0n;
|
||||
const depositEnabled = balance.walletType.depositEnabled === true;
|
||||
const withdrawEnabled = balance.walletType.withdrawEnabled === true;
|
||||
const anyDeposit = networks.some((n) => n.depositEnabled);
|
||||
|
||||
return (
|
||||
<Card sx={{ borderRadius: 2, height: '100%', opacity: depositEnabled || withdrawEnabled ? 1 : 0.92 }}>
|
||||
<Card sx={{ borderRadius: 2, height: '100%' }}>
|
||||
<CardContent sx={{ p: 2.5 }}>
|
||||
<Stack direction="row" spacing={1.5} sx={{ alignItems: 'center' }}>
|
||||
<Box
|
||||
@ -51,44 +51,18 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps
|
||||
{coinSymbol(code)}
|
||||
</Box>
|
||||
<Box sx={{ flex: 1 }}>
|
||||
<Typography sx={{ fontWeight: 800 }}>{balance.walletType.name}</Typography>
|
||||
<Typography sx={{ fontWeight: 800 }}>{t('wallet.mainCard.title')}</Typography>
|
||||
<Typography variant="body2" sx={{ opacity: 0.65 }}>
|
||||
{networkLabel(code)}
|
||||
{t('wallet.mainCard.unifiedSubtitle')}
|
||||
</Typography>
|
||||
<Stack direction="row" spacing={0.75} sx={{ mt: 0.75, flexWrap: 'wrap', gap: 0.75 }}>
|
||||
<Chip
|
||||
size="small"
|
||||
color={depositEnabled ? 'success' : 'default'}
|
||||
variant={depositEnabled ? 'filled' : 'outlined'}
|
||||
label={
|
||||
depositEnabled
|
||||
? t('wallet.mainCard.depositsOn')
|
||||
: t('wallet.mainCard.depositsOff')
|
||||
}
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
<Chip
|
||||
size="small"
|
||||
color={withdrawEnabled ? 'success' : 'default'}
|
||||
variant={withdrawEnabled ? 'filled' : 'outlined'}
|
||||
label={
|
||||
withdrawEnabled
|
||||
? t('wallet.mainCard.withdrawalsOn')
|
||||
: t('wallet.mainCard.withdrawalsOff')
|
||||
}
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
{balance.walletType.predictionEnabled ? (
|
||||
<Chip
|
||||
size="small"
|
||||
color="primary"
|
||||
label={t('wallet.mainCard.predictionBadge')}
|
||||
sx={{ fontWeight: 700 }}
|
||||
/>
|
||||
) : null}
|
||||
</Stack>
|
||||
<Chip
|
||||
size="small"
|
||||
color="primary"
|
||||
label={t('wallet.mainCard.predictionBadge')}
|
||||
sx={{ mt: 0.75, fontWeight: 700 }}
|
||||
/>
|
||||
</Box>
|
||||
{depositEnabled ? (
|
||||
{anyDeposit ? (
|
||||
<IconButton size="small" aria-label={t('wallet.mainCard.receiveAria')} onClick={onReceive}>
|
||||
<QrCode2RoundedIcon fontSize="small" />
|
||||
</IconButton>
|
||||
@ -99,24 +73,33 @@ export function MainAssetCard({ balance, onReceive, onSend }: MainAssetCardProps
|
||||
{t('wallet.mainCard.availableBalance')}
|
||||
</Typography>
|
||||
<Typography variant="h5" sx={{ fontWeight: 900 }}>
|
||||
{formatBalance(balance.available, balance.walletType.decimals, code)}
|
||||
{formatBalance(balance.available, balance.walletType.decimals, 'USDT')}
|
||||
</Typography>
|
||||
|
||||
{hasLocked && (
|
||||
<Typography variant="body2" sx={{ opacity: 0.65, mt: 0.5 }}>
|
||||
{t('wallet.mainCard.locked')}{' '}
|
||||
{formatBalance(balance.locked, balance.walletType.decimals, code)}
|
||||
{formatBalance(balance.locked, balance.walletType.decimals, 'USDT')}
|
||||
</Typography>
|
||||
)}
|
||||
|
||||
{!depositEnabled && (
|
||||
<Typography variant="body2" color="warning.main" sx={{ mt: 1 }}>
|
||||
{t('wallet.mainCard.depositsDisabledHint')}
|
||||
</Typography>
|
||||
)}
|
||||
<Stack spacing={0.75} sx={{ mt: 1.5 }}>
|
||||
{networks.map((n) => (
|
||||
<Typography key={n.code} variant="body2" sx={{ opacity: 0.75 }}>
|
||||
{networkLabel(n.code)}:{' '}
|
||||
{n.depositEnabled
|
||||
? t('wallet.mainCard.depositsOn')
|
||||
: t('wallet.mainCard.depositsOff')}
|
||||
{' · '}
|
||||
{n.withdrawEnabled
|
||||
? t('wallet.mainCard.withdrawalsOn')
|
||||
: t('wallet.mainCard.withdrawalsOff')}
|
||||
</Typography>
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
<Stack direction="row" spacing={1} sx={{ mt: 2 }}>
|
||||
<Button size="small" variant="contained" onClick={onReceive} disabled={!depositEnabled}>
|
||||
<Button size="small" variant="contained" onClick={onReceive} disabled={!anyDeposit}>
|
||||
{t('wallet.mainCard.receive')}
|
||||
</Button>
|
||||
<Button size="small" variant="outlined" onClick={onSend}>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Receive (deposit) dialog — choose TRC20 or BEP20 when enabled.
|
||||
* Receive (deposit) dialog — choose TRC20 or BEP20 custody rail when depositEnabled.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -24,7 +24,6 @@ import { useEffect, useMemo, useState } from 'react';
|
||||
import { Trans, useTranslation } from 'react-i18next';
|
||||
import { useBalances, useDepositAddress } from '../hooks/useWalletData';
|
||||
import { networkLabel } from '../utils/coinDisplay';
|
||||
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from '../utils/walletCapabilities';
|
||||
|
||||
type ReceiveDialogProps = {
|
||||
open: boolean;
|
||||
@ -36,29 +35,23 @@ type ReceiveDialogProps = {
|
||||
export function ReceiveDialog({ open, onClose, onCopied, initialAsset }: ReceiveDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const balancesQ = useBalances();
|
||||
const depositOptions = useMemo(() => {
|
||||
const rows = balancesQ.data ?? [];
|
||||
return rows.filter(
|
||||
(b) =>
|
||||
(b.walletType.code === USDT_TRC20_CODE || b.walletType.code === USDT_BEP20_CODE) &&
|
||||
b.walletType.depositEnabled === true
|
||||
);
|
||||
}, [balancesQ.data]);
|
||||
const depositOptions = useMemo(
|
||||
() => (balancesQ.data?.networks ?? []).filter((n) => n.depositEnabled === true),
|
||||
[balancesQ.data]
|
||||
);
|
||||
|
||||
const [asset, setAsset] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
void balancesQ.refetch();
|
||||
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps -- refetch when dialog opens
|
||||
}, [open]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const preferred =
|
||||
(initialAsset && depositOptions.some((b) => b.walletType.code === initialAsset)
|
||||
? initialAsset
|
||||
: null) ??
|
||||
depositOptions[0]?.walletType.code ??
|
||||
(initialAsset && depositOptions.some((n) => n.code === initialAsset) ? initialAsset : null) ??
|
||||
depositOptions[0]?.code ??
|
||||
'';
|
||||
setAsset(preferred);
|
||||
}, [open, initialAsset, depositOptions]);
|
||||
@ -81,6 +74,10 @@ export function ReceiveDialog({ open, onClose, onCopied, initialAsset }: Receive
|
||||
<DialogTitle sx={{ fontWeight: 900 }}>{t('wallet.receiveDialog.title')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Stack spacing={2.5} sx={{ pt: 0.5 }}>
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
{t('wallet.receiveDialog.unifiedLedgerHint')}
|
||||
</Alert>
|
||||
|
||||
{depositOptions.length === 0 ? (
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
{t('wallet.receiveDialog.noNetworks')}
|
||||
@ -94,9 +91,9 @@ export function ReceiveDialog({ open, onClose, onCopied, initialAsset }: Receive
|
||||
value={asset}
|
||||
onChange={(e) => setAsset(e.target.value)}
|
||||
>
|
||||
{depositOptions.map((b) => (
|
||||
<MenuItem key={b.walletType.code} value={b.walletType.code}>
|
||||
{b.walletType.name} — {networkLabel(b.walletType.code)}
|
||||
{depositOptions.map((n) => (
|
||||
<MenuItem key={n.code} value={n.code}>
|
||||
{networkLabel(n.code)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/**
|
||||
* On-chain withdrawal dialog for the wallet page.
|
||||
* On-chain withdrawal dialog — unified USDT ledger; payout rail is any enabled network.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
@ -23,16 +23,17 @@ import { Link as RouterLink } from 'react-router-dom';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import { apiErrorMessage } from '../../../shared/utils/apiError';
|
||||
import { useProfile } from '../../profile/hooks/useProfile';
|
||||
import type { BalanceEntry } from '../types';
|
||||
import { addressPlaceholder, networkLabel, scaleWithdrawalFeeRaw } from '../utils/coinDisplay';
|
||||
import type { BalanceEntry, NetworkBalanceInfo } from '../types';
|
||||
import { addressPlaceholder, networkLabel } from '../utils/coinDisplay';
|
||||
import { formatBalance, humanToRaw, rawToHuman, shortSymbol } from '../utils/walletFormat';
|
||||
|
||||
type WithdrawDialogProps = {
|
||||
open: boolean;
|
||||
balances: BalanceEntry[];
|
||||
spendable: BalanceEntry | null;
|
||||
networks: NetworkBalanceInfo[];
|
||||
withdrawalsEnabled: boolean;
|
||||
networkFeeRaw: string;
|
||||
initialAsset?: string | null;
|
||||
initialRail?: string | null;
|
||||
onClose: () => void;
|
||||
onSuccess?: (message: string) => void;
|
||||
onError?: (message: string) => void;
|
||||
@ -40,10 +41,11 @@ type WithdrawDialogProps = {
|
||||
|
||||
export function WithdrawDialog({
|
||||
open,
|
||||
balances,
|
||||
spendable,
|
||||
networks,
|
||||
withdrawalsEnabled,
|
||||
networkFeeRaw,
|
||||
initialAsset,
|
||||
initialRail,
|
||||
onClose,
|
||||
onSuccess,
|
||||
onError,
|
||||
@ -51,16 +53,16 @@ export function WithdrawDialog({
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const profileQ = useProfile();
|
||||
const [asset, setAsset] = useState('');
|
||||
const [rail, setRail] = useState('');
|
||||
const [toAddress, setToAddress] = useState('');
|
||||
const [amount, setAmount] = useState('');
|
||||
const [totpCode, setTotpCode] = useState('');
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const withdrawBalances = useMemo(
|
||||
() => balances.filter((b) => b.walletType.withdrawEnabled === true),
|
||||
[balances]
|
||||
const withdrawRails = useMemo(
|
||||
() => networks.filter((n) => n.withdrawEnabled === true),
|
||||
[networks]
|
||||
);
|
||||
|
||||
const policyQ = useQuery({
|
||||
@ -76,55 +78,55 @@ export function WithdrawDialog({
|
||||
const totpEnabled = profileQ.data?.totpEnabled ?? false;
|
||||
const needs2faSetup = requireWithdrawal2fa && !totpEnabled;
|
||||
|
||||
const decimals = spendable?.walletType.decimals ?? 6;
|
||||
|
||||
const feeRaw = useMemo(() => {
|
||||
try {
|
||||
const n = BigInt((networkFeeRaw || '0').trim() || '0');
|
||||
return n >= 0n ? n : 0n;
|
||||
} catch {
|
||||
return 0n;
|
||||
}
|
||||
}, [networkFeeRaw]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setAsset(initialAsset ?? withdrawBalances[0]?.walletType.code ?? '');
|
||||
setRail(initialRail ?? withdrawRails[0]?.code ?? '');
|
||||
setToAddress('');
|
||||
setAmount('');
|
||||
setTotpCode('');
|
||||
setConfirmOpen(false);
|
||||
}
|
||||
}, [open, initialAsset, withdrawBalances]);
|
||||
}, [open, initialRail, withdrawRails]);
|
||||
|
||||
const selected = useMemo(
|
||||
() => withdrawBalances.find((b) => b.walletType.code === asset),
|
||||
[withdrawBalances, asset]
|
||||
const selectedRail = useMemo(
|
||||
() => withdrawRails.find((n) => n.code === rail),
|
||||
[withdrawRails, rail]
|
||||
);
|
||||
|
||||
const feeRaw = useMemo(() => {
|
||||
if (!selected) return 0n;
|
||||
return scaleWithdrawalFeeRaw(networkFeeRaw, selected.walletType.decimals);
|
||||
}, [networkFeeRaw, selected]);
|
||||
|
||||
const amountRaw = useMemo(() => {
|
||||
if (!selected) return 0n;
|
||||
try {
|
||||
return BigInt(humanToRaw(amount, selected.walletType.decimals));
|
||||
return BigInt(humanToRaw(amount, decimals));
|
||||
} catch {
|
||||
return 0n;
|
||||
}
|
||||
}, [amount, selected]);
|
||||
}, [amount, decimals]);
|
||||
|
||||
const totalDebitRaw = amountRaw + feeRaw;
|
||||
const availableRaw = useMemo(() => {
|
||||
if (!selected) return 0n;
|
||||
if (!spendable) return 0n;
|
||||
try {
|
||||
return BigInt(selected.available);
|
||||
return BigInt(spendable.available);
|
||||
} catch {
|
||||
return 0n;
|
||||
}
|
||||
}, [selected]);
|
||||
}, [spendable]);
|
||||
|
||||
const feeLabel = selected
|
||||
? `${rawToHuman(feeRaw.toString(), selected.walletType.decimals)} ${shortSymbol(asset)}`
|
||||
: rawToHuman(networkFeeRaw, 6);
|
||||
|
||||
const totalDebitLabel = selected
|
||||
? `${rawToHuman(totalDebitRaw.toString(), selected.walletType.decimals)} ${shortSymbol(asset)}`
|
||||
: '';
|
||||
const feeLabel = `${rawToHuman(feeRaw.toString(), decimals)} USDT`;
|
||||
const totalDebitLabel = `${rawToHuman(totalDebitRaw.toString(), decimals)} USDT`;
|
||||
|
||||
const submit = async () => {
|
||||
if (!selected) return;
|
||||
if (!spendable || !selectedRail) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const res = await api.post<{
|
||||
@ -132,17 +134,15 @@ export function WithdrawDialog({
|
||||
fee?: string;
|
||||
totalDebited?: string;
|
||||
}>('/api/v1/withdraw', {
|
||||
walletType: asset,
|
||||
walletType: rail,
|
||||
toAddress: toAddress.trim(),
|
||||
amount: humanToRaw(amount, selected.walletType.decimals),
|
||||
amount: humanToRaw(amount, decimals),
|
||||
totpCode: totpCode.trim() || undefined,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
const feeHuman =
|
||||
res.data.fee && res.data.fee !== '0'
|
||||
? rawToHuman(res.data.fee, selected.walletType.decimals)
|
||||
: null;
|
||||
res.data.fee && res.data.fee !== '0' ? rawToHuman(res.data.fee, decimals) : null;
|
||||
onSuccess?.(
|
||||
feeHuman
|
||||
? t('wallet.withdrawDialog.successWithFee', { fee: feeHuman })
|
||||
@ -154,6 +154,8 @@ export function WithdrawDialog({
|
||||
const apiErr = err?.response?.data;
|
||||
if (apiErr?.code === 'WITHDRAWAL_2FA_REQUIRED' || /2FA must be enabled/i.test(apiErr?.error ?? '')) {
|
||||
onError?.(t('wallet.withdrawDialog.twoFaRequiredError'));
|
||||
} else if (apiErr?.code === 'HOT_WALLET_INSUFFICIENT_LIQUIDITY') {
|
||||
onError?.(t('wallet.withdrawDialog.liquidityError'));
|
||||
} else {
|
||||
onError?.(apiErrorMessage(err, t('common.withdrawalFailed')));
|
||||
}
|
||||
@ -163,13 +165,14 @@ export function WithdrawDialog({
|
||||
}
|
||||
};
|
||||
|
||||
const insufficientFunds = amountRaw > 0n && feeRaw >= 0n && availableRaw < totalDebitRaw;
|
||||
const insufficientFunds = amountRaw > 0n && availableRaw < totalDebitRaw;
|
||||
|
||||
const totpOk = !requireWithdrawal2fa || (totpEnabled && totpCode.trim().length === 6);
|
||||
|
||||
const canProceed =
|
||||
withdrawalsEnabled &&
|
||||
!!selected &&
|
||||
!!selectedRail &&
|
||||
!!spendable &&
|
||||
toAddress.trim().length > 8 &&
|
||||
amountRaw > 0n &&
|
||||
!insufficientFunds &&
|
||||
@ -177,9 +180,7 @@ export function WithdrawDialog({
|
||||
totpOk;
|
||||
|
||||
const feePart =
|
||||
feeRaw > 0n && selected
|
||||
? t('wallet.withdrawDialog.networkFeePart', { fee: feeLabel })
|
||||
: '';
|
||||
feeRaw > 0n ? t('wallet.withdrawDialog.networkFeePart', { fee: feeLabel }) : '';
|
||||
|
||||
const totpLabel = requireWithdrawal2fa
|
||||
? t('wallet.withdrawDialog.totpRequired')
|
||||
@ -197,7 +198,7 @@ export function WithdrawDialog({
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{withdrawBalances.length === 0 && (
|
||||
{withdrawRails.length === 0 && (
|
||||
<Alert severity="warning" sx={{ borderRadius: 2 }}>
|
||||
{t('wallet.withdrawDialog.noNetworks')}
|
||||
</Alert>
|
||||
@ -214,6 +215,10 @@ export function WithdrawDialog({
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
{t('wallet.withdrawDialog.crossNetworkHint')}
|
||||
</Alert>
|
||||
|
||||
<Alert severity="error" variant="outlined" sx={{ borderRadius: 2 }}>
|
||||
{t('wallet.withdrawDialog.networkWarning')}
|
||||
</Alert>
|
||||
@ -224,37 +229,32 @@ export function WithdrawDialog({
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<FormControl fullWidth disabled={!withdrawalsEnabled || needs2faSetup || withdrawBalances.length === 0}>
|
||||
<InputLabel id="withdraw-asset-label">{t('common.asset')}</InputLabel>
|
||||
<FormControl fullWidth disabled={!withdrawalsEnabled || needs2faSetup || withdrawRails.length === 0}>
|
||||
<InputLabel id="withdraw-rail-label">{t('wallet.withdrawDialog.payoutNetwork')}</InputLabel>
|
||||
<Select
|
||||
labelId="withdraw-asset-label"
|
||||
label={t('common.asset')}
|
||||
value={asset}
|
||||
onChange={(e) => setAsset(e.target.value)}
|
||||
labelId="withdraw-rail-label"
|
||||
label={t('wallet.withdrawDialog.payoutNetwork')}
|
||||
value={rail}
|
||||
onChange={(e) => setRail(e.target.value)}
|
||||
>
|
||||
{withdrawBalances.map((b) => (
|
||||
<MenuItem key={b.walletType.code} value={b.walletType.code}>
|
||||
{b.walletType.name} — {networkLabel(b.walletType.code)}
|
||||
{withdrawRails.map((n) => (
|
||||
<MenuItem key={n.code} value={n.code}>
|
||||
{networkLabel(n.code)} —{' '}
|
||||
{t('wallet.withdrawDialog.withdrawable', {
|
||||
amount: rawToHuman(n.withdrawable, decimals),
|
||||
})}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
<Alert severity="info" sx={{ borderRadius: 2 }}>
|
||||
<Trans
|
||||
i18nKey="wallet.withdrawDialog.networkFixed"
|
||||
values={{ network: networkLabel(asset) }}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
</Alert>
|
||||
|
||||
<TextField
|
||||
label={t('wallet.withdrawDialog.destinationAddress')}
|
||||
fullWidth
|
||||
value={toAddress}
|
||||
onChange={(e) => setToAddress(e.target.value)}
|
||||
disabled={!withdrawalsEnabled || needs2faSetup}
|
||||
placeholder={addressPlaceholder(asset)}
|
||||
placeholder={addressPlaceholder(rail)}
|
||||
slotProps={{
|
||||
htmlInput: { style: { fontFamily: 'monospace', fontSize: 13 } },
|
||||
}}
|
||||
@ -269,15 +269,11 @@ export function WithdrawDialog({
|
||||
disabled={!withdrawalsEnabled || needs2faSetup}
|
||||
error={insufficientFunds}
|
||||
helperText={
|
||||
selected
|
||||
spendable
|
||||
? insufficientFunds
|
||||
? t('wallet.withdrawDialog.insufficient', { total: totalDebitLabel })
|
||||
: t('wallet.withdrawDialog.availableWithFee', {
|
||||
available: formatBalance(
|
||||
selected.available,
|
||||
selected.walletType.decimals,
|
||||
asset
|
||||
),
|
||||
available: formatBalance(spendable.available, decimals, 'USDT'),
|
||||
feePart,
|
||||
})
|
||||
: undefined
|
||||
@ -323,8 +319,8 @@ export function WithdrawDialog({
|
||||
i18nKey="wallet.withdrawDialog.receiveOnNetwork"
|
||||
values={{
|
||||
amount,
|
||||
asset: shortSymbol(asset),
|
||||
network: networkLabel(asset),
|
||||
asset: shortSymbol('USDT'),
|
||||
network: networkLabel(rail),
|
||||
}}
|
||||
components={{ b: <b /> }}
|
||||
/>
|
||||
|
||||
@ -4,7 +4,13 @@
|
||||
*/
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import type { BalanceEntry, DepositAddressResponse, WalletActivityCategory, WalletTransaction } from '../types';
|
||||
import type {
|
||||
BalanceEntry,
|
||||
BalancesResponse,
|
||||
DepositAddressResponse,
|
||||
WalletActivityCategory,
|
||||
WalletTransaction,
|
||||
} from '../types';
|
||||
|
||||
export type PaginatedTransactions = {
|
||||
items: WalletTransaction[];
|
||||
@ -13,13 +19,40 @@ export type PaginatedTransactions = {
|
||||
offset: number;
|
||||
};
|
||||
|
||||
/** Fetches the authenticated user's ledger balances (includes deposit/withdraw flags). */
|
||||
function normalizeBalancesPayload(data: unknown): BalancesResponse {
|
||||
if (Array.isArray(data)) {
|
||||
const balances = data as BalanceEntry[];
|
||||
const spendable = balances[0];
|
||||
return {
|
||||
spendable: spendable ?? {
|
||||
walletType: {
|
||||
id: 0,
|
||||
code: 'USDT_TRC20',
|
||||
name: 'USDT',
|
||||
network: 'TRON',
|
||||
decimals: 6,
|
||||
contract_address: null,
|
||||
},
|
||||
available: '0',
|
||||
locked: '0',
|
||||
bonusAvailable: '0',
|
||||
testAvailable: '0',
|
||||
},
|
||||
inventory: { TRON: '0', BSC: '0' },
|
||||
networks: [],
|
||||
balances,
|
||||
};
|
||||
}
|
||||
return data as BalancesResponse;
|
||||
}
|
||||
|
||||
/** Fetches unified USDT ledger + network inventory. */
|
||||
export function useBalances() {
|
||||
return useQuery({
|
||||
queryKey: ['wallet-balances'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<BalanceEntry[]>('/api/v1/balances');
|
||||
return res.data;
|
||||
const res = await api.get<BalancesResponse | BalanceEntry[]>('/api/v1/balances');
|
||||
return normalizeBalancesPayload(res.data);
|
||||
},
|
||||
staleTime: 0,
|
||||
refetchOnMount: 'always',
|
||||
@ -35,19 +68,21 @@ type LiveBalancesOptions = {
|
||||
|
||||
/**
|
||||
* Balances with optional polling — for pages that need live stake wallet updates.
|
||||
* Exposes `.balances` array for stake label helpers (spendable ledger only).
|
||||
*/
|
||||
export function useLiveBalances(options: LiveBalancesOptions = {}) {
|
||||
const { refetchIntervalMs = false, enabled = true } = options;
|
||||
return useQuery({
|
||||
queryKey: ['wallet-balances'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<BalanceEntry[]>('/api/v1/balances');
|
||||
return res.data;
|
||||
const res = await api.get<BalancesResponse | BalanceEntry[]>('/api/v1/balances');
|
||||
return normalizeBalancesPayload(res.data);
|
||||
},
|
||||
enabled,
|
||||
refetchInterval: refetchIntervalMs === false ? false : refetchIntervalMs,
|
||||
refetchOnWindowFocus: true,
|
||||
staleTime: 2_000,
|
||||
select: (data) => data.balances,
|
||||
});
|
||||
}
|
||||
|
||||
@ -55,8 +90,6 @@ const DEFAULT_TX_PAGE_SIZE = 10;
|
||||
|
||||
/**
|
||||
* Fetches paginated transaction history for the wallet activity panel.
|
||||
* @param page Zero-based page index
|
||||
* @param pageSize Rows per page (default 10)
|
||||
*/
|
||||
export function useTransactions(
|
||||
page: number,
|
||||
@ -78,9 +111,7 @@ export function useTransactions(
|
||||
export { DEFAULT_TX_PAGE_SIZE };
|
||||
|
||||
/**
|
||||
* Fetches a deposit address for the given wallet type code.
|
||||
* @param walletType Asset code (USDT_TRC20)
|
||||
* @param enabled When false, the query does not run
|
||||
* Fetches a deposit address for the given wallet type code (custody rail).
|
||||
*/
|
||||
export function useDepositAddress(walletType: string | null, enabled: boolean) {
|
||||
return useQuery({
|
||||
|
||||
@ -18,7 +18,7 @@ export type WalletType = {
|
||||
predictionEnabled?: boolean;
|
||||
};
|
||||
|
||||
/** User balance row from GET /balances. */
|
||||
/** User balance row from GET /balances (spendable ledger entry). */
|
||||
export type BalanceEntry = {
|
||||
walletType: WalletType;
|
||||
available: string;
|
||||
@ -27,6 +27,25 @@ export type BalanceEntry = {
|
||||
testAvailable?: string;
|
||||
};
|
||||
|
||||
/** Per-network custody / withdraw rail info from GET /balances. */
|
||||
export type NetworkBalanceInfo = {
|
||||
code: string;
|
||||
network: string;
|
||||
depositEnabled: boolean;
|
||||
withdrawEnabled: boolean;
|
||||
inventory: string;
|
||||
withdrawable: string;
|
||||
};
|
||||
|
||||
/** Full balances payload (unified ledger; inventory is ops telemetry). */
|
||||
export type BalancesResponse = {
|
||||
spendable: BalanceEntry;
|
||||
inventory: { TRON: string; BSC: string };
|
||||
networks: NetworkBalanceInfo[];
|
||||
/** Compatibility: usually `[spendable]` only. */
|
||||
balances: BalanceEntry[];
|
||||
};
|
||||
|
||||
/** Deposit address response from GET /deposit-address/:walletType. */
|
||||
export type DepositAddressResponse = {
|
||||
address: string;
|
||||
|
||||
@ -299,10 +299,11 @@ export const en = {
|
||||
wallet: {
|
||||
title: 'Wallet',
|
||||
subtitle:
|
||||
'Deposit <b>USDT</b> on <b>TRON (TRC20)</b> or <b>BSC (BEP20)</b>. Candle Predict stakes use your TRC20 balance.',
|
||||
'Deposit <b>USDT</b> on <b>TRON (TRC20)</b> or <b>BSC (BEP20)</b>. Your spendable balance is unified for Candle Predict; withdraw on either enabled network (subject to platform liquidity).',
|
||||
refreshWallet: 'Refresh wallet',
|
||||
loadError: 'Failed to load balances. Make sure you are logged in and the API is running.',
|
||||
mainBalance: 'USDT balances by network',
|
||||
mainBalance: 'Spendable USDT',
|
||||
inventorySummary: 'inventory {{inventory}} · withdrawable {{withdrawable}}',
|
||||
locked: '{{amount}} locked',
|
||||
noBalance: 'No balance yet — receive USDT to get started.',
|
||||
receiveUsdt: 'Receive USDT',
|
||||
@ -318,10 +319,13 @@ export const en = {
|
||||
},
|
||||
receiveDialog: {
|
||||
title: 'Receive USDT',
|
||||
network: 'Network',
|
||||
network: 'Deposit network',
|
||||
unifiedLedgerHint:
|
||||
'Funds credited from either network increase your single USDT balance used for Candle Predict.',
|
||||
noNetworks: 'No deposit networks are enabled right now. Contact support or try again later.',
|
||||
info: 'Send <b>USDT</b> on <b>{{network}}</b> only. Wrong network may result in permanent loss.',
|
||||
wrongNetwork: 'Use the exact network shown above (TRC20 ≠ BEP20). Wrong network transfers cannot be recovered.',
|
||||
wrongNetwork:
|
||||
'Use the exact network shown above (TRC20 ≠ BEP20). Wrong network transfers cannot be recovered.',
|
||||
loadAddressFailed: 'Failed to load deposit address',
|
||||
copyAddressAria: 'Copy address',
|
||||
confirmationsHint: 'Deposits are credited after the required on-chain confirmations.',
|
||||
@ -347,6 +351,15 @@ export const en = {
|
||||
networkWarning: 'Double-check the destination address and network. Wrong network transfers are irreversible.',
|
||||
networkFee: 'A network fee of <b>{{fee}}</b> is deducted from your balance in addition to the withdrawal amount (covers on-chain gas).',
|
||||
networkFixed: 'Network: <b>{{network}}</b> (cannot be changed)',
|
||||
payoutNetwork: 'Payout network',
|
||||
withdrawable: 'up to {{amount}} USDT',
|
||||
crossNetworkHint:
|
||||
'You can withdraw on TRON or BSC regardless of where you deposited. Wins count toward your spendable USDT. If a network is temporarily unavailable, the platform hot wallet may need more USDT or gas — try the other network or retry later.',
|
||||
liquidityError:
|
||||
'Withdrawals on this network are temporarily unavailable (platform liquidity). Try the other network or try again later.',
|
||||
inventoryHint:
|
||||
'You can only withdraw on a network up to your inventory on that network (from deposits there). Game wins increase your spendable USDT but may not increase network inventory.',
|
||||
inventoryError: 'Not enough inventory on the selected network for this withdrawal.',
|
||||
noNetworks: 'No withdrawal networks are enabled right now.',
|
||||
destinationAddress: 'Destination address',
|
||||
amountToReceive: 'Amount to receive',
|
||||
@ -371,13 +384,15 @@ export const en = {
|
||||
successWithFee: 'Withdrawal submitted successfully (fee {{fee}} USDT)',
|
||||
},
|
||||
mainCard: {
|
||||
title: 'Main wallet',
|
||||
title: 'USDT wallet',
|
||||
badge: 'Deposits & withdrawals',
|
||||
unifiedSubtitle: 'Single spendable balance for predictions',
|
||||
depositsOn: 'Deposits on',
|
||||
depositsOff: 'Deposits off',
|
||||
withdrawalsOn: 'Withdrawals on',
|
||||
withdrawalsOff: 'Withdrawals off',
|
||||
predictionBadge: 'Candle Predict',
|
||||
inventoryLine: 'inventory {{inventory}} · withdrawable {{withdrawable}}',
|
||||
depositsDisabledHint:
|
||||
'Deposits are disabled for this network by the platform. Do not send funds to an old address for this network.',
|
||||
availableBalance: 'Available balance',
|
||||
|
||||
@ -306,11 +306,12 @@ export const fr = {
|
||||
wallet: {
|
||||
title: 'Portefeuille',
|
||||
subtitle:
|
||||
'Déposez des <b>USDT</b> sur <b>TRON (TRC20)</b> ou <b>BSC (BEP20)</b>. Les mises Candle Predict utilisent votre solde TRC20.',
|
||||
'Déposez des <b>USDT</b> sur <b>TRON (TRC20)</b> ou <b>BSC (BEP20)</b>. Votre solde jouable est unifié pour Candle Predict ; retirez sur n’importe quel réseau activé (selon la liquidité plateforme).',
|
||||
refreshWallet: 'Actualiser le portefeuille',
|
||||
loadError:
|
||||
'Impossible de charger les soldes. Vérifiez que vous êtes connecté et que l’API est active.',
|
||||
mainBalance: 'Soldes USDT par réseau',
|
||||
mainBalance: 'USDT disponible',
|
||||
inventorySummary: 'inventaire {{inventory}} · retirable {{withdrawable}}',
|
||||
locked: '{{amount}} bloqué',
|
||||
noBalance: 'Aucun solde — recevez des USDT pour commencer.',
|
||||
receiveUsdt: 'Recevoir USDT',
|
||||
@ -326,7 +327,9 @@ export const fr = {
|
||||
},
|
||||
receiveDialog: {
|
||||
title: 'Recevoir USDT',
|
||||
network: 'Réseau',
|
||||
network: 'Réseau de dépôt',
|
||||
unifiedLedgerHint:
|
||||
'Les fonds crédités depuis n’importe quel réseau augmentent votre solde USDT unique utilisé pour Candle Predict.',
|
||||
noNetworks: 'Aucun réseau de dépôt n’est activé pour le moment. Contactez le support ou réessayez plus tard.',
|
||||
info: 'Envoyez des <b>USDT</b> sur <b>{{network}}</b> uniquement. Un mauvais réseau peut entraîner une perte définitive.',
|
||||
wrongNetwork:
|
||||
@ -356,6 +359,15 @@ export const fr = {
|
||||
networkWarning: 'Vérifiez l’adresse et le réseau de destination. Les transferts sur le mauvais réseau sont irréversibles.',
|
||||
networkFee: 'Des frais réseau de <b>{{fee}}</b> sont déduits de votre solde en plus du montant du retrait (couvre le gas on-chain).',
|
||||
networkFixed: 'Réseau : <b>{{network}}</b> (non modifiable)',
|
||||
payoutNetwork: 'Réseau de paiement',
|
||||
withdrawable: 'jusqu’à {{amount}} USDT',
|
||||
crossNetworkHint:
|
||||
'Vous pouvez retirer sur TRON ou BSC indépendamment du réseau de dépôt. Les gains comptent dans votre solde USDT. Si un réseau est temporairement indisponible, le hot wallet plateforme peut manquer d’USDT ou de gas — essayez l’autre réseau ou réessayez plus tard.',
|
||||
liquidityError:
|
||||
'Les retraits sur ce réseau sont temporairement indisponibles (liquidité plateforme). Essayez l’autre réseau ou réessayez plus tard.',
|
||||
inventoryHint:
|
||||
'Vous ne pouvez retirer sur un réseau que jusqu’à votre inventaire sur ce réseau (issu des dépôts). Les gains de jeu augmentent le solde jouable mais pas forcément l’inventaire réseau.',
|
||||
inventoryError: 'Inventaire insuffisant sur le réseau sélectionné pour ce retrait.',
|
||||
noNetworks: 'Aucun réseau de retrait n’est activé pour le moment.',
|
||||
destinationAddress: 'Adresse de destination',
|
||||
amountToReceive: 'Montant à recevoir',
|
||||
@ -366,7 +378,7 @@ export const fr = {
|
||||
twoFaRequiredError: 'La 2FA doit être activée avant de retirer. Activez-la dans les paramètres de votre profil.',
|
||||
enableTwoFa: 'Activer la 2FA dans le profil',
|
||||
totpPlaceholder: 'Code à 6 chiffres',
|
||||
insufficient: 'Solde insuffisant — besoin de {{total}} (montant + frais réseau)',
|
||||
insufficient: 'Solde insuffisant — besoin de {{total}} (montant + frais)',
|
||||
availableWithFee: 'Disponible : {{available}}{{feePart}}',
|
||||
networkFeePart: ' · Frais réseau : {{fee}}',
|
||||
review: 'Vérifier le retrait',
|
||||
@ -380,13 +392,15 @@ export const fr = {
|
||||
successWithFee: 'Retrait soumis avec succès (frais {{fee}} USDT)',
|
||||
},
|
||||
mainCard: {
|
||||
title: 'Portefeuille principal',
|
||||
title: 'Portefeuille USDT',
|
||||
badge: 'Dépôts et retraits',
|
||||
unifiedSubtitle: 'Solde jouable unique pour les prédictions',
|
||||
depositsOn: 'Dépôts activés',
|
||||
depositsOff: 'Dépôts désactivés',
|
||||
withdrawalsOn: 'Retraits activés',
|
||||
withdrawalsOff: 'Retraits désactivés',
|
||||
predictionBadge: 'Candle Predict',
|
||||
inventoryLine: 'inventaire {{inventory}} · retirable {{withdrawable}}',
|
||||
depositsDisabledHint:
|
||||
'Les dépôts sont désactivés pour ce réseau. N’envoyez pas de fonds vers une ancienne adresse de ce réseau.',
|
||||
availableBalance: 'Solde disponible',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user