162 lines
7.1 KiB
JavaScript
162 lines
7.1 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, created_at 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');
|
|
}
|
|
}
|
|
}
|
|
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 || 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 ${address}: ${transfers.length} transfer(s)`);
|
|
}
|
|
for (const t of transfers) {
|
|
const amount = tronService.parseTrc20TokenAmount(t.value);
|
|
if (amount == null) {
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
console.warn(`[deposit] USDT ${address}: skip invalid amount tx=${t.txId} value=${t.value}`);
|
|
}
|
|
continue;
|
|
}
|
|
if (t.confirmations >= TRON_CONFIRMATIONS) {
|
|
try {
|
|
await creditDeposit(user_id, walletType.id, amount, t.txId, t.from, address, t.confirmations);
|
|
}
|
|
catch (e) {
|
|
console.error(`[deposit] credit failed tx=${t.txId}:`, e);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
await depositScannerRepository.updateState(walletType.id, BigInt(currentBlock));
|
|
}
|
|
async function creditDeposit(userId, walletTypeId, amount, blockchainTxId, fromAddress, toAddress, block) {
|
|
const account = await ledgerRepository.getOrCreateAccount(userId, walletTypeId, 'main');
|
|
const client = await (0, connection_1.getClient)();
|
|
let tx = null;
|
|
try {
|
|
await (0, connection_1.beginAuthorizedTransaction)(client);
|
|
tx = await transactionRepository.insertDepositIfNew(client, {
|
|
userId,
|
|
walletTypeId,
|
|
amount,
|
|
blockchainTxId,
|
|
fromAddress,
|
|
toAddress,
|
|
confirmations: block,
|
|
requiredConfirmations: TRON_CONFIRMATIONS,
|
|
});
|
|
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 (0, sweepService_1.enqueueSweepAfterDeposit)(userId, walletTypeId, amount, tx.id);
|
|
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
|
|
}
|
|
//# sourceMappingURL=depositMonitorService.js.map
|