games_app/backend/src/services/depositMonitorService.ts
2026-08-25 17:59:10 +02:00

294 lines
10 KiB
TypeScript

/**
* Deposit scanner and crediting service.
* 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';
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 networkInventoryRepository from '../repositories/networkInventoryRepository';
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';
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;
/** 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 custodyType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
const ledgerType = custodyType;
if (!custodyType || !ledgerType) return;
const currentBlock = await tronService.getCurrentBlock();
const state = await depositScannerRepository.getState(custodyType.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',
[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`,
[ledgerType.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 || custodyType.contract_address || '';
if (!trc20Contract) return;
if (process.env.NODE_ENV !== 'production') {
console.log(
`[deposit] USDT_TRC20 (id=${custodyType.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({
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);
}
}
}
}
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
}
/** 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 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(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',
[custodyType.id]
);
if (userWallets.length === 0) {
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
return;
}
if (fromBlock === 0) {
fromBlock = Math.max(0, currentBlock - 5_000);
}
const contract = bscService.resolveUsdtContract(custodyType.contract_address);
if (process.env.NODE_ENV !== 'production') {
console.log(
`[deposit] USDT_BEP20 (id=${custodyType.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;
const ledgerAmount = scaleChainToLedger(t.value, BEP20_USDT_DECIMALS, LEDGER_USDT_DECIMALS);
if (ledgerAmount <= 0n) continue;
try {
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,
requiredConfirmations: BSC_CONFIRMATIONS,
});
} catch (e) {
console.error(`[deposit] BEP20 credit failed tx=${t.txHash}:`, e);
}
}
}
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
}
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: 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');
return;
}
await ledgerRepository.creditUsingClient(
client,
account.id,
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');
throw e;
} finally {
client.release();
}
if (!tx) return;
await referralService.processFirstDepositReferralCommissions({
userId: opts.userId,
depositTransactionId: tx.id,
depositAmount: opts.ledgerAmount,
walletTypeId: opts.ledgerWalletTypeId,
});
await auditLogRepository.create({
userId: opts.userId,
action: 'deposit_confirmed',
resourceType: 'transaction',
resourceId: tx.id,
metadata: {
amount: opts.ledgerAmount.toString(),
chainAmount: opts.chainAmount.toString(),
network: opts.network,
sourceWalletType: opts.sourceWalletCode,
blockchainTxId: opts.blockchainTxId,
},
});
// Sweep uses custody type + on-chain amount
await enqueueSweepAfterDeposit(
opts.userId,
opts.custodyWalletTypeId,
opts.chainAmount,
tx.id
);
queueUserAdminStatsRefresh(opts.userId);
}