diff --git a/.env.example b/.env.example index 98f9280d..294b9a8c 100644 --- a/.env.example +++ b/.env.example @@ -74,6 +74,12 @@ POLYGON_RPC_URL=https://rpc-amoy.polygon.technology POLYGON_CONFIRMATIONS=8 USDC_POLYGON_CONTRACT= ALLOW_WITHDRAWALS=false +# Treasury sweeps (deposit HD → cold). Also wire these in docker-compose (recreate backend after change). +SWEEP_ENABLED=false +# 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 +# SWEEP_TRON_GAS_TOPUP_SUN=15000000 RATE_LIMIT_MAX=2000 # Ports dédiés Prediqo (n'utilise pas 80/443 du VPS) diff --git a/backend/src/controllers/treasuryController.ts b/backend/src/controllers/treasuryController.ts index e320c4b2..37b25f8b 100644 --- a/backend/src/controllers/treasuryController.ts +++ b/backend/src/controllers/treasuryController.ts @@ -2,6 +2,7 @@ import { Response } from 'express'; import { AuthRequest } from '../middleware/auth'; import * as treasuryService from '../services/treasuryService'; import * as fundApprovalService from '../services/fundApprovalService'; +import { createSweepBatchApprovalRequests } from '../services/sweepBatchService'; export async function getOverview(_req: AuthRequest, res: Response): Promise { try { @@ -50,17 +51,17 @@ export async function listSweeps(req: AuthRequest, res: Response): Promise } } -export async function runSweeps(req: AuthRequest, res: Response): Promise { +export async function runSweeps(_req: AuthRequest, res: Response): Promise { try { - const result = await fundApprovalService.createFundRequest({ - operationType: 'sweep_manual', - payload: {}, - requestedBy: req.user!.userId, - }); + // Close open batches → Approvals (sweep_batch) → on-chain execute after super-admin approve. + // (Legacy sweep_manual + unbatchedOnly never saw deposits, which are always batched.) + const batchesSubmitted = await createSweepBatchApprovalRequests(); res.status(202).json({ - requestId: result.id, - status: result.status, - message: 'Sweep run submitted — pending super-admin approval', + batchesSubmitted, + message: + batchesSubmitted > 0 + ? `${batchesSubmitted} sweep batch(es) submitted — approve under Approvals to broadcast to cold` + : 'No open sweep batches ready. Need SWEEP_ENABLED=true, an active cold wallet, and a credited deposit that enqueued a sweep.', }); } catch (e) { res.status(400).json({ error: e instanceof Error ? e.message : 'Sweep request failed' }); diff --git a/backend/src/scripts/enqueueSweepForDepositTx.ts b/backend/src/scripts/enqueueSweepForDepositTx.ts new file mode 100644 index 00000000..c0774de7 --- /dev/null +++ b/backend/src/scripts/enqueueSweepForDepositTx.ts @@ -0,0 +1,122 @@ +/** + * Enqueue a cold-wallet sweep for an already-credited deposit (e.g. credited + * before SWEEP_ENABLED / cold wallet were configured). + * + * VPS: + * sudo docker compose run --rm --no-deps --build backend \ + * node dist/scripts/enqueueSweepForDepositTx.js \ + * --tx=0x... + * + * Requires SWEEP_ENABLED=true and an active cold wallet for the deposit's custody rail. + */ + +import './loadEnv'; +import * as transactionRepository from '../repositories/transactionRepository'; +import * as walletRepository from '../repositories/walletRepository'; +import * as coldWalletRepository from '../repositories/coldWalletRepository'; +import { enqueueSweepAfterDeposit } from '../services/sweepService'; +import { config } from '../config'; +import * as depositSweepRepository from '../repositories/depositSweepRepository'; + +async function main(): Promise { + const txArg = process.argv.find((a) => a.startsWith('--tx='))?.slice('--tx='.length).trim(); + if (!txArg) { + console.error('Usage: node dist/scripts/enqueueSweepForDepositTx.js --tx='); + process.exit(1); + } + + if (!config.treasury.sweepEnabled) { + console.error('SWEEP_ENABLED is not true in this environment — set it and recreate the backend container.'); + process.exit(2); + } + + const deposit = await transactionRepository.findByBlockchainTxId(txArg); + if (!deposit) { + console.error(`No transaction found for blockchain_tx_id=${txArg}`); + process.exit(3); + } + if (deposit.type !== 'deposit') { + console.error(`Transaction ${deposit.id} is type=${deposit.type}, expected deposit`); + process.exit(3); + } + + const meta = (deposit.metadata ?? {}) as Record; + const sourceCode = + typeof meta.source_wallet_type === 'string' ? meta.source_wallet_type : null; + const chainAmountRaw = + typeof meta.chain_amount === 'string' + ? meta.chain_amount + : typeof meta.chainAmount === 'string' + ? meta.chainAmount + : null; + + if (!sourceCode || !chainAmountRaw) { + console.error( + 'Deposit metadata missing source_wallet_type / chain_amount — cannot determine custody rail amount' + ); + process.exit(4); + } + + const custodyType = await walletRepository.getWalletTypeByCode(sourceCode); + if (!custodyType) { + console.error(`Unknown custody wallet type code: ${sourceCode}`); + process.exit(4); + } + + const cold = await coldWalletRepository.getActiveColdWallet(custodyType.id); + if (!cold) { + console.error( + `No active cold wallet for ${sourceCode} (wallet_type_id=${custodyType.id}). Set it in Admin → Treasury first.` + ); + process.exit(5); + } + + const existing = await depositSweepRepository.findByDepositTransactionId(deposit.id); + if (existing) { + console.log( + JSON.stringify( + { + enqueued: false, + alreadyExists: true, + sweepId: existing.id, + status: existing.status, + batchId: existing.batch_id, + note: 'Use Treasury → Submit sweeps for approval (if still pending), then Approvals.', + }, + null, + 2 + ) + ); + return; + } + + const chainAmount = BigInt(chainAmountRaw); + await enqueueSweepAfterDeposit(deposit.user_id, custodyType.id, chainAmount, deposit.id); + + const created = await depositSweepRepository.findByDepositTransactionId(deposit.id); + console.log( + JSON.stringify( + { + enqueued: !!created, + sweepId: created?.id ?? null, + status: created?.status ?? null, + batchId: created?.batch_id ?? null, + depositId: deposit.id, + userId: deposit.user_id, + custodyWalletType: sourceCode, + toCold: cold.address, + chainAmount: chainAmount.toString(), + blockchainTxId: txArg, + note: 'Next: Treasury → Submit sweeps for approval → Approvals → approve sweep_batch.', + }, + null, + 2 + ) + ); + if (!created) process.exit(6); +} + +main().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/backend/src/services/fundApprovalService.ts b/backend/src/services/fundApprovalService.ts index 8e3a05c1..9a200847 100644 --- a/backend/src/services/fundApprovalService.ts +++ b/backend/src/services/fundApprovalService.ts @@ -136,8 +136,11 @@ async function executeApprovedRequest( return { message: 'Pool funded', pools }; } case 'sweep_manual': { - const processed = await sweepService.processPendingSweeps({ unbatchedOnly: true }); - return { processed }; + // Legacy: promote open batches to Approvals; also run any rare unbatched pending rows. + const { createSweepBatchApprovalRequests } = await import('./sweepBatchService'); + const batchesSubmitted = await createSweepBatchApprovalRequests(); + const processedUnbatched = await sweepService.processPendingSweeps({ unbatchedOnly: true }); + return { batchesSubmitted, processedUnbatched }; } case 'sweep_batch': { const { batchId } = request.payload as { batchId: string }; diff --git a/docker-compose.yml b/docker-compose.yml index 60a6f781..aab1a475 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -48,6 +48,12 @@ x-backend-common: &backend-common POLYGON_CONFIRMATIONS: ${POLYGON_CONFIRMATIONS:-8} USDC_POLYGON_CONTRACT: ${USDC_POLYGON_CONTRACT:-} ALLOW_WITHDRAWALS: ${ALLOW_WITHDRAWALS:-false} + # Treasury: auto-enqueue deposit → cold sweeps (requires active cold wallet in Admin → Treasury) + SWEEP_ENABLED: ${SWEEP_ENABLED:-false} + 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} + SWEEP_TRON_GAS_TOPUP_SUN: ${SWEEP_TRON_GAS_TOPUP_SUN:-15000000} RATE_LIMIT_MAX: ${RATE_LIMIT_MAX:-2000} INITIAL_SETUP_TOKEN: ${INITIAL_SETUP_TOKEN:-} # Emergency Super Admin 2FA reset CLI only (not an HTTP API). Min 32 chars; leave empty to disable break-glass. diff --git a/docs/DEPLOY-VPS.md b/docs/DEPLOY-VPS.md index 0f8ad089..aad5127c 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -76,6 +76,7 @@ nano .env # ou vim | `BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS` | Re-scan chevauchant chaque poll (défaut `5000`) | | `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) | | `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 | @@ -423,6 +424,74 @@ sudo docker compose run --rm --no-deps --build backend \ 4. Logs backend : `[deposit] USDT_BEP20` / `[deposit] credited USDT_BEP20`. +### Test trésorerie — Cold wallet + Sweep + Cold→Hot (BEP20) + +Objectif : valider le circuit **Dépôt user → adresse HD dépôt → Sweep → Cold → alimentation Hot → Retrait**. + +#### Prérequis + +1. Hot BSC déjà seedé et financé en **BNB** (gas pour sweeps + retraits). +2. Créer une adresse **cold** BEP20 sous votre contrôle (MetaMask / hardware / cold storage) — **distincte** du hot et des adresses user. +3. Dans le `.env` VPS : + +```env +SWEEP_ENABLED=true +# 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 +``` + +4. Recréer le backend pour injecter les vars (`docker-compose` les passe désormais) : + +```bash +sudo docker compose --profile http up -d --force-recreate backend +# ou profil https-dns selon votre stack +``` + +5. Admin → **Treasury** : chip **Sweeps enabled**. Pour **USDT (BEP20)** : coller l’adresse cold → **Save cold**. + +#### A. Sweep dépôt → Cold + +| Étape | Action | Vérifier | +|-------|--------|----------| +| 1 | Micro-dépôt BEP20 vers l’adresse Receive user (ou réutiliser un dépôt déjà on-chain sur l’HD) | Ledger crédité ; solde USDT encore sur l’**adresse de dépôt** (pas le hot) | +| 2 | Si le dépôt a été crédité **avant** cold/`SWEEP_ENABLED` : enqueue manuel | Script ci-dessous | +| 3 | Treasury → table Deposit sweeps : statut `pending` | Ligne vers l’adresse cold | +| 4 | **Submit sweeps for approval** (ou attendre ~15 min le job auto) | Message : lot soumis | +| 5 | **Approvals** → approuver `sweep_batch` (super_admin) | Backend : gas BNB hot→dépôt si besoin, puis USDT dépôt→cold | +| 6 | BscScan cold + Treasury | Solde USDT cold ↑ ; sweep `completed` + tx hash ; logs `[sweep]` | + +Enqueue d’un dépôt déjà crédité : + +```bash +sudo docker compose run --rm --no-deps --build backend \ + node dist/scripts/enqueueSweepForDepositTx.js \ + --tx=0xVOTRE_TX_HASH_DEPOT +``` + +Échecs typiques : pas de cold BEP20, `SWEEP_ENABLED=false` (chip Sweeps disabled), hot BNB insuffisant pour le top-up gas, sweep `failed` → message d’erreur dans Treasury. + +> Le sweep **ne touche pas** le ledger utilisateur (déjà crédité au dépôt). Il déplace uniquement l’USDT on-chain de l’HD vers le cold. + +#### B. Cold → Hot (float retraits) + +Le transfert on-chain est **manuel** (clé cold hors plateforme) ; Prediqo enregistre la demande + la confirmation. + +1. Treasury → **Cold → Hot funding** : wallet type ID **2** (USDT_BEP20 en général), montant en **unités brutes 18 déc.** (ex. `1000000000000000000` = 1 USDT), notes optionnelles → **Request funding** → Approvals. +2. Après approbation : transferrer manuellement USDT BEP20 **cold → hot** (`0x2950…` ou l’adresse hot affichée). +3. Treasury → **Confirm tx** avec le hash BscScan. +4. Vérifier le solde USDT hot on-chain (Treasury / explorateur). + +#### C. Cycle complet + +1. Dépôt user BEP20 → crédit ledger. +2. Sweep approuvé → USDT sur cold. +3. Cold→Hot confirmé → float hot reconstitué. +4. Retrait user BEP20 (kill-switch + rail withdraw on) → débit ledger + tx depuis le **hot**. + +Checklist traçabilité : transaction dépôt, ligne `deposit_sweeps`, demande Approvals `sweep_batch` / `treasury_cold_to_hot`, funding confirmé, retrait + audit logs. + ### Prérequis communs | Étape | Détail | diff --git a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx index 8a19d76a..ddeddf89 100644 --- a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx +++ b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx @@ -436,7 +436,7 @@ export function TreasuryAdminPage() {