games_app/backend/src/services/depositMonitorService.ts
2026-08-24 13:41:54 +02:00

243 lines
7.9 KiB
TypeScript

/**
* Deposit scanner and crediting service.
* Polls TRON for incoming USDT (TRC20) transfers and credits user ledger accounts.
*/
import { config } from '../config';
import { query, getClient, beginAuthorizedTransaction } from '../db/connection';
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 auditLogRepository from '../repositories/auditLogRepository';
import { enqueueSweepAfterDeposit } from './sweepService';
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
import * as referralService from './referralService';
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';
const TRON_CONFIRMATIONS = config.blockchain.tron.confirmations;
const BSC_CONFIRMATIONS = config.blockchain.bsc.confirmations;
/** Scans TRON + BSC for new USDT deposits and credits confirmed transfers. */
export async function processAllDeposits(): Promise<void> {
await processTronDeposits();
await processBscDeposits();
}
/** Scans TRON for new USDT TRC20 deposits and credits confirmed transfers. */
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 currentBlock = await tronService.getCurrentBlock();
const state = await depositScannerRepository.getState(walletType.id);
let fromBlock = state ? BigInt(state.last_block) + 1n : 0n;
if (fromBlock > BigInt(currentBlock)) {
fromBlock = 0n;
}
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]
);
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]
).then((r) => r.length > 0);
if (!hasAnyUsdtDeposit && fromBlock > 0n) {
fromBlock = 0n;
if (process.env.NODE_ENV !== 'production') {
console.log('[deposit] USDT_TRC20: no deposit txs in DB yet, scanning from start');
}
}
}
let scannerMinTimestamp = 0;
if (fromBlock > 0n) {
const blockTs = await tronService.getBlockTimestamp(Number(fromBlock));
if (blockTs != null) scannerMinTimestamp = blockTs;
}
const trc20Contract =
config.blockchain.tron.usdtTrc20Contract || walletType.contract_address || '';
if (!trc20Contract) return;
if (process.env.NODE_ENV !== 'production') {
console.log(
`[deposit] USDT_TRC20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
);
}
for (const { address, user_id, created_at } of userWallets) {
const walletCreatedMs = new Date(created_at).getTime();
const minTimestamp = Math.max(scannerMinTimestamp, walletCreatedMs);
const transfers = await tronService.getTrc20TransfersToAddress(
address,
trc20Contract,
minTimestamp
);
if (process.env.NODE_ENV !== 'production' && transfers.length > 0) {
console.log(`[deposit] USDT TRC20 ${address}: ${transfers.length} transfer(s)`);
}
for (const t of transfers) {
const amount = tronService.parseTrc20TokenAmount(t.value);
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
);
} catch (e) {
console.error(`[deposit] TRC20 credit failed tx=${t.txId}:`, e);
}
}
}
}
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
}
/** Scans BSC for new USDT BEP20 deposits and credits confirmed transfers. */
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 currentBlock = await bscService.getCurrentBlock();
const state = await depositScannerRepository.getState(walletType.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]
);
if (userWallets.length === 0) {
await depositScannerRepository.updateState(walletType.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);
if (process.env.NODE_ENV !== 'production') {
console.log(
`[deposit] USDT_BEP20 (id=${walletType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}`
);
}
for (const { address, user_id } of userWallets) {
const transfers = await bscService.getUsdtTransfersToAddress(
address,
contract,
fromBlock,
currentBlock
);
for (const t of transfers) {
const confirmations = currentBlock - t.blockNumber + 1;
if (confirmations < BSC_CONFIRMATIONS) continue;
try {
await creditDeposit(
user_id,
walletType.id,
t.value,
t.txHash,
t.from,
address,
confirmations,
BSC_CONFIRMATIONS
);
} catch (e) {
console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e);
}
}
}
await depositScannerRepository.updateState(walletType.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');
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,
});
if (!tx) {
await client.query('COMMIT');
return;
}
await ledgerRepository.creditUsingClient(
client,
account.id,
amount,
'deposit',
'transaction',
tx.id
);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
if (!tx) return;
await referralService.processFirstDepositReferralCommissions({
userId,
depositTransactionId: tx.id,
depositAmount: amount,
walletTypeId,
});
await auditLogRepository.create({
userId,
action: 'deposit_confirmed',
resourceType: 'transaction',
resourceId: tx.id,
metadata: { amount: amount.toString(), blockchainTxId },
});
await enqueueSweepAfterDeposit(userId, walletTypeId, amount, tx.id);
queueUserAdminStatsRefresh(userId);
}