games_app/backend/dist/services/depositMonitorService.js
2026-06-29 15:01:23 +02:00

129 lines
6.0 KiB
JavaScript

"use strict";
/**
* Deposit scanner and crediting service.
* Polls TRON for incoming USDT (TRC20) transfers and credits user ledger accounts.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.processTronDeposits = processTronDeposits;
const config_1 = require("../config");
const connection_1 = require("../db/connection");
const walletRepository = __importStar(require("../repositories/walletRepository"));
const ledgerRepository = __importStar(require("../repositories/ledgerRepository"));
const transactionRepository = __importStar(require("../repositories/transactionRepository"));
const depositScannerRepository = __importStar(require("../repositories/depositScannerRepository"));
const auditLogRepository = __importStar(require("../repositories/auditLogRepository"));
const sweepService_1 = require("./sweepService");
const userAdminStatsService_1 = require("./userAdminStatsService");
const referralService = __importStar(require("./referralService"));
const walletCapabilities_1 = require("./walletCapabilities");
const tronService = __importStar(require("./blockchain/tronService"));
const TRON_CONFIRMATIONS = config_1.config.blockchain.tron.confirmations;
/** Scans TRON for new USDT TRC20 deposits and credits confirmed transfers. */
async function processTronDeposits() {
const walletType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_WALLET_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 (0, connection_1.query)('SELECT address, user_id FROM user_wallets WHERE wallet_type_id = $1', [walletType.id]);
if (userWallets.length > 0) {
const hasAnyUsdtTx = await (0, connection_1.query)('SELECT 1 as n FROM transactions WHERE wallet_type_id = $1 LIMIT 1', [walletType.id]).then((r) => r.length > 0);
if (!hasAnyUsdtTx && fromBlock > 0n) {
fromBlock = 0n;
if (process.env.NODE_ENV !== 'production') {
console.log('[deposit] USDT_TRC20: no deposits in DB yet, scanning from start');
}
}
}
const fromTimestamp = Number(fromBlock) * 3000;
const trc20Contract = config_1.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 } of userWallets) {
const transfers = await tronService.getTrc20TransfersToAddress(address, trc20Contract, fromTimestamp);
if (process.env.NODE_ENV !== 'production' && transfers.length > 0) {
console.log(`[deposit] USDT ${address}: ${transfers.length} transfer(s)`);
}
for (const t of transfers) {
if (t.confirmations >= TRON_CONFIRMATIONS) {
await creditDeposit(user_id, walletType.id, BigInt(t.value), t.txId, t.from, address, t.confirmations);
}
}
}
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
}
async function creditDeposit(userId, walletTypeId, amount, blockchainTxId, fromAddress, toAddress, block) {
const existing = await transactionRepository.findByBlockchainTxId(blockchainTxId);
if (existing)
return;
const account = await ledgerRepository.getOrCreateAccount(userId, walletTypeId, 'main');
const tx = await transactionRepository.create({
userId,
walletTypeId,
type: 'deposit',
amount,
status: 'completed',
blockchainTxId,
fromAddress,
toAddress,
confirmations: block,
requiredConfirmations: TRON_CONFIRMATIONS,
});
await ledgerRepository.credit(account.id, amount, 'deposit', 'transaction', tx.id);
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 (0, sweepService_1.enqueueSweepAfterDeposit)(userId, walletTypeId, amount, tx.id);
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
}
//# sourceMappingURL=depositMonitorService.js.map