After starting the sweep and cold wallet testing
This commit is contained in:
parent
a1a8a04984
commit
4661b6c66e
@ -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)
|
||||
|
||||
@ -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<void> {
|
||||
try {
|
||||
@ -50,17 +51,17 @@ export async function listSweeps(req: AuthRequest, res: Response): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
export async function runSweeps(req: AuthRequest, res: Response): Promise<void> {
|
||||
export async function runSweeps(_req: AuthRequest, res: Response): Promise<void> {
|
||||
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' });
|
||||
|
||||
122
backend/src/scripts/enqueueSweepForDepositTx.ts
Normal file
122
backend/src/scripts/enqueueSweepForDepositTx.ts
Normal file
@ -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<void> {
|
||||
const txArg = process.argv.find((a) => a.startsWith('--tx='))?.slice('--tx='.length).trim();
|
||||
if (!txArg) {
|
||||
console.error('Usage: node dist/scripts/enqueueSweepForDepositTx.js --tx=<blockchain_tx_hash>');
|
||||
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<string, unknown>;
|
||||
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);
|
||||
});
|
||||
@ -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 };
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -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 |
|
||||
|
||||
@ -436,7 +436,7 @@ export function TreasuryAdminPage() {
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
disabled={runSweepsMut.isPending}
|
||||
disabled={runSweepsMut.isPending || !overview?.sweepEnabled}
|
||||
onClick={() => void runSweepsMut.mutateAsync()}
|
||||
sx={{ alignSelf: { xs: 'stretch', sm: 'auto' } }}
|
||||
>
|
||||
|
||||
@ -1534,7 +1534,7 @@ export const en = {
|
||||
pendingSweeps: '{{count}} pending sweeps',
|
||||
failedSweeps: '{{count}} failed sweeps',
|
||||
sweepDisabledHint:
|
||||
'Set SWEEP_ENABLED=true in backend .env to auto-move deposits to cold storage.',
|
||||
'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.',
|
||||
coldOnChain: 'Cold: {{address}} · USDT {{balance}}',
|
||||
hotOnChain: 'Hot: {{address}} · USDT {{balance}}',
|
||||
coldGasOnChain: 'Cold gas ({{symbol}}): {{balance}}',
|
||||
@ -1550,8 +1550,8 @@ export const en = {
|
||||
fundingTitle: 'Cold → Hot funding',
|
||||
fundingSubtitle:
|
||||
'Create a request, transfer manually from cold wallet, then confirm with the blockchain transaction ID.',
|
||||
walletTypeId: 'Wallet type ID (USDT_TRC20)',
|
||||
amountRaw: 'Amount (raw units)',
|
||||
walletTypeId: 'Wallet type ID (1=TRC20, 2=BEP20 typically)',
|
||||
amountRaw: 'Amount (raw units: TRC20 6 dec, BEP20 18 dec)',
|
||||
notes: 'Notes',
|
||||
requestFunding: 'Request funding for approval',
|
||||
amount: 'Amount',
|
||||
@ -1565,7 +1565,8 @@ export const en = {
|
||||
tx: 'Tx',
|
||||
confirmDialogTitle: 'Confirm cold → hot transfer',
|
||||
blockchainTxId: 'Blockchain transaction ID',
|
||||
sweepPending: 'Sweep request submitted — pending super-admin approval',
|
||||
sweepPending:
|
||||
'Sweep batch(es) submitted — approve under Approvals to broadcast USDT to cold.',
|
||||
fundingPending: 'Funding request submitted — pending super-admin approval',
|
||||
},
|
||||
security: {
|
||||
|
||||
@ -1550,7 +1550,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 backend pour déplacer automatiquement les dépôts vers le cold storage.',
|
||||
'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.',
|
||||
coldOnChain: 'Cold : {{address}} · USDT {{balance}}',
|
||||
hotOnChain: 'Hot : {{address}} · USDT {{balance}}',
|
||||
coldGasOnChain: 'Gas cold ({{symbol}}) : {{balance}}',
|
||||
@ -1566,8 +1566,8 @@ export const fr = {
|
||||
fundingTitle: 'Alimentation Cold → Hot',
|
||||
fundingSubtitle:
|
||||
'Créez une demande, transférez manuellement depuis le cold wallet, puis confirmez avec l’ID de transaction blockchain.',
|
||||
walletTypeId: 'ID type wallet (USDT_TRC20)',
|
||||
amountRaw: 'Montant (unités brutes)',
|
||||
walletTypeId: 'ID type wallet (1=TRC20, 2=BEP20 en général)',
|
||||
amountRaw: 'Montant (unités brutes : TRC20 6 déc., BEP20 18 déc.)',
|
||||
notes: 'Notes',
|
||||
requestFunding: 'Demander un financement (approbation)',
|
||||
amount: 'Montant',
|
||||
@ -1581,7 +1581,8 @@ export const fr = {
|
||||
tx: 'Tx',
|
||||
confirmDialogTitle: 'Confirmer le transfert cold → hot',
|
||||
blockchainTxId: 'ID transaction blockchain',
|
||||
sweepPending: 'Demande de sweep soumise — en attente d’approbation super-admin',
|
||||
sweepPending:
|
||||
'Lot(s) de sweep soumis — approuvez sous Approvals pour diffuser l’USDT vers le cold.',
|
||||
fundingPending: 'Demande de financement soumise — en attente d’approbation super-admin',
|
||||
},
|
||||
security: {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user