games_app/backend/dist/services/depositMonitorService.js

459 lines
22 KiB
JavaScript

"use strict";
/**
* 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.
*/
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.processAllDeposits = processAllDeposits;
exports.processTronDeposits = processTronDeposits;
exports.processBscDeposits = processBscDeposits;
exports.creditBscDepositByTxHash = creditBscDepositByTxHash;
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 networkInventoryRepository = __importStar(require("../repositories/networkInventoryRepository"));
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 bscService = __importStar(require("./blockchain/bscService"));
const settingsRepository = __importStar(require("../repositories/settingsRepository"));
const depositHdSnapshotRepository = __importStar(require("../repositories/depositHdSnapshotRepository"));
const usdtUnits_1 = require("../utils/usdtUnits");
const bscDepositScan_1 = require("../utils/bscDepositScan");
const TRON_CONFIRMATIONS = config_1.config.blockchain.tron.confirmations;
const BSC_CONFIRMATIONS = config_1.config.blockchain.bsc.confirmations;
/** Scans TRON + BSC for new USDT deposits and credits confirmed transfers. */
async function processAllDeposits() {
await processTronDeposits();
await processBscDeposits();
}
/** Scans TRON for new USDT TRC20 deposits and credits confirmed transfers. */
async function processTronDeposits() {
const settings = await settingsRepository.getSettings();
if (!settings.network_usdt_trc20_deposit_enabled)
return;
const custodyType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.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 (0, connection_1.query)('SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1', [custodyType.id]);
if (userWallets.length > 0) {
const hasAnyUsdtDeposit = await (0, connection_1.query)(`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_1.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: walletCapabilities_1.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);
}
}
}
}
for (const { address, user_id } of userWallets) {
try {
const bal = await tronService.getTrc20BalanceRaw(address, trc20Contract);
await depositHdSnapshotRepository.upsertSnapshot({
userId: user_id,
walletTypeId: custodyType.id,
address,
onChainAmount: bal,
});
}
catch (e) {
console.error(`[deposit] USDT_TRC20: balance snapshot failed for ${address}:`, e);
}
}
await depositScannerRepository.updateState(custodyType.id, BigInt(currentBlock));
}
/** Scans BSC for new USDT BEP20 deposits; credits unified ledger (6 dec) + BSC inventory. */
async function processBscDeposits() {
const settings = await settingsRepository.getSettings();
if (!settings.network_usdt_bep20_deposit_enabled) {
console.warn('[deposit] USDT_BEP20: deposit flag disabled — skipping scan');
return;
}
const custodyType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_BEP20_CODE);
const ledgerType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_TRC20_CODE);
if (!custodyType || !ledgerType) {
console.warn('[deposit] USDT_BEP20: wallet type(s) missing — skipping scan');
return;
}
const currentBlock = await bscService.getCurrentBlock();
const state = await depositScannerRepository.getState(custodyType.id);
const lastBlock = state ? Number(state.last_block) : null;
const userWallets = await (0, connection_1.query)('SELECT address, user_id, created_at FROM user_wallets WHERE wallet_type_id = $1', [custodyType.id]);
// Never advance the cursor with zero wallets — that permanently skips history
// once the first deposit address is created after a tip checkpoint.
if (userWallets.length === 0) {
console.warn('[deposit] USDT_BEP20: no deposit wallets yet — scanner idle');
return;
}
const initialLookback = config_1.config.blockchain.bsc.depositInitialLookbackBlocks;
const overlapLookback = config_1.config.blockchain.bsc.depositOverlapLookbackBlocks;
let fromBlock = (0, bscDepositScan_1.computeBscScanFromBlock)({
lastBlock,
currentBlock,
initialLookback,
overlapLookback,
});
const contract = bscService.resolveUsdtContract(custodyType.contract_address);
const custodyDecimals = custodyType.decimals ?? usdtUnits_1.BEP20_USDT_DECIMALS;
/** HD still holding USDT that is not yet covered by ledger deposits (needs credit recover). */
const uncreditedHd = new Set();
/** HD with any on-chain USDT (ops log / sweep path). */
let hdHoldingCount = 0;
for (const { address, user_id } of userWallets) {
try {
const bal = await bscService.getUsdtBalanceRaw(address, contract);
await depositHdSnapshotRepository.upsertSnapshot({
userId: user_id,
walletTypeId: custodyType.id,
address,
onChainAmount: bal,
});
if (bal <= 0n)
continue;
hdHoldingCount += 1;
const caughtUp = await depositHdSnapshotRepository.isAddressLedgerCaughtUp(address, bal, custodyDecimals);
if (!caughtUp)
uncreditedHd.add(address.toLowerCase());
}
catch (e) {
console.error(`[deposit] USDT_BEP20: balance check failed for ${address}:`, e);
}
}
if (hdHoldingCount > 0) {
console.warn(`[deposit] USDT_BEP20: ${hdHoldingCount} HD address(es) still hold USDT` +
(uncreditedHd.size > 0
? ` — ${uncreditedHd.size} not yet credited (recover)`
: ' — all already credited (awaiting sweep)'));
}
console.log(`[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}, tip=${currentBlock}`);
for (const { address, user_id } of userWallets) {
try {
const transfers = await bscService.getUsdtTransfersToAddress(address, contract, fromBlock, currentBlock);
if (transfers.length > 0) {
console.log(`[deposit] USDT_BEP20 ${address}: ${transfers.length} transfer(s) in window`);
}
for (const t of transfers) {
const confirmations = currentBlock - t.blockNumber + 1;
if (confirmations < BSC_CONFIRMATIONS)
continue;
const ledgerAmount = (0, usdtUnits_1.scaleChainToLedger)(t.value, usdtUnits_1.BEP20_USDT_DECIMALS, usdtUnits_1.LEDGER_USDT_DECIMALS);
if (ledgerAmount <= 0n)
continue;
try {
await creditDeposit({
userId: user_id,
ledgerWalletTypeId: ledgerType.id,
custodyWalletTypeId: custodyType.id,
network: 'BSC',
sourceWalletCode: walletCapabilities_1.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);
}
}
}
catch (e) {
console.error(`[deposit] USDT_BEP20 getLogs failed for ${address}:`, e);
}
}
// Receipt-based catch-up for HDs that still hold USDT (missed credit).
// Lookback must cover deposits missed while eth_getLogs was broken (days, not ~1 day).
// Newest-first scan stops once Transfer values cover the on-chain balance.
const unpaidLookback = Math.max(config_1.config.blockchain.bsc.unpaidLookbackBlocks, config_1.config.blockchain.bsc.depositInitialLookbackBlocks);
for (const { address } of userWallets) {
if (!uncreditedHd.has(address.toLowerCase()))
continue;
try {
const still = await bscService.getUsdtBalanceRaw(address, contract);
if (still <= 0n)
continue;
const recentFrom = Math.max(0, currentBlock - unpaidLookback);
console.warn(`[deposit] USDT_BEP20 unpaid recover for ${address} (on-chain=${still.toString()}) ` +
`lookback=${unpaidLookback} fromBlock=${recentFrom} tip=${currentBlock}`);
const hashes = new Set();
const viaExplorer = await bscService.listIncomingUsdtTxHashesViaExplorer(address, contract);
for (const h of viaExplorer)
hashes.add(h);
if (viaExplorer.length > 0) {
console.log(`[deposit] USDT_BEP20 unpaid explorer found ${viaExplorer.length} tx(s) for ${address}`);
}
try {
const recent = await bscService.getUsdtTransfersToAddressUntilValue(address, contract, recentFrom, currentBlock, still);
console.log(`[deposit] USDT_BEP20 unpaid getLogs hits=${recent.length} for ${address}`);
for (const t of recent)
hashes.add(t.txHash);
}
catch (e) {
console.warn(`[deposit] USDT_BEP20 unpaid getLogs failed for ${address}:`, e instanceof Error ? e.message : e);
}
if (hashes.size === 0) {
console.error(`[deposit] USDT_BEP20 unpaid ${address}: no tx hashes in blocks ${recentFrom}-${currentBlock}. ` +
`Set BSC_RPC_FALLBACKS (e.g. https://rpc-bsc.48.club) or BSCSCAN_API_KEY.`);
continue;
}
for (const txHash of hashes) {
const result = await creditBscDepositByTxHash(txHash);
if (result.credited) {
console.log(`[deposit] USDT_BEP20 recovered unpaid via tx=${txHash} user=${result.userId}`);
}
else if (result.alreadyCredited) {
// idempotent — expected when re-scanning
}
else if (result.reason && !/already|idempotent/i.test(result.reason)) {
console.warn(`[deposit] USDT_BEP20 unpaid recover skipped tx=${txHash}: ${result.reason}`);
}
}
}
catch (e) {
console.error(`[deposit] USDT_BEP20 unpaid recover failed for ${address}:`, e);
}
}
const committed = (0, bscDepositScan_1.computeBscCommittedScannerBlock)(currentBlock, BSC_CONFIRMATIONS);
await depositScannerRepository.updateState(custodyType.id, BigInt(committed));
}
/**
* Manually credit a confirmed BSC USDT transfer by tx hash (ops recovery).
* Safe to re-run: insertDepositIfNew is idempotent on blockchain_tx_id.
*/
async function creditBscDepositByTxHash(txHash) {
const settings = await settingsRepository.getSettings();
if (!settings.network_usdt_bep20_deposit_enabled) {
return { credited: false, reason: 'network_usdt_bep20_deposit_enabled is false' };
}
const custodyType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_BEP20_CODE);
const ledgerType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.USDT_TRC20_CODE);
if (!custodyType || !ledgerType) {
return { credited: false, reason: 'wallet types missing' };
}
const receipt = await bscService.getTransactionReceipt(txHash);
if (!receipt)
return { credited: false, reason: 'transaction not found' };
if (receipt.status !== 1)
return { credited: false, reason: 'transaction failed on-chain' };
const contract = bscService.resolveUsdtContract(custodyType.contract_address).toLowerCase();
const usdtTransfers = receipt.transfers.filter((t) => t.contract.toLowerCase() === contract);
if (usdtTransfers.length === 0) {
return { credited: false, reason: 'no USDT Transfer log for configured BEP20 contract' };
}
let wallet;
let transfer = usdtTransfers[0];
for (const t of usdtTransfers) {
const rows = await (0, connection_1.query)(`SELECT address, user_id FROM user_wallets
WHERE wallet_type_id = $1 AND lower(address) = lower($2)`, [custodyType.id, t.to]);
if (rows[0]) {
wallet = rows[0];
transfer = t;
break;
}
}
if (!wallet) {
return {
credited: false,
reason: `no USDT_BEP20 user_wallet for to=${usdtTransfers.map((t) => t.to).join(',')}`,
};
}
const currentBlock = await bscService.getCurrentBlock();
const confirmations = currentBlock - receipt.blockNumber + 1;
if (confirmations < BSC_CONFIRMATIONS) {
return {
credited: false,
reason: `need ${BSC_CONFIRMATIONS} confirmations, have ${confirmations}`,
};
}
const ledgerAmount = (0, usdtUnits_1.scaleChainToLedger)(transfer.value, usdtUnits_1.BEP20_USDT_DECIMALS, usdtUnits_1.LEDGER_USDT_DECIMALS);
if (ledgerAmount <= 0n)
return { credited: false, reason: 'amount too small after scale' };
const inserted = await creditDeposit({
userId: wallet.user_id,
ledgerWalletTypeId: ledgerType.id,
custodyWalletTypeId: custodyType.id,
network: 'BSC',
sourceWalletCode: walletCapabilities_1.USDT_BEP20_CODE,
ledgerAmount,
chainAmount: transfer.value,
blockchainTxId: txHash,
fromAddress: transfer.from,
toAddress: wallet.address,
confirmations,
requiredConfirmations: BSC_CONFIRMATIONS,
});
if (!inserted) {
return {
credited: false,
alreadyCredited: true,
userId: wallet.user_id,
ledgerAmount: ledgerAmount.toString(),
reason: 'already credited (idempotent)',
};
}
return {
credited: true,
userId: wallet.user_id,
ledgerAmount: ledgerAmount.toString(),
};
}
async function creditDeposit(opts) {
const account = await ledgerRepository.getOrCreateAccount(opts.userId, opts.ledgerWalletTypeId, 'main');
const client = await (0, connection_1.getClient)();
let tx = null;
try {
await (0, connection_1.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 false;
}
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');
console.log(`[deposit] credited ${opts.sourceWalletCode} user=${opts.userId} ledger=${opts.ledgerAmount.toString()} tx=${opts.blockchainTxId}`);
}
catch (e) {
await client.query('ROLLBACK');
throw e;
}
finally {
client.release();
}
if (!tx)
return false;
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 (0, sweepService_1.enqueueSweepAfterDeposit)(opts.userId, opts.custodyWalletTypeId, opts.chainAmount, tx.id);
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(opts.userId);
return true;
}
//# sourceMappingURL=depositMonitorService.js.map