209 lines
9.1 KiB
JavaScript
209 lines
9.1 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.processPendingSweeps = processPendingSweeps;
|
|
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 PLATFORM_MNEMONIC = process.env.PLATFORM_MNEMONIC || '';
|
|
const TRON_WALLET_TYPE_IDS = [1, 2];
|
|
const POLYGON_WALLET_TYPE_ID = 3;
|
|
const MIN_TRX_FOR_TRC20_SWEEP = 3000000n;
|
|
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 deriveDepositPrivateKey(walletTypeId, derivationIndex) {
|
|
const mnemonic = getMnemonic();
|
|
if (TRON_WALLET_TYPE_IDS.includes(walletTypeId)) {
|
|
return (0, hdWallet_1.deriveTronFromMnemonic)(mnemonic, derivationIndex).privateKey;
|
|
}
|
|
if (walletTypeId === POLYGON_WALLET_TYPE_ID) {
|
|
return (0, hdWallet_1.derivePolygonFromMnemonic)(mnemonic, derivationIndex).privateKey;
|
|
}
|
|
throw new Error('Unsupported wallet type for sweep');
|
|
}
|
|
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 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) {
|
|
const trxBalance = await tronService.getTrxBalanceSun(depositAddress);
|
|
if (trxBalance >= MIN_TRX_FOR_TRC20_SWEEP)
|
|
return;
|
|
const hot = await hotWalletRepository.getActiveHotWallet(1);
|
|
if (!hot)
|
|
throw new Error('No TRX 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 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 = sweep.wallet_type_id === 1
|
|
? await walletRepository.getWalletTypeByCode('TRX')
|
|
: sweep.wallet_type_id === 2
|
|
? await walletRepository.getWalletTypeByCode('USDT_TRC20')
|
|
: await walletRepository.getWalletTypeByCode('USDC_POLYGON');
|
|
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(sweep.wallet_type_id, userWallet.derivation_index);
|
|
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
|
|
let txId;
|
|
if (walletType.network === 'TRON') {
|
|
const trc20Contract = walletType.code === 'USDT_TRC20' && 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);
|
|
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 === 'POLYGON') {
|
|
const hot = await hotWalletRepository.getActiveHotWallet(POLYGON_WALLET_TYPE_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 });
|
|
}
|
|
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++;
|
|
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;
|
|
}
|
|
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
|