games_app/backend/src/services/sweepService.ts
2026-08-24 13:41:54 +02:00

215 lines
8.2 KiB
TypeScript

/**
* Sweeps on-chain deposits from user HD addresses to cold storage.
*/
import * as bip39 from 'bip39';
import { config } from '../config';
import {
deriveTronFromMnemonic,
deriveEvmFromMnemonic,
decryptPrivateKey,
} from './hdWallet';
import * as walletRepository from '../repositories/walletRepository';
import * as coldWalletRepository from '../repositories/coldWalletRepository';
import * as depositSweepRepository from '../repositories/depositSweepRepository';
import * as depositSweepBatchRepository from '../repositories/depositSweepBatchRepository';
import * as hotWalletRepository from '../repositories/hotWalletRepository';
import * as tronService from './blockchain/tronService';
import * as polygonService from './blockchain/polygonService';
import * as bscService from './blockchain/bscService';
import { USDT_BEP20_CODE, USDT_TRC20_CODE } from './walletCapabilities';
const PLATFORM_MNEMONIC = process.env.PLATFORM_MNEMONIC || '';
const MIN_TRX_FOR_TRC20_SWEEP = 3_000_000n;
const MIN_BNB_WEI = 50_000_000_000_000n; // 0.00005 BNB
function getMnemonic(): string {
const raw = PLATFORM_MNEMONIC.trim();
if (!raw || !bip39.validateMnemonic(raw)) {
throw new Error('PLATFORM_MNEMONIC is not configured for sweeps');
}
return raw;
}
function minSweepAmount(): bigint {
return BigInt(config.treasury.sweepMinAmountRaw);
}
function deriveDepositPrivateKey(network: string, derivationIndex: number): string {
const mnemonic = getMnemonic();
if (network === 'TRON') {
return deriveTronFromMnemonic(mnemonic, derivationIndex).privateKey;
}
if (network === 'BSC' || network === 'POLYGON') {
return deriveEvmFromMnemonic(mnemonic, derivationIndex).privateKey;
}
throw new Error(`Unsupported network for sweep: ${network}`);
}
export async function enqueueSweepAfterDeposit(
userId: string,
walletTypeId: number,
amount: bigint,
depositTransactionId: string
): Promise<void> {
if (!config.treasury.sweepEnabled) return;
const existing = await depositSweepRepository.findByDepositTransactionId(depositTransactionId);
if (existing) return;
const cold = await coldWalletRepository.getActiveColdWallet(walletTypeId);
if (!cold) {
if (process.env.NODE_ENV !== 'production') {
console.warn(`[sweep] No cold wallet for type ${walletTypeId}; skipping enqueue`);
}
return;
}
const userWallet = await walletRepository.getUserWallet(userId, walletTypeId);
if (!userWallet) return;
if (amount < minSweepAmount()) return;
const batch = await depositSweepBatchRepository.getOrCreateOpenBatch();
await depositSweepRepository.createSweep({
userId,
walletTypeId,
fromAddress: userWallet.address,
toColdAddress: cold.address,
amount,
depositTransactionId,
batchId: batch.id,
});
await depositSweepBatchRepository.incrementBatchCount(batch.id);
}
async function ensureTronGasForTokenSweep(depositAddress: string, usdtWalletTypeId: number): Promise<void> {
const trxBalance = await tronService.getTrxBalanceSun(depositAddress);
if (trxBalance >= MIN_TRX_FOR_TRC20_SWEEP) return;
// Prefer USDT TRC20 hot wallet (same TRON address holds TRX for gas)
const hot = await hotWalletRepository.getActiveHotWallet(usdtWalletTypeId);
if (!hot) throw new Error('No TRON hot wallet for gas top-up');
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
const topUp = BigInt(config.treasury.tronGasTopUpSun);
await tronService.sendTrx(hotKey, depositAddress, topUp);
}
async function ensureBscGasForUsdtSweep(depositAddress: string, hotPrivateKey: string): Promise<void> {
const bnb = await bscService.getNativeBalanceWei(depositAddress);
if (bnb >= MIN_BNB_WEI) return;
const topUp = BigInt(config.blockchain.bsc.gasTopUpWei);
await bscService.sendBnb(hotPrivateKey, depositAddress, topUp);
}
async function ensurePolygonGasForUsdcSweep(depositAddress: string, hotPrivateKey: string): Promise<void> {
const matic = await polygonService.getNativeBalanceWei(depositAddress);
const minGas = 50_000_000_000_000_000n;
if (matic >= minGas) return;
const topUp = BigInt(config.treasury.polygonGasTopUpWei);
await polygonService.sendMatic(hotPrivateKey, depositAddress, topUp);
}
async function executeSweep(sweep: depositSweepRepository.DepositSweepRow): Promise<void> {
const walletType = await walletRepository.getWalletTypeById(sweep.wallet_type_id);
if (!walletType) throw new Error('Unknown wallet type');
const userWallet = await walletRepository.getUserWallet(sweep.user_id, sweep.wallet_type_id);
if (!userWallet) throw new Error('User deposit wallet not found');
const amount = BigInt(sweep.amount);
const privateKey = deriveDepositPrivateKey(walletType.network, userWallet.derivation_index);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
let txId: string;
if (walletType.network === 'TRON') {
const trc20Contract =
walletType.code === USDT_TRC20_CODE && config.blockchain.tron.usdtTrc20Contract
? config.blockchain.tron.usdtTrc20Contract
: walletType.contract_address;
if (trc20Contract) {
await depositSweepRepository.updateSweepStatus(sweep.id, 'gas_funding');
await ensureTronGasForTokenSweep(sweep.from_address, walletType.id);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
txId = await tronService.sendTrc20(
privateKey,
trc20Contract,
sweep.to_cold_address,
amount
);
} else {
txId = await tronService.sendTrx(privateKey, sweep.to_cold_address, amount);
}
} else if (walletType.network === 'BSC' || walletType.code === USDT_BEP20_CODE) {
const hot = await hotWalletRepository.getActiveHotWallet(walletType.id);
if (!hot) throw new Error('No BSC hot wallet for gas');
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
await depositSweepRepository.updateSweepStatus(sweep.id, 'gas_funding');
await ensureBscGasForUsdtSweep(sweep.from_address, hotKey);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
const contract = bscService.resolveUsdtContract(walletType.contract_address);
txId = await bscService.sendUsdt(privateKey, contract, sweep.to_cold_address, amount);
} else if (walletType.network === 'POLYGON') {
const hot = await hotWalletRepository.getActiveHotWallet(walletType.id);
if (!hot) throw new Error('No Polygon hot wallet for gas');
const hotKey = decryptPrivateKey(hot.encrypted_private_key);
await depositSweepRepository.updateSweepStatus(sweep.id, 'gas_funding');
await ensurePolygonGasForUsdcSweep(sweep.from_address, hotKey);
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
txId = await polygonService.sendUsdc(privateKey, sweep.to_cold_address, amount);
} else {
throw new Error('Unsupported network');
}
await depositSweepRepository.updateSweepStatus(sweep.id, 'completed', { blockchainTxId: txId });
}
export async function processPendingSweeps(opts?: {
unbatchedOnly?: boolean;
batchId?: string;
limit?: number;
}): Promise<number> {
if (!config.treasury.sweepEnabled) return 0;
const pending = await depositSweepRepository.listPendingSweeps(opts?.limit ?? 10, {
unbatchedOnly: opts?.unbatchedOnly,
batchId: opts?.batchId,
});
let processed = 0;
for (const sweep of pending) {
try {
await executeSweep(sweep);
processed++;
if (process.env.NODE_ENV !== 'production') {
console.log(`[sweep] Completed sweep ${sweep.id} → cold`);
}
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error(`[sweep] Failed sweep ${sweep.id}:`, msg);
await depositSweepRepository.updateSweepStatus(sweep.id, 'failed', { errorMessage: msg });
}
}
return processed;
}
export async function executeApprovedBatch(batchId: string): Promise<number> {
await depositSweepBatchRepository.markBatchStatus(batchId, 'executing');
try {
const processed = await processPendingSweeps({ batchId, limit: 100 });
await depositSweepBatchRepository.markBatchStatus(batchId, 'completed');
return processed;
} catch (e) {
await depositSweepBatchRepository.markBatchStatus(batchId, 'failed');
throw e;
}
}
export function getSweepPollIntervalMs(): number {
return config.treasury.sweepPollIntervalMs;
}