After trying to recuparate money from cold wallet17
This commit is contained in:
parent
0548e64c42
commit
ae13b91822
@ -84,6 +84,12 @@ USDC_POLYGON_CONTRACT=
|
||||
ALLOW_WITHDRAWALS=false
|
||||
# Treasury sweeps (deposit HD → cold). Also wire these in docker-compose (recreate backend after change).
|
||||
SWEEP_ENABLED=false
|
||||
# true = auto HD→cold without Approvals (recommended only with SWEEP_COLD_ALLOWLIST set)
|
||||
# SWEEP_AUTO_EXECUTE=false
|
||||
# Optional raw max for auto path; above this still needs Approvals (BEP20: 18 decimals, e.g. 100 USDT = 100000000000000000000)
|
||||
# SWEEP_AUTO_MAX_AMOUNT_RAW=
|
||||
# Pin allowed cold destination(s); blocks sweeps if DB cold is changed to another address
|
||||
# SWEEP_COLD_ALLOWLIST=0xYourColdAddress
|
||||
# Min on-chain raw units to enqueue (TRC20: 1e6 = 1 USDT; BEP20 uses 18-dec chain amount so 1e6 is tiny)
|
||||
SWEEP_MIN_AMOUNT_RAW=1000000
|
||||
# SWEEP_BSC_GAS_TOPUP_WEI=1000000000000000
|
||||
|
||||
@ -14,6 +14,7 @@ import {
|
||||
createSweepBatchApprovalRequests,
|
||||
SWEEP_BATCH_INTERVAL_MS,
|
||||
} from '../services/sweepBatchService';
|
||||
import { processAutoEligibleSweeps, getSweepPollIntervalMs } from '../services/sweepService';
|
||||
import { ensureCountriesSeeded } from '../services/countryService';
|
||||
import { scheduleAdminStatsBackfill } from '../services/userAdminStatsService';
|
||||
import { startAdminExportWorker } from '../services/adminUserExportService';
|
||||
@ -95,14 +96,24 @@ function startDbTamperMonitor(): void {
|
||||
function startSweepBatchMonitor(): void {
|
||||
const run = async () => {
|
||||
try {
|
||||
if (config.treasury.sweepEnabled && config.treasury.sweepAutoExecute) {
|
||||
const auto = await processAutoEligibleSweeps();
|
||||
if (auto > 0) {
|
||||
console.log(`[sweep] auto-executed ${auto} sweep(s)`);
|
||||
}
|
||||
}
|
||||
const n = await createSweepBatchApprovalRequests();
|
||||
if (n > 0 && process.env.NODE_ENV !== 'production') {
|
||||
if (n > 0) {
|
||||
console.log(`[sweep-batch] Enqueued ${n} batch approval request(s)`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Sweep batch job error:', e);
|
||||
}
|
||||
setTimeout(run, SWEEP_BATCH_INTERVAL_MS);
|
||||
const nextMs =
|
||||
config.treasury.sweepEnabled && config.treasury.sweepAutoExecute
|
||||
? Math.min(SWEEP_BATCH_INTERVAL_MS, getSweepPollIntervalMs())
|
||||
: SWEEP_BATCH_INTERVAL_MS;
|
||||
setTimeout(run, nextMs);
|
||||
};
|
||||
setTimeout(run, 60_000);
|
||||
}
|
||||
|
||||
@ -174,6 +174,24 @@ export const config = {
|
||||
treasury: {
|
||||
/** Moves on-chain deposits from user addresses to cold storage */
|
||||
sweepEnabled: process.env.SWEEP_ENABLED === 'true',
|
||||
/**
|
||||
* When true, pending sweeps execute on-chain without Approvals (after safety checks).
|
||||
* Default false — keep human approval for cold destination / amount review.
|
||||
*/
|
||||
sweepAutoExecute: process.env.SWEEP_AUTO_EXECUTE === 'true',
|
||||
/**
|
||||
* Optional raw-unit cap for auto-execute. Above this amount, sweep stays pending
|
||||
* for Submit sweeps → Approvals. Empty = no cap when SWEEP_AUTO_EXECUTE=true.
|
||||
*/
|
||||
sweepAutoMaxAmountRaw: (process.env.SWEEP_AUTO_MAX_AMOUNT_RAW || '').trim(),
|
||||
/**
|
||||
* Optional comma-separated cold addresses allowed as sweep destinations (EVM lowercased).
|
||||
* When set, active cold must match; blocks sweeps if DB cold was changed to an unknown address.
|
||||
*/
|
||||
sweepColdAllowlist: (process.env.SWEEP_COLD_ALLOWLIST || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
sweepPollIntervalMs: parseInt(process.env.SWEEP_POLL_INTERVAL_MS || '120000', 10),
|
||||
/** Minimum token amount (raw units) to sweep */
|
||||
sweepMinAmountRaw: process.env.SWEEP_MIN_AMOUNT_RAW || '1000000',
|
||||
|
||||
@ -35,6 +35,96 @@ function minSweepAmount(): bigint {
|
||||
return BigInt(config.treasury.sweepMinAmountRaw);
|
||||
}
|
||||
|
||||
function normalizeChainAddress(network: string, address: string): string {
|
||||
const a = address.trim();
|
||||
if (network === 'BSC' || network === 'POLYGON' || a.startsWith('0x') || a.startsWith('0X')) {
|
||||
return a.toLowerCase();
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
function addressesMatch(network: string, a: string, b: string): boolean {
|
||||
return normalizeChainAddress(network, a) === normalizeChainAddress(network, b);
|
||||
}
|
||||
|
||||
function isColdOnAllowlist(network: string, coldAddress: string): boolean {
|
||||
const list = 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: bigint): boolean {
|
||||
if (!config.treasury.sweepAutoExecute) return false;
|
||||
const maxRaw = 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: depositSweepRepository.DepositSweepRow): Promise<{
|
||||
network: string;
|
||||
walletType: NonNullable<Awaited<ReturnType<typeof walletRepository.getWalletTypeById>>>;
|
||||
}> {
|
||||
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 === 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 === USDT_TRC20_CODE && config.blockchain.tron.usdtTrc20Contract
|
||||
? 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: string, derivationIndex: number): string {
|
||||
const mnemonic = getMnemonic();
|
||||
if (network === 'TRON') {
|
||||
@ -65,6 +155,15 @@ export async function enqueueSweepAfterDeposit(
|
||||
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;
|
||||
|
||||
@ -153,11 +252,15 @@ async function ensurePolygonGasForUsdcSweep(depositAddress: string, hotPrivateKe
|
||||
}
|
||||
|
||||
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 { 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);
|
||||
@ -271,9 +374,7 @@ export async function processPendingSweeps(opts?: {
|
||||
try {
|
||||
await executeSweep(sweep);
|
||||
processed++;
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(`[sweep] Completed sweep ${sweep.id} → cold`);
|
||||
}
|
||||
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);
|
||||
@ -284,6 +385,52 @@ export async function processPendingSweeps(opts?: {
|
||||
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.
|
||||
*/
|
||||
export async function processAutoEligibleSweeps(): Promise<number> {
|
||||
if (!config.treasury.sweepEnabled || !config.treasury.sweepAutoExecute) return 0;
|
||||
|
||||
const pending = await depositSweepRepository.listPendingSweeps(25);
|
||||
let processed = 0;
|
||||
|
||||
for (const sweep of pending) {
|
||||
const amount = BigInt(sweep.amount);
|
||||
if (!isAutoExecuteEligible(amount)) 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 import('../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 });
|
||||
}
|
||||
}
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
export async function executeApprovedBatch(batchId: string): Promise<number> {
|
||||
await depositSweepBatchRepository.markBatchStatus(batchId, 'executing');
|
||||
try {
|
||||
|
||||
@ -56,6 +56,12 @@ x-backend-common: &backend-common
|
||||
ALLOW_WITHDRAWALS: ${ALLOW_WITHDRAWALS:-false}
|
||||
# Treasury: auto-enqueue deposit → cold sweeps (requires active cold wallet in Admin → Treasury)
|
||||
SWEEP_ENABLED: ${SWEEP_ENABLED:-false}
|
||||
# true = sweep HD→cold without Approvals (still validates cold allowlist / balances)
|
||||
SWEEP_AUTO_EXECUTE: ${SWEEP_AUTO_EXECUTE:-false}
|
||||
# Optional: auto only below this raw amount; larger still need Approvals
|
||||
SWEEP_AUTO_MAX_AMOUNT_RAW: ${SWEEP_AUTO_MAX_AMOUNT_RAW:-}
|
||||
# Optional: comma-separated allowed cold addresses (recommended if auto-execute)
|
||||
SWEEP_COLD_ALLOWLIST: ${SWEEP_COLD_ALLOWLIST:-}
|
||||
SWEEP_MIN_AMOUNT_RAW: ${SWEEP_MIN_AMOUNT_RAW:-1000000}
|
||||
SWEEP_POLL_INTERVAL_MS: ${SWEEP_POLL_INTERVAL_MS:-120000}
|
||||
SWEEP_BSC_GAS_TOPUP_WEI: ${SWEEP_BSC_GAS_TOPUP_WEI:-1000000000000000}
|
||||
|
||||
@ -81,6 +81,9 @@ nano .env # ou vim
|
||||
| `USDT_BEP20_CONTRACT` | Laisser **vide** en mainnet (USDT officiel BSC en DB) |
|
||||
| `ALLOW_WITHDRAWALS` | `false` jusqu’à validation des dépôts (le kill-switch admin Settings prime aussi) |
|
||||
| `SWEEP_ENABLED` | `false` jusqu’au test cold/sweep ; passer à `true` + cold wallet (voir section trésorerie) |
|
||||
| `SWEEP_AUTO_EXECUTE` | `false` (défaut) = Submit + Approvals ; `true` = sweep HD→cold automatique après contrôles |
|
||||
| `SWEEP_AUTO_MAX_AMOUNT_RAW` | Optionnel — au-dessus de ce montant (raw), l’approbation manuelle reste obligatoire |
|
||||
| `SWEEP_COLD_ALLOWLIST` | Optionnel mais **recommandé** avec auto : adresses cold autorisées (séparées par virgule) |
|
||||
| `APP_PUBLIC_URL` | Ex. HTTP test : `http://prediqo.redirectme.net:9080` · HTTPS : `https://…:9443` |
|
||||
| `CORS_ORIGINS` | Même origine que le front (schéma + hôte + port) |
|
||||
| `VITE_API_BASE_URL` | Même URL de base que `APP_PUBLIC_URL` (sans `/api`) — **rebuild** front après changement |
|
||||
@ -444,12 +447,17 @@ Objectif : valider le circuit **Dépôt user → adresse HD dépôt → Sweep
|
||||
|
||||
```env
|
||||
SWEEP_ENABLED=true
|
||||
# Optionnel — sweep sans Approvals (garder false si vous voulez une revue humaine) :
|
||||
# SWEEP_AUTO_EXECUTE=true
|
||||
# SWEEP_COLD_ALLOWLIST=0xVotreColdBep20
|
||||
# SWEEP_AUTO_MAX_AMOUNT_RAW=100000000000000000000
|
||||
# optionnel : min on-chain (défaut 1000000 — largement sous 1 USDT BEP20 à 18 déc.)
|
||||
# SWEEP_MIN_AMOUNT_RAW=1000000
|
||||
# top-up BNB vers l’adresse de dépôt avant transfer USDT (défaut 0.001 BNB)
|
||||
# SWEEP_BSC_GAS_TOPUP_WEI=1000000000000000
|
||||
```
|
||||
|
||||
> **Approbation vs auto :** par défaut, « Submit sweeps for approval » + Approvals est un **contrôle ops** (revoir destination / montant). Ce n’est pas ce qui protège contre une compromission totale du serveur (`PLATFORM_MNEMONIC` suffit déjà à signer). Avec `SWEEP_AUTO_EXECUTE=true`, le job exécute les sweeps éligibles après vérif cold actif = allowlist, solde HD ≥ montant, min amount. Les montants au-dessus de `SWEEP_AUTO_MAX_AMOUNT_RAW` restent manuels.
|
||||
4. Recréer le backend pour injecter les vars (`docker-compose` les passe désormais) :
|
||||
|
||||
```bash
|
||||
|
||||
@ -1538,7 +1538,7 @@ export const en = {
|
||||
pendingSweeps: '{{count}} pending sweeps',
|
||||
failedSweeps: '{{count}} failed sweeps',
|
||||
sweepDisabledHint:
|
||||
'Set SWEEP_ENABLED=true in the VPS .env (wired via docker-compose), recreate the backend container, then save a cold wallet address below. New deposits enqueue sweeps automatically; approve batches under Approvals.',
|
||||
'Set SWEEP_ENABLED=true in the VPS .env (wired via docker-compose), recreate the backend container, then save a cold wallet address below. New deposits enqueue sweeps; approve under Approvals — or set SWEEP_AUTO_EXECUTE=true (with SWEEP_COLD_ALLOWLIST) for hands-free HD→cold.',
|
||||
coldWallet: 'Cold wallet',
|
||||
hotWallet: 'Hot wallet',
|
||||
address: 'Address',
|
||||
|
||||
@ -1554,7 +1554,7 @@ export const fr = {
|
||||
pendingSweeps: '{{count}} sweep(s) en attente',
|
||||
failedSweeps: '{{count}} sweep(s) échoué(s)',
|
||||
sweepDisabledHint:
|
||||
'Définissez SWEEP_ENABLED=true dans le .env VPS (passé via docker-compose), recréez le conteneur backend, puis enregistrez une adresse cold ci-dessous. Les nouveaux dépôts enfilent un sweep ; approuvez les lots sous Approvals.',
|
||||
'Définissez SWEEP_ENABLED=true dans le .env VPS (passé via docker-compose), recréez le conteneur backend, puis enregistrez une adresse cold ci-dessous. Les nouveaux dépôts enfilent un sweep ; Approvals — ou SWEEP_AUTO_EXECUTE=true (avec SWEEP_COLD_ALLOWLIST) pour un HD→cold sans clic.',
|
||||
coldWallet: 'Cold wallet',
|
||||
hotWallet: 'Hot wallet',
|
||||
address: 'Adresse',
|
||||
|
||||
Loading…
Reference in New Issue
Block a user