171 lines
5.6 KiB
TypeScript
171 lines
5.6 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_WALLET_CODE } from './walletCapabilities';
|
|
import * as tronService from './blockchain/tronService';
|
|
|
|
const TRON_CONFIRMATIONS = config.blockchain.tron.confirmations;
|
|
|
|
/** Scans TRON for new USDT TRC20 deposits and credits confirmed transfers. */
|
|
export async function processTronDeposits(): Promise<void> {
|
|
const walletType = await walletRepository.getWalletTypeByCode(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 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) {
|
|
// Only *deposit* rows count — game_stake/transfer/etc. must not block backfill,
|
|
// otherwise a missed faucet transfer is never scanned again (forward-only cursor).
|
|
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 ${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: string,
|
|
walletTypeId: number,
|
|
amount: bigint,
|
|
blockchainTxId: string,
|
|
fromAddress: string,
|
|
toAddress: string,
|
|
block: 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: 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 enqueueSweepAfterDeposit(userId, walletTypeId, amount, tx.id);
|
|
queueUserAdminStatsRefresh(userId);
|
|
}
|