451 lines
20 KiB
JavaScript
451 lines
20 KiB
JavaScript
"use strict";
|
||
/**
|
||
* Sweeps on-chain deposits from user HD addresses to cold storage.
|
||
*/
|
||
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.enqueueSweepAfterDeposit = enqueueSweepAfterDeposit;
|
||
exports.enqueueSweepsForCreditedHdBalances = enqueueSweepsForCreditedHdBalances;
|
||
exports.processPendingSweeps = processPendingSweeps;
|
||
exports.processAutoEligibleSweeps = processAutoEligibleSweeps;
|
||
exports.executeApprovedBatch = executeApprovedBatch;
|
||
exports.getSweepPollIntervalMs = getSweepPollIntervalMs;
|
||
const bip39 = __importStar(require("bip39"));
|
||
const config_1 = require("../config");
|
||
const hdWallet_1 = require("./hdWallet");
|
||
const walletRepository = __importStar(require("../repositories/walletRepository"));
|
||
const coldWalletRepository = __importStar(require("../repositories/coldWalletRepository"));
|
||
const depositSweepRepository = __importStar(require("../repositories/depositSweepRepository"));
|
||
const depositSweepBatchRepository = __importStar(require("../repositories/depositSweepBatchRepository"));
|
||
const hotWalletRepository = __importStar(require("../repositories/hotWalletRepository"));
|
||
const tronService = __importStar(require("./blockchain/tronService"));
|
||
const polygonService = __importStar(require("./blockchain/polygonService"));
|
||
const bscService = __importStar(require("./blockchain/bscService"));
|
||
const walletCapabilities_1 = require("./walletCapabilities");
|
||
const PLATFORM_MNEMONIC = process.env.PLATFORM_MNEMONIC || '';
|
||
const MIN_TRX_FOR_TRC20_SWEEP = 3000000n;
|
||
const MIN_BNB_WEI = 50000000000000n; // 0.00005 BNB
|
||
function getMnemonic() {
|
||
const raw = PLATFORM_MNEMONIC.trim();
|
||
if (!raw || !bip39.validateMnemonic(raw)) {
|
||
throw new Error('PLATFORM_MNEMONIC is not configured for sweeps');
|
||
}
|
||
return raw;
|
||
}
|
||
function minSweepAmount() {
|
||
return BigInt(config_1.config.treasury.sweepMinAmountRaw);
|
||
}
|
||
function normalizeChainAddress(network, address) {
|
||
const a = address.trim();
|
||
if (network === 'BSC' || network === 'POLYGON' || a.startsWith('0x') || a.startsWith('0X')) {
|
||
return a.toLowerCase();
|
||
}
|
||
return a;
|
||
}
|
||
function addressesMatch(network, a, b) {
|
||
return normalizeChainAddress(network, a) === normalizeChainAddress(network, b);
|
||
}
|
||
function isColdOnAllowlist(network, coldAddress) {
|
||
const list = config_1.config.treasury.sweepColdAllowlist;
|
||
if (list.length === 0)
|
||
return true;
|
||
const want = normalizeChainAddress(network, coldAddress);
|
||
return list.some((entry) => normalizeChainAddress(network, entry) === want);
|
||
}
|
||
function isAutoExecuteEligible(amount) {
|
||
if (!config_1.config.treasury.sweepAutoExecute)
|
||
return false;
|
||
const maxRaw = config_1.config.treasury.sweepAutoMaxAmountRaw;
|
||
if (maxRaw) {
|
||
try {
|
||
if (amount > BigInt(maxRaw))
|
||
return false;
|
||
}
|
||
catch {
|
||
return false;
|
||
}
|
||
}
|
||
return true;
|
||
}
|
||
/**
|
||
* Re-validates destination + amount immediately before broadcast.
|
||
* Prevents sweeping to a cold address that changed / is not allowlisted.
|
||
*/
|
||
async function assertSweepSafeToExecute(sweep) {
|
||
const walletType = await walletRepository.getWalletTypeById(sweep.wallet_type_id);
|
||
if (!walletType)
|
||
throw new Error('Unknown wallet type');
|
||
const amount = BigInt(sweep.amount);
|
||
if (amount < minSweepAmount()) {
|
||
throw new Error(`Sweep amount below SWEEP_MIN_AMOUNT_RAW (${amount} < ${minSweepAmount()})`);
|
||
}
|
||
const cold = await coldWalletRepository.getActiveColdWallet(sweep.wallet_type_id);
|
||
if (!cold)
|
||
throw new Error('No active cold wallet for this network');
|
||
if (!addressesMatch(walletType.network, cold.address, sweep.to_cold_address)) {
|
||
throw new Error(`Sweep destination mismatch: queued=${sweep.to_cold_address} activeCold=${cold.address}`);
|
||
}
|
||
if (!isColdOnAllowlist(walletType.network, cold.address)) {
|
||
throw new Error(`Cold address ${cold.address} is not in SWEEP_COLD_ALLOWLIST — refusing sweep`);
|
||
}
|
||
// On-chain balance must cover the queued amount (guards against stale / wrong enqueue).
|
||
if (walletType.network === 'BSC' || walletType.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
||
const contract = bscService.resolveUsdtContract(walletType.contract_address);
|
||
const bal = await bscService.getUsdtBalanceRaw(sweep.from_address, contract);
|
||
if (bal < amount) {
|
||
throw new Error(`HD balance ${bal.toString()} < sweep amount ${amount.toString()} for ${sweep.from_address}`);
|
||
}
|
||
}
|
||
else if (walletType.network === 'TRON') {
|
||
const trc20Contract = walletType.code === walletCapabilities_1.USDT_TRC20_CODE && config_1.config.blockchain.tron.usdtTrc20Contract
|
||
? config_1.config.blockchain.tron.usdtTrc20Contract
|
||
: walletType.contract_address;
|
||
if (trc20Contract) {
|
||
const bal = await tronService.getTrc20BalanceRaw(sweep.from_address, trc20Contract);
|
||
if (bal < amount) {
|
||
throw new Error(`HD balance ${bal.toString()} < sweep amount ${amount.toString()} for ${sweep.from_address}`);
|
||
}
|
||
}
|
||
}
|
||
return { network: walletType.network, walletType };
|
||
}
|
||
function deriveDepositPrivateKey(network, derivationIndex) {
|
||
const mnemonic = getMnemonic();
|
||
if (network === 'TRON') {
|
||
return (0, hdWallet_1.deriveTronFromMnemonic)(mnemonic, derivationIndex).privateKey;
|
||
}
|
||
if (network === 'BSC' || network === 'POLYGON') {
|
||
return (0, hdWallet_1.deriveEvmFromMnemonic)(mnemonic, derivationIndex).privateKey;
|
||
}
|
||
throw new Error(`Unsupported network for sweep: ${network}`);
|
||
}
|
||
async function enqueueSweepAfterDeposit(userId, walletTypeId, amount, depositTransactionId) {
|
||
if (!config_1.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 walletType = await walletRepository.getWalletTypeById(walletTypeId);
|
||
if (!walletType)
|
||
return;
|
||
if (!isColdOnAllowlist(walletType.network, cold.address)) {
|
||
console.error(`[sweep] Active cold ${cold.address} not in SWEEP_COLD_ALLOWLIST — not enqueueing`);
|
||
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);
|
||
// Don't wait for the 1–2 min poll — run auto path right after enqueue.
|
||
if (isAutoExecuteEligible(amount)) {
|
||
void processAutoEligibleSweeps().catch((e) => {
|
||
console.error('[sweep] post-enqueue auto-execute error:', e);
|
||
});
|
||
}
|
||
}
|
||
async function enqueueSweepsForCreditedHdBalances() {
|
||
if (!config_1.config.treasury.sweepEnabled) {
|
||
return { sweepEnabled: false, enqueued: 0, alreadyQueued: 0 };
|
||
}
|
||
const { listPositiveSnapshots } = await Promise.resolve().then(() => __importStar(require('../repositories/depositHdSnapshotRepository')));
|
||
const { listCompletedDepositsToAddress } = await Promise.resolve().then(() => __importStar(require('../repositories/transactionRepository')));
|
||
const snapshots = await listPositiveSnapshots();
|
||
let enqueued = 0;
|
||
let alreadyQueued = 0;
|
||
for (const s of snapshots) {
|
||
if (!s.credited)
|
||
continue;
|
||
const deposits = await listCompletedDepositsToAddress(s.address);
|
||
for (const deposit of deposits) {
|
||
const existing = await depositSweepRepository.findByDepositTransactionId(deposit.id);
|
||
if (existing) {
|
||
alreadyQueued += 1;
|
||
continue;
|
||
}
|
||
const meta = (deposit.metadata ?? {});
|
||
const chainRaw = typeof meta.chain_amount === 'string'
|
||
? meta.chain_amount
|
||
: typeof meta.chainAmount === 'string'
|
||
? meta.chainAmount
|
||
: null;
|
||
const amount = chainRaw ? BigInt(chainRaw) : BigInt(deposit.amount);
|
||
if (amount <= 0n)
|
||
continue;
|
||
await enqueueSweepAfterDeposit(deposit.user_id, s.wallet_type_id, amount, deposit.id);
|
||
const after = await depositSweepRepository.findByDepositTransactionId(deposit.id);
|
||
if (after)
|
||
enqueued += 1;
|
||
}
|
||
}
|
||
return { sweepEnabled: true, enqueued, alreadyQueued };
|
||
}
|
||
async function ensureTronGasForTokenSweep(depositAddress, usdtWalletTypeId) {
|
||
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 = (0, hdWallet_1.decryptPrivateKey)(hot.encrypted_private_key);
|
||
const topUp = BigInt(config_1.config.treasury.tronGasTopUpSun);
|
||
await tronService.sendTrx(hotKey, depositAddress, topUp);
|
||
}
|
||
async function ensureBscGasForUsdtSweep(depositAddress, hotPrivateKey) {
|
||
const bnb = await bscService.getNativeBalanceWei(depositAddress);
|
||
if (bnb >= MIN_BNB_WEI)
|
||
return;
|
||
const topUp = BigInt(config_1.config.blockchain.bsc.gasTopUpWei);
|
||
await bscService.sendBnb(hotPrivateKey, depositAddress, topUp);
|
||
}
|
||
async function ensurePolygonGasForUsdcSweep(depositAddress, hotPrivateKey) {
|
||
const matic = await polygonService.getNativeBalanceWei(depositAddress);
|
||
const minGas = 50000000000000000n;
|
||
if (matic >= minGas)
|
||
return;
|
||
const topUp = BigInt(config_1.config.treasury.polygonGasTopUpWei);
|
||
await polygonService.sendMatic(hotPrivateKey, depositAddress, topUp);
|
||
}
|
||
async function executeSweep(sweep) {
|
||
const { walletType } = await assertSweepSafeToExecute(sweep);
|
||
const userWallet = await walletRepository.getUserWallet(sweep.user_id, sweep.wallet_type_id);
|
||
if (!userWallet)
|
||
throw new Error('User deposit wallet not found');
|
||
if (!addressesMatch(walletType.network, userWallet.address, sweep.from_address)) {
|
||
throw new Error(`Sweep from_address mismatch: queued=${sweep.from_address} userWallet=${userWallet.address}`);
|
||
}
|
||
const amount = BigInt(sweep.amount);
|
||
const privateKey = deriveDepositPrivateKey(walletType.network, userWallet.derivation_index);
|
||
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
|
||
let txId;
|
||
if (walletType.network === 'TRON') {
|
||
const trc20Contract = walletType.code === walletCapabilities_1.USDT_TRC20_CODE && config_1.config.blockchain.tron.usdtTrc20Contract
|
||
? config_1.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 === walletCapabilities_1.USDT_BEP20_CODE) {
|
||
const hot = await hotWalletRepository.getActiveHotWallet(walletType.id);
|
||
if (!hot)
|
||
throw new Error('No BSC hot wallet for gas');
|
||
const hotKey = (0, hdWallet_1.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 = (0, hdWallet_1.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 });
|
||
// Treasury "USDT still on HD" reads deposit_hd_snapshots; refresh so the row clears
|
||
// without waiting for the next deposit-monitor poll / manual Scan & credit.
|
||
try {
|
||
let remaining = 0n;
|
||
if (walletType.network === 'TRON') {
|
||
const trc20Contract = walletType.code === walletCapabilities_1.USDT_TRC20_CODE && config_1.config.blockchain.tron.usdtTrc20Contract
|
||
? config_1.config.blockchain.tron.usdtTrc20Contract
|
||
: walletType.contract_address;
|
||
if (trc20Contract) {
|
||
remaining = await tronService.getTrc20BalanceRaw(sweep.from_address, trc20Contract);
|
||
}
|
||
}
|
||
else if (walletType.network === 'BSC' || walletType.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
||
const contract = bscService.resolveUsdtContract(walletType.contract_address);
|
||
remaining = await bscService.getUsdtBalanceRaw(sweep.from_address, contract);
|
||
}
|
||
else if (walletType.network === 'POLYGON') {
|
||
remaining = await polygonService.getUsdcBalanceRaw(sweep.from_address);
|
||
}
|
||
const { upsertSnapshot } = await Promise.resolve().then(() => __importStar(require('../repositories/depositHdSnapshotRepository')));
|
||
await upsertSnapshot({
|
||
userId: sweep.user_id,
|
||
walletTypeId: sweep.wallet_type_id,
|
||
address: sweep.from_address,
|
||
onChainAmount: remaining,
|
||
});
|
||
}
|
||
catch (e) {
|
||
console.warn(`[sweep] HD balance re-read failed after sweep ${sweep.id}:`, e instanceof Error ? e.message : e);
|
||
try {
|
||
const { decreaseSnapshotBy } = await Promise.resolve().then(() => __importStar(require('../repositories/depositHdSnapshotRepository')));
|
||
await decreaseSnapshotBy({
|
||
userId: sweep.user_id,
|
||
walletTypeId: sweep.wallet_type_id,
|
||
amount,
|
||
});
|
||
}
|
||
catch (e2) {
|
||
console.warn(`[sweep] HD snapshot decrease failed after sweep ${sweep.id}:`, e2 instanceof Error ? e2.message : e2);
|
||
}
|
||
}
|
||
}
|
||
async function processPendingSweeps(opts) {
|
||
if (!config_1.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++;
|
||
console.log(`[sweep] Completed sweep ${sweep.id} → ${sweep.to_cold_address}`);
|
||
}
|
||
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;
|
||
}
|
||
/**
|
||
* Auto path: execute pending sweeps that pass SWEEP_AUTO_EXECUTE + optional max amount,
|
||
* without going through Approvals. Large sweeps (over max) stay queued for manual approval.
|
||
*/
|
||
async function processAutoEligibleSweeps() {
|
||
if (!config_1.config.treasury.sweepEnabled) {
|
||
console.warn('[sweep] auto-execute skipped: SWEEP_ENABLED is not true');
|
||
return 0;
|
||
}
|
||
if (!config_1.config.treasury.sweepAutoExecute) {
|
||
console.warn('[sweep] auto-execute skipped: SWEEP_AUTO_EXECUTE is not true');
|
||
return 0;
|
||
}
|
||
const pending = await depositSweepRepository.listPendingSweeps(25);
|
||
if (pending.length === 0)
|
||
return 0;
|
||
console.log(`[sweep] auto-execute: ${pending.length} pending sweep(s) to consider`);
|
||
let processed = 0;
|
||
let skippedMax = 0;
|
||
for (const sweep of pending) {
|
||
const amount = BigInt(sweep.amount);
|
||
if (!isAutoExecuteEligible(amount)) {
|
||
skippedMax += 1;
|
||
console.warn(`[sweep] skip ${sweep.id}: amount ${sweep.amount} above SWEEP_AUTO_MAX_AMOUNT_RAW=` +
|
||
`${config_1.config.treasury.sweepAutoMaxAmountRaw || '(unset)'} (BEP20 uses 18 decimals)`);
|
||
continue;
|
||
}
|
||
try {
|
||
await executeSweep(sweep);
|
||
processed += 1;
|
||
console.log(`[sweep] auto-executed ${sweep.id} amount=${sweep.amount} → ${sweep.to_cold_address}`);
|
||
try {
|
||
const auditLogRepository = await Promise.resolve().then(() => __importStar(require('../repositories/auditLogRepository')));
|
||
await auditLogRepository.create({
|
||
userId: sweep.user_id,
|
||
action: 'sweep_auto_executed',
|
||
resourceType: 'deposit_sweep',
|
||
resourceId: sweep.id,
|
||
metadata: {
|
||
amount: sweep.amount,
|
||
from: sweep.from_address,
|
||
to: sweep.to_cold_address,
|
||
walletTypeId: sweep.wallet_type_id,
|
||
},
|
||
});
|
||
}
|
||
catch {
|
||
// audit must not block sweep success
|
||
}
|
||
}
|
||
catch (e) {
|
||
const msg = e instanceof Error ? e.message : String(e);
|
||
console.error(`[sweep] auto-execute failed ${sweep.id}:`, msg);
|
||
await depositSweepRepository.updateSweepStatus(sweep.id, 'failed', { errorMessage: msg });
|
||
}
|
||
}
|
||
if (skippedMax > 0) {
|
||
console.warn(`[sweep] ${skippedMax} sweep(s) left for Approvals (over SWEEP_AUTO_MAX_AMOUNT_RAW)`);
|
||
}
|
||
return processed;
|
||
}
|
||
async function executeApprovedBatch(batchId) {
|
||
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;
|
||
}
|
||
}
|
||
function getSweepPollIntervalMs() {
|
||
return config_1.config.treasury.sweepPollIntervalMs;
|
||
}
|
||
//# sourceMappingURL=sweepService.js.map
|