From add1e69f5b706e37c141934c13b3b71b602a8b5f Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 15 Sep 2026 13:42:57 +0200 Subject: [PATCH] After adding additionnel configuration for validations --- .env.example | 2 + backend/src/config/index.ts | 5 + .../src/controllers/fundApprovalController.ts | 58 +- backend/src/controllers/treasuryController.ts | 60 ++ backend/src/db/connection.ts | 2 + backend/src/db/schema.sql | 85 ++- backend/src/models/transaction.model.ts | 9 +- backend/src/rbac/permissionCatalog.ts | 16 + .../repositories/approvalPolicyRepository.ts | 229 +++++++ .../fundOperationRequestRepository.ts | 110 +++- .../fundOperationVoteRepository.ts | 76 +++ backend/src/routes/index.ts | 22 + backend/src/services/approvalPolicyEngine.ts | 208 ++++++ backend/src/services/fundApprovalService.ts | 612 +++++++++++++++--- backend/src/services/treasuryService.ts | 145 +++++ backend/src/services/withdrawalService.ts | 189 +++++- backend/src/validation/adminSchemas.ts | 35 + docker-compose.yml | 2 + docs/DEPLOY-VPS.md | 28 +- .../reports/problems/problems-report.html | 2 +- prediqo_web/src/app/router/router.tsx | 2 + .../approvals/ApprovalPoliciesPage.tsx | 525 +++++++++++++++ .../src/features/approvals/ApprovalsPage.tsx | 85 ++- .../src/features/options/OptionsPage.tsx | 11 + .../features/treasury/TreasuryAdminPage.tsx | 242 ++++++- prediqo_web/src/shared/auth/permissions.ts | 4 + prediqo_web/src/shared/i18n/locales/en.ts | 75 ++- prediqo_web/src/shared/i18n/locales/fr.ts | 75 ++- prediqo_web/src/shared/layout/AppShell.tsx | 12 +- 29 files changed, 2750 insertions(+), 176 deletions(-) create mode 100644 backend/src/repositories/approvalPolicyRepository.ts create mode 100644 backend/src/repositories/fundOperationVoteRepository.ts create mode 100644 backend/src/services/approvalPolicyEngine.ts create mode 100644 prediqo_web/src/features/approvals/ApprovalPoliciesPage.tsx diff --git a/.env.example b/.env.example index bd27df47..90f7d170 100644 --- a/.env.example +++ b/.env.example @@ -94,6 +94,8 @@ SWEEP_ENABLED=false SWEEP_MIN_AMOUNT_RAW=1000000 # SWEEP_BSC_GAS_TOPUP_WEI=1000000000000000 # SWEEP_TRON_GAS_TOPUP_SUN=15000000 +# Optional USDT left on hot after Hot→Cold (raw units; default 0). BEP20 18 dec / TRC20 6 dec. +# HOT_USDT_MIN_RESERVE_RAW=0 RATE_LIMIT_MAX=2000 # Ports dédiés Prediqo (n'utilise pas 80/443 du VPS) diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index beee97a1..57de766d 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -197,6 +197,11 @@ export const config = { sweepMinAmountRaw: process.env.SWEEP_MIN_AMOUNT_RAW || '1000000', /** TRX sent from hot wallet to fund TRC20 sweeps (sun) */ tronGasTopUpSun: process.env.SWEEP_TRON_GAS_TOPUP_SUN || '15000000', + /** + * Min USDT (chain raw units) to leave on hot after Hot→Cold USDT transfer. + * Default 0 = no USDT floor (native withdrawal gas reserve still enforced). + */ + hotUsdtMinReserveRaw: (process.env.HOT_USDT_MIN_RESERVE_RAW || '0').trim() || '0', /** MATIC sent from hot wallet to fund USDC sweeps (wei) */ polygonGasTopUpWei: process.env.SWEEP_POLYGON_GAS_TOPUP_WEI || '100000000000000000', }, diff --git a/backend/src/controllers/fundApprovalController.ts b/backend/src/controllers/fundApprovalController.ts index 861555ac..6d7280f0 100644 --- a/backend/src/controllers/fundApprovalController.ts +++ b/backend/src/controllers/fundApprovalController.ts @@ -2,6 +2,7 @@ import { Response } from 'express'; import { AuthRequest } from '../middleware/auth'; import * as fundApprovalService from '../services/fundApprovalService'; import type { FundOperationStatus, FundOperationType } from '../repositories/fundOperationRequestRepository'; +import type { PolicyInput } from '../repositories/approvalPolicyRepository'; export async function createFundRequest(req: AuthRequest, res: Response): Promise { try { @@ -31,12 +32,10 @@ export async function listFundRequests(req: AuthRequest, res: Response): Promise const operationType = (req.query.operationType as FundOperationType) || undefined; const limit = parseInt((req.query.limit as string) || '50', 10); const offset = parseInt((req.query.offset as string) || '0', 10); - const result = await fundApprovalService.listFundRequests({ - status, - operationType, - limit, - offset, - }); + const result = await fundApprovalService.listFundRequests( + { status, operationType, limit, offset }, + req.user!.userId + ); res.json(result); } catch (e) { res.status(500).json({ error: e instanceof Error ? e.message : 'Failed to list requests' }); @@ -45,7 +44,7 @@ export async function listFundRequests(req: AuthRequest, res: Response): Promise export async function getFundRequest(req: AuthRequest, res: Response): Promise { try { - const result = await fundApprovalService.getFundRequest(req.params.id); + const result = await fundApprovalService.getFundRequest(req.params.id, req.user!.userId); if (!result) { res.status(404).json({ error: 'Request not found' }); return; @@ -94,3 +93,48 @@ export async function cancelFundRequest(req: AuthRequest, res: Response): Promis res.status(400).json({ error: msg }); } } + +export async function listApprovalPolicies(req: AuthRequest, res: Response): Promise { + try { + const items = await fundApprovalService.listApprovalPolicies(req.user!.userId); + res.json({ items }); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to list policies'; + res.status(msg.includes('Permission') ? 403 : 500).json({ error: msg }); + } +} + +export async function listPolicyRevisions(req: AuthRequest, res: Response): Promise { + try { + const limit = parseInt((req.query.limit as string) || '50', 10); + const items = await fundApprovalService.listPolicyRevisions(req.user!.userId, limit); + res.json({ items }); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to list revisions'; + res.status(msg.includes('Permission') ? 403 : 500).json({ error: msg }); + } +} + +export async function draftPolicyChange(req: AuthRequest, res: Response): Promise { + try { + const { after, note } = req.body as { after?: PolicyInput[]; note?: string }; + if (!Array.isArray(after)) { + res.status(400).json({ error: 'after (policies array) is required' }); + return; + } + const result = await fundApprovalService.draftPolicyChange({ + after, + note, + requestedBy: req.user!.userId, + }); + res.status(202).json({ + requestId: result.id, + status: result.status, + message: 'Policy change submitted — approve under Approvals to apply', + request: result, + }); + } catch (e) { + const msg = e instanceof Error ? e.message : 'Failed to draft policy change'; + res.status(400).json({ error: msg }); + } +} diff --git a/backend/src/controllers/treasuryController.ts b/backend/src/controllers/treasuryController.ts index c3bf8f9d..5a231b27 100644 --- a/backend/src/controllers/treasuryController.ts +++ b/backend/src/controllers/treasuryController.ts @@ -139,6 +139,66 @@ export async function cancelFunding(req: AuthRequest, res: Response): Promise { + try { + const walletTypeId = parseInt(String(req.query.walletTypeId ?? ''), 10); + if (!Number.isFinite(walletTypeId) || walletTypeId <= 0) { + res.status(400).json({ error: 'walletTypeId is required' }); + return; + } + res.json(await treasuryService.previewHotToColdUsdt(walletTypeId)); + } catch (e) { + res.status(400).json({ error: e instanceof Error ? e.message : 'Hot→Cold preview failed' }); + } +} + +export async function requestHotToColdUsdt(req: AuthRequest, res: Response): Promise { + try { + const { walletTypeId, amount, notes } = req.body as { + walletTypeId?: number; + amount?: string | number; + notes?: string; + }; + if (typeof walletTypeId !== 'number' || amount == null) { + res.status(400).json({ error: 'walletTypeId and amount are required' }); + return; + } + const preview = await treasuryService.previewHotToColdUsdt(walletTypeId); + const amountRaw = BigInt(amount); + if (amountRaw <= 0n) { + res.status(400).json({ error: 'amount must be greater than zero' }); + return; + } + if (!preview.gasOk) { + res.status(400).json({ error: preview.gasHint || 'Hot wallet has insufficient native gas' }); + return; + } + if (amountRaw > BigInt(preview.maxSendable)) { + res.status(400).json({ + error: `Amount exceeds max sendable after USDT reserve. Max: ${preview.maxSendable}`, + }); + return; + } + const result = await fundApprovalService.createFundRequest({ + operationType: 'treasury_hot_to_cold', + payload: { + walletTypeId, + amountRaw: amountRaw.toString(), + notes, + }, + requestedBy: req.user!.userId, + }); + res.status(202).json({ + requestId: result.id, + status: result.status, + message: + 'Hot→Cold USDT submitted — approve under Approvals; the platform will send from hot to cold', + }); + } catch (e) { + res.status(400).json({ error: e instanceof Error ? e.message : 'Hot→Cold request failed' }); + } +} + export async function listStuckDeposits(_req: AuthRequest, res: Response): Promise { try { res.json(await treasuryService.listStuckDeposits()); diff --git a/backend/src/db/connection.ts b/backend/src/db/connection.ts index 83b09ec2..0d22f9b4 100644 --- a/backend/src/db/connection.ts +++ b/backend/src/db/connection.ts @@ -178,6 +178,8 @@ export async function runMigrations(): Promise { await client.query(sql); const { syncPermissionCatalog } = await import('../rbac/syncPermissions'); await syncPermissionCatalog(); + const { ensureDefaultPoliciesSeeded } = await import('../repositories/approvalPolicyRepository'); + await ensureDefaultPoliciesSeeded(); } finally { client.release(); } diff --git a/backend/src/db/schema.sql b/backend/src/db/schema.sql index c07852c4..7ae033ed 100644 --- a/backend/src/db/schema.sql +++ b/backend/src/db/schema.sql @@ -130,18 +130,26 @@ CREATE TABLE IF NOT EXISTS fund_operation_requests ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), operation_type VARCHAR(64) NOT NULL CHECK (operation_type IN ( - 'ledger_credit', 'treasury_cold_to_hot', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', - 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas' + 'ledger_credit', 'treasury_cold_to_hot', 'treasury_hot_to_cold', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', + 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas', 'user_withdrawal', 'approval_policy_change' )), status VARCHAR(32) NOT NULL DEFAULT 'pending_approval' CHECK (status IN ( - 'pending_approval', 'approved', 'rejected', 'executed', 'failed', 'cancelled' + 'pending_approval', 'approved', 'processing', 'confirmed', 'executed', 'failed', 'rejected', 'cancelled' )), payload JSONB NOT NULL DEFAULT '{}', requested_by UUID NOT NULL REFERENCES users(id), approved_by UUID REFERENCES users(id), rejection_reason TEXT, execution_result JSONB, + policy_id UUID, + policy_snapshot JSONB, + required_quorum JSONB, + amount_raw TEXT, + asset_code VARCHAR(64), + network VARCHAR(32), + from_address VARCHAR(255), + to_address VARCHAR(255), created_at TIMESTAMPTZ DEFAULT NOW(), approved_at TIMESTAMPTZ, executed_at TIMESTAMPTZ @@ -155,10 +163,77 @@ ALTER TABLE fund_operation_requests DROP CONSTRAINT IF EXISTS fund_operation_req ALTER TABLE fund_operation_requests ADD CONSTRAINT fund_operation_requests_operation_type_check CHECK (operation_type IN ( - 'ledger_credit', 'treasury_cold_to_hot', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', - 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas' + 'ledger_credit', 'treasury_cold_to_hot', 'treasury_hot_to_cold', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', + 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas', 'user_withdrawal', 'approval_policy_change' )); +ALTER TABLE fund_operation_requests DROP CONSTRAINT IF EXISTS fund_operation_requests_status_check; +ALTER TABLE fund_operation_requests + ADD CONSTRAINT fund_operation_requests_status_check + CHECK (status IN ( + 'pending_approval', 'approved', 'processing', 'confirmed', 'executed', 'failed', 'rejected', 'cancelled' + )); + +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS policy_id UUID; +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS policy_snapshot JSONB; +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS required_quorum JSONB; +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS amount_raw TEXT; +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS asset_code VARCHAR(64); +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS network VARCHAR(32); +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS from_address VARCHAR(255); +ALTER TABLE fund_operation_requests ADD COLUMN IF NOT EXISTS to_address VARCHAR(255); + +-- Configurable approval policies (N-of-M) +CREATE TABLE IF NOT EXISTS approval_policies ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(128) NOT NULL, + enabled BOOLEAN NOT NULL DEFAULT true, + priority INTEGER NOT NULL DEFAULT 100, + operation_type VARCHAR(64), + wallet_type_id INTEGER REFERENCES wallet_types(id), + network VARCHAR(32), + amount_min_raw TEXT, + amount_max_raw TEXT, + source_wallet_kind VARCHAR(16) NOT NULL DEFAULT 'any' + CHECK (source_wallet_kind IN ('hot', 'cold', 'hd', 'user', 'any')), + dest_wallet_kind VARCHAR(16) NOT NULL DEFAULT 'any' + CHECK (dest_wallet_kind IN ('hot', 'cold', 'hd', 'user', 'any')), + decision JSONB NOT NULL DEFAULT '{}', + version INTEGER NOT NULL DEFAULT 1, + updated_by UUID REFERENCES users(id), + created_at TIMESTAMPTZ DEFAULT NOW(), + updated_at TIMESTAMPTZ DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_approval_policies_enabled_priority + ON approval_policies(enabled, priority); + +CREATE TABLE IF NOT EXISTS approval_policy_revisions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + change_request_id UUID REFERENCES fund_operation_requests(id), + actor_id UUID REFERENCES users(id), + before_snapshot JSONB NOT NULL DEFAULT '[]', + after_snapshot JSONB NOT NULL DEFAULT '[]', + note TEXT, + created_at TIMESTAMPTZ DEFAULT NOW() +); + +CREATE INDEX IF NOT EXISTS idx_approval_policy_revisions_created + ON approval_policy_revisions(created_at DESC); + +CREATE TABLE IF NOT EXISTS fund_operation_votes ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + request_id UUID NOT NULL REFERENCES fund_operation_requests(id) ON DELETE CASCADE, + voter_id UUID NOT NULL REFERENCES users(id), + decision VARCHAR(16) NOT NULL CHECK (decision IN ('approve', 'reject')), + reason TEXT, + voter_roles JSONB NOT NULL DEFAULT '[]', + created_at TIMESTAMPTZ DEFAULT NOW(), + UNIQUE (request_id, voter_id) +); + +CREATE INDEX IF NOT EXISTS idx_fund_operation_votes_request ON fund_operation_votes(request_id); + -- Batched automatic deposit sweeps awaiting approval CREATE TABLE IF NOT EXISTS deposit_sweep_batches ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), diff --git a/backend/src/models/transaction.model.ts b/backend/src/models/transaction.model.ts index a9d2e004..52153e2e 100644 --- a/backend/src/models/transaction.model.ts +++ b/backend/src/models/transaction.model.ts @@ -11,7 +11,14 @@ export interface Transaction { type: 'deposit' | 'withdrawal' | 'transfer'; amount: string; fee: string; - status: 'pending' | 'confirming' | 'completed' | 'failed'; + status: + | 'pending' + | 'pending_approval' + | 'broadcasting' + | 'confirming' + | 'completed' + | 'failed' + | 'ledger_finalize_failed'; blockchain_tx_id: string | null; from_address: string | null; to_address: string | null; diff --git a/backend/src/rbac/permissionCatalog.ts b/backend/src/rbac/permissionCatalog.ts index eab0dc50..0aafe297 100644 --- a/backend/src/rbac/permissionCatalog.ts +++ b/backend/src/rbac/permissionCatalog.ts @@ -65,6 +65,20 @@ export const PERMISSION_CATALOG: PermissionDef[] = [ resource: 'fund_operations', action: 'approve', }, + { + key: 'approval_policy.view', + description: 'View approval policies and revision history', + category: 'fund_operations', + resource: 'approval_policies', + action: 'view', + }, + { + key: 'approval_policy.manage', + description: 'Submit approval policy changes for Approvals', + category: 'fund_operations', + resource: 'approval_policies', + action: 'manage', + }, { key: 'user.manage_roles', description: 'Assign roles and manage RBAC', @@ -169,6 +183,8 @@ export const PERMISSION_CATALOG: PermissionDef[] = [ // Granular — fund operations p('fund_operations', 'request', 'Submit fund operation requests', 'fund_operations', ['fund_operation.request']), p('fund_operations', 'approve', 'Approve fund operations', 'fund_operations', ['fund_operation.approve']), + p('approval_policies', 'view', 'View approval policies', 'fund_operations', ['approval_policy.view']), + p('approval_policies', 'manage', 'Manage approval policies', 'fund_operations', ['approval_policy.manage']), // Granular — ledger p('ledger_credit', 'manage', 'Grant ledger credits to users', 'users', ['ledger.credit']), diff --git a/backend/src/repositories/approvalPolicyRepository.ts b/backend/src/repositories/approvalPolicyRepository.ts new file mode 100644 index 00000000..91c71356 --- /dev/null +++ b/backend/src/repositories/approvalPolicyRepository.ts @@ -0,0 +1,229 @@ +/** + * Approval policies — configurable N-of-M rules for sensitive fund operations. + */ + +import { query } from '../db/connection'; + +export type WalletKind = 'hot' | 'cold' | 'hd' | 'user' | 'any'; + +export type QuorumSlot = { + role?: string; + permission?: string; + count: number; +}; + +export type PolicyDecision = { + mode: 'auto_execute' | 'require_approvals'; + quorum: QuorumSlot[]; + forbid_self_approve: boolean; + require_distinct_users?: boolean; +}; + +export type ApprovalPolicyRow = { + id: string; + name: string; + enabled: boolean; + priority: number; + operation_type: string | null; + wallet_type_id: number | null; + network: string | null; + amount_min_raw: string | null; + amount_max_raw: string | null; + source_wallet_kind: WalletKind; + dest_wallet_kind: WalletKind; + decision: PolicyDecision; + version: number; + updated_by: string | null; + created_at: Date; + updated_at: Date; +}; + +export type ApprovalPolicyRevisionRow = { + id: string; + change_request_id: string | null; + actor_id: string | null; + before_snapshot: unknown; + after_snapshot: unknown; + note: string | null; + created_at: Date; +}; + +function normalizeDecision(raw: unknown): PolicyDecision { + const d = (raw && typeof raw === 'object' ? raw : {}) as Partial; + const quorum = Array.isArray(d.quorum) + ? d.quorum + .map((s) => ({ + role: typeof s?.role === 'string' ? s.role : undefined, + permission: typeof s?.permission === 'string' ? s.permission : undefined, + count: Math.max(1, Number(s?.count) || 1), + })) + .filter((s) => s.role || s.permission) + : []; + return { + mode: d.mode === 'auto_execute' ? 'auto_execute' : 'require_approvals', + quorum, + forbid_self_approve: d.forbid_self_approve !== false, + require_distinct_users: d.require_distinct_users !== false, + }; +} + +function mapRow(row: Record): ApprovalPolicyRow { + return { + id: String(row.id), + name: String(row.name), + enabled: Boolean(row.enabled), + priority: Number(row.priority), + operation_type: row.operation_type != null ? String(row.operation_type) : null, + wallet_type_id: row.wallet_type_id != null ? Number(row.wallet_type_id) : null, + network: row.network != null ? String(row.network) : null, + amount_min_raw: row.amount_min_raw != null ? String(row.amount_min_raw) : null, + amount_max_raw: row.amount_max_raw != null ? String(row.amount_max_raw) : null, + source_wallet_kind: (row.source_wallet_kind as WalletKind) || 'any', + dest_wallet_kind: (row.dest_wallet_kind as WalletKind) || 'any', + decision: normalizeDecision(row.decision), + version: Number(row.version ?? 1), + updated_by: row.updated_by != null ? String(row.updated_by) : null, + created_at: row.created_at as Date, + updated_at: row.updated_at as Date, + }; +} + +export async function listEnabledPolicies(): Promise { + const rows = await query[]>( + `SELECT * FROM approval_policies WHERE enabled = true ORDER BY priority ASC, created_at ASC` + ); + return rows.map(mapRow); +} + +export async function listAllPolicies(): Promise { + const rows = await query[]>( + `SELECT * FROM approval_policies ORDER BY priority ASC, created_at ASC` + ); + return rows.map(mapRow); +} + +export async function findById(id: string): Promise { + const rows = await query[]>( + `SELECT * FROM approval_policies WHERE id = $1`, + [id] + ); + return rows[0] ? mapRow(rows[0]) : null; +} + +export async function countPolicies(): Promise { + const rows = await query<{ count: string }[]>( + `SELECT COUNT(*)::text AS count FROM approval_policies` + ); + return parseInt(rows[0]?.count ?? '0', 10); +} + +export type PolicyInput = { + name: string; + enabled?: boolean; + priority?: number; + operationType?: string | null; + walletTypeId?: number | null; + network?: string | null; + amountMinRaw?: string | null; + amountMaxRaw?: string | null; + sourceWalletKind?: WalletKind; + destWalletKind?: WalletKind; + decision: PolicyDecision; +}; + +export async function replaceAllPolicies( + policies: PolicyInput[], + updatedBy: string | null +): Promise { + await query(`DELETE FROM approval_policies`); + const out: ApprovalPolicyRow[] = []; + for (const p of policies) { + const rows = await query[]>( + `INSERT INTO approval_policies ( + name, enabled, priority, operation_type, wallet_type_id, network, + amount_min_raw, amount_max_raw, source_wallet_kind, dest_wallet_kind, + decision, version, updated_by, updated_at + ) VALUES ( + $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, 1, $12, NOW() + ) RETURNING *`, + [ + p.name, + p.enabled !== false, + p.priority ?? 100, + p.operationType ?? null, + p.walletTypeId ?? null, + p.network ?? null, + p.amountMinRaw ?? null, + p.amountMaxRaw ?? null, + p.sourceWalletKind ?? 'any', + p.destWalletKind ?? 'any', + JSON.stringify(normalizeDecision(p.decision)), + updatedBy, + ] + ); + out.push(mapRow(rows[0])); + } + return out; +} + +export async function insertRevision(input: { + changeRequestId?: string | null; + actorId: string | null; + beforeSnapshot: unknown; + afterSnapshot: unknown; + note?: string | null; +}): Promise { + const rows = await query( + `INSERT INTO approval_policy_revisions ( + change_request_id, actor_id, before_snapshot, after_snapshot, note + ) VALUES ($1, $2, $3::jsonb, $4::jsonb, $5) + RETURNING *`, + [ + input.changeRequestId ?? null, + input.actorId, + JSON.stringify(input.beforeSnapshot ?? []), + JSON.stringify(input.afterSnapshot ?? []), + input.note ?? null, + ] + ); + return rows[0]; +} + +export async function listRevisions(limit = 50): Promise { + return query( + `SELECT * FROM approval_policy_revisions ORDER BY created_at DESC LIMIT $1`, + [Math.min(limit, 200)] + ); +} + +/** Default fail-closed + current-platform behavior seed. */ +export function defaultPolicySeed(): PolicyInput[] { + const superAdminQuorum: PolicyDecision = { + mode: 'require_approvals', + quorum: [{ role: 'super_admin', count: 1 }], + forbid_self_approve: true, + require_distinct_users: true, + }; + return [ + { + name: 'Default — all fund ops (1 Super Admin)', + enabled: true, + priority: 1000, + operationType: null, + decision: superAdminQuorum, + }, + { + name: 'Approval policy changes (1 other Super Admin)', + enabled: true, + priority: 10, + operationType: 'approval_policy_change', + decision: superAdminQuorum, + }, + ]; +} + +export async function ensureDefaultPoliciesSeeded(): Promise { + const count = await countPolicies(); + if (count > 0) return; + await replaceAllPolicies(defaultPolicySeed(), null); +} diff --git a/backend/src/repositories/fundOperationRequestRepository.ts b/backend/src/repositories/fundOperationRequestRepository.ts index ef2e34d6..b27da0e3 100644 --- a/backend/src/repositories/fundOperationRequestRepository.ts +++ b/backend/src/repositories/fundOperationRequestRepository.ts @@ -7,18 +7,23 @@ import { query } from '../db/connection'; export type FundOperationType = | 'ledger_credit' | 'treasury_cold_to_hot' + | 'treasury_hot_to_cold' | 'bonus_pool_fund' | 'sweep_manual' | 'sweep_batch' | 'treasury_hot_to_cold_gas' - | 'treasury_cold_to_hot_gas'; + | 'treasury_cold_to_hot_gas' + | 'user_withdrawal' + | 'approval_policy_change'; export type FundOperationStatus = | 'pending_approval' | 'approved' - | 'rejected' + | 'processing' + | 'confirmed' | 'executed' | 'failed' + | 'rejected' | 'cancelled'; export type FundOperationRequestRow = { @@ -30,23 +35,68 @@ export type FundOperationRequestRow = { approved_by: string | null; rejection_reason: string | null; execution_result: Record | null; + policy_id: string | null; + policy_snapshot: Record | null; + required_quorum: unknown[] | null; + amount_raw: string | null; + asset_code: string | null; + network: string | null; + from_address: string | null; + to_address: string | null; created_at: Date; approved_at: Date | null; executed_at: Date | null; }; +export type CreateFundRequestMeta = { + policyId?: string | null; + policySnapshot?: Record | null; + requiredQuorum?: unknown[] | null; + amountRaw?: string | null; + assetCode?: string | null; + network?: string | null; + fromAddress?: string | null; + toAddress?: string | null; +}; + +function normalizeRow(row: FundOperationRequestRow): FundOperationRequestRow { + if (row.status === 'executed') { + return { ...row, status: 'confirmed' }; + } + return row; +} + export async function createRequest(input: { operationType: FundOperationType; payload: Record; requestedBy: string; + meta?: CreateFundRequestMeta; }): Promise { + const m = input.meta ?? {}; const rows = await query( - `INSERT INTO fund_operation_requests (operation_type, payload, requested_by) - VALUES ($1, $2::jsonb, $3) + `INSERT INTO fund_operation_requests ( + operation_type, payload, requested_by, + policy_id, policy_snapshot, required_quorum, + amount_raw, asset_code, network, from_address, to_address + ) VALUES ( + $1, $2::jsonb, $3, $4, $5::jsonb, $6::jsonb, $7, $8, $9, $10, $11 + ) RETURNING *`, - [input.operationType, JSON.stringify(input.payload), input.requestedBy] + [ + input.operationType, + JSON.stringify(input.payload), + input.requestedBy, + m.policyId ?? null, + m.policySnapshot != null ? JSON.stringify(m.policySnapshot) : null, + m.requiredQuorum != null ? JSON.stringify(m.requiredQuorum) : null, + m.amountRaw ?? null, + m.assetCode ?? null, + m.network ?? null, + m.fromAddress ?? null, + m.toAddress ?? null, + ] ); - return rows[0]; + return normalizeRow(rows[0]); } export async function findById(id: string): Promise { @@ -54,7 +104,7 @@ export async function findById(id: string): Promise { @@ -99,7 +153,18 @@ export async function markApproved(id: string, approvedBy: string): Promise { + const rows = await query( + `UPDATE fund_operation_requests + SET status = 'processing' + WHERE id = $1 AND status IN ('approved', 'pending_approval') + RETURNING *`, + [id] + ); + return rows[0] ? normalizeRow(rows[0]) : null; } export async function markRejected( @@ -114,16 +179,24 @@ export async function markRejected( RETURNING *`, [id, approvedBy, reason] ); - return rows[0] ?? null; + return rows[0] ? normalizeRow(rows[0]) : null; } +/** @deprecated prefer markConfirmed — kept for callers; writes status confirmed */ export async function markExecuted( id: string, executionResult: Record +): Promise { + await markConfirmed(id, executionResult); +} + +export async function markConfirmed( + id: string, + executionResult: Record ): Promise { await query( `UPDATE fund_operation_requests - SET status = 'executed', executed_at = NOW(), execution_result = $2::jsonb + SET status = 'confirmed', executed_at = NOW(), execution_result = $2::jsonb WHERE id = $1`, [id, JSON.stringify(executionResult)] ); @@ -146,5 +219,14 @@ export async function markCancelled(id: string): Promise { + await query( + `UPDATE fund_operation_requests + SET approved_by = $2, approved_at = COALESCE(approved_at, NOW()) + WHERE id = $1`, + [id, approvedBy] + ); } diff --git a/backend/src/repositories/fundOperationVoteRepository.ts b/backend/src/repositories/fundOperationVoteRepository.ts new file mode 100644 index 00000000..ef743fe5 --- /dev/null +++ b/backend/src/repositories/fundOperationVoteRepository.ts @@ -0,0 +1,76 @@ +/** + * Votes on fund operation approval requests (N-of-M). + */ + +import { query } from '../db/connection'; + +export type VoteDecision = 'approve' | 'reject'; + +export type FundOperationVoteRow = { + id: string; + request_id: string; + voter_id: string; + decision: VoteDecision; + reason: string | null; + voter_roles: string[]; + created_at: Date; +}; + +function mapRow(row: Record): FundOperationVoteRow { + const rolesRaw = row.voter_roles; + const roles = Array.isArray(rolesRaw) + ? rolesRaw.map(String) + : typeof rolesRaw === 'string' + ? (JSON.parse(rolesRaw) as string[]) + : []; + return { + id: String(row.id), + request_id: String(row.request_id), + voter_id: String(row.voter_id), + decision: row.decision as VoteDecision, + reason: row.reason != null ? String(row.reason) : null, + voter_roles: roles, + created_at: row.created_at as Date, + }; +} + +export async function listByRequest(requestId: string): Promise { + const rows = await query[]>( + `SELECT * FROM fund_operation_votes WHERE request_id = $1 ORDER BY created_at ASC`, + [requestId] + ); + return rows.map(mapRow); +} + +export async function findByRequestAndVoter( + requestId: string, + voterId: string +): Promise { + const rows = await query[]>( + `SELECT * FROM fund_operation_votes WHERE request_id = $1 AND voter_id = $2`, + [requestId, voterId] + ); + return rows[0] ? mapRow(rows[0]) : null; +} + +export async function insertVote(input: { + requestId: string; + voterId: string; + decision: VoteDecision; + reason?: string | null; + voterRoles: string[]; +}): Promise { + const rows = await query[]>( + `INSERT INTO fund_operation_votes (request_id, voter_id, decision, reason, voter_roles) + VALUES ($1, $2, $3, $4, $5::jsonb) + RETURNING *`, + [ + input.requestId, + input.voterId, + input.decision, + input.reason ?? null, + JSON.stringify(input.voterRoles), + ] + ); + return mapRow(rows[0]); +} diff --git a/backend/src/routes/index.ts b/backend/src/routes/index.ts index a4be0dfa..2bd08a47 100644 --- a/backend/src/routes/index.ts +++ b/backend/src/routes/index.ts @@ -35,6 +35,7 @@ import { adminLedgerCreditBodySchema, fundRequestCreateBodySchema, fundRequestRejectBodySchema, + approvalPolicyDraftBodySchema, securityAlertResolveBodySchema, securitySettingsBodySchema, adminUserSecurityBodySchema, @@ -322,6 +323,25 @@ router.delete( requirePermissions('fund_operation.request'), fundApprovalController.cancelFundRequest ); +router.get( + '/admin/approval-policies', + requireRoles('admin'), + requirePermissions('approval_policy.view'), + fundApprovalController.listApprovalPolicies +); +router.get( + '/admin/approval-policies/revisions', + requireRoles('admin'), + requirePermissions('approval_policy.view'), + fundApprovalController.listPolicyRevisions +); +router.post( + '/admin/approval-policies/draft-change', + requireRoles('admin'), + requirePermissions('approval_policy.manage'), + validateBody(approvalPolicyDraftBodySchema), + fundApprovalController.draftPolicyChange +); router.post( '/admin/users/:userId/verify-email', requireRoles('admin'), @@ -474,6 +494,8 @@ router.get('/admin/treasury/sweeps', requireRoles('admin'), requirePermissions(' router.post('/admin/treasury/sweeps/run', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.runSweeps); router.get('/admin/treasury/funding', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.listFunding); router.post('/admin/treasury/funding', requireRoles('admin'), requirePermissions('treasury.view'), validateBody(treasuryFundingBodySchema), treasuryController.requestFunding); +router.get('/admin/treasury/funding/hot-to-cold/preview', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.previewHotToColdUsdt); +router.post('/admin/treasury/funding/hot-to-cold', requireRoles('admin'), requirePermissions('treasury.view'), validateBody(treasuryFundingBodySchema), treasuryController.requestHotToColdUsdt); router.patch('/admin/treasury/funding/:fundingId/confirm', requireRoles('admin'), requirePermissions('treasury.view'), validateBody(treasuryFundingConfirmBodySchema), treasuryController.confirmFunding); router.delete('/admin/treasury/funding/:fundingId', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.cancelFunding); router.get('/admin/treasury/stuck-deposits', requireRoles('admin'), requirePermissions('treasury.view'), treasuryController.listStuckDeposits); diff --git a/backend/src/services/approvalPolicyEngine.ts b/backend/src/services/approvalPolicyEngine.ts new file mode 100644 index 00000000..e34690d4 --- /dev/null +++ b/backend/src/services/approvalPolicyEngine.ts @@ -0,0 +1,208 @@ +/** + * Evaluates configurable approval policies (N-of-M / auto-execute). + */ + +import * as approvalPolicyRepository from '../repositories/approvalPolicyRepository'; +import type { + ApprovalPolicyRow, + PolicyDecision, + QuorumSlot, + WalletKind, +} from '../repositories/approvalPolicyRepository'; +import type { FundOperationType } from '../repositories/fundOperationRequestRepository'; +import type { FundOperationVoteRow } from '../repositories/fundOperationVoteRepository'; + +export type EvaluateInput = { + operationType: FundOperationType | string; + amountRaw?: string | null; + walletTypeId?: number | null; + network?: string | null; + sourceKind?: WalletKind; + destKind?: WalletKind; +}; + +export type EvaluateResult = { + policy: ApprovalPolicyRow | null; + decision: PolicyDecision; + matchedBy: 'policy' | 'fail_closed_default'; +}; + +const FAIL_CLOSED: PolicyDecision = { + mode: 'require_approvals', + quorum: [{ role: 'super_admin', count: 1 }], + forbid_self_approve: true, + require_distinct_users: true, +}; + +function kindMatches(rule: WalletKind, actual: WalletKind | undefined): boolean { + if (rule === 'any') return true; + if (!actual || actual === 'any') return true; + return rule === actual; +} + +function amountInRange( + amountRaw: string | null | undefined, + minRaw: string | null, + maxRaw: string | null +): boolean { + if (amountRaw == null || amountRaw === '') { + return minRaw == null && maxRaw == null; + } + let amount: bigint; + try { + amount = BigInt(amountRaw); + } catch { + return false; + } + if (minRaw != null && minRaw !== '') { + try { + if (amount < BigInt(minRaw)) return false; + } catch { + return false; + } + } + if (maxRaw != null && maxRaw !== '') { + try { + if (amount > BigInt(maxRaw)) return false; + } catch { + return false; + } + } + return true; +} + +export function policyMatches(policy: ApprovalPolicyRow, input: EvaluateInput): boolean { + if (!policy.enabled) return false; + if (policy.operation_type && policy.operation_type !== input.operationType) return false; + if (policy.wallet_type_id != null && policy.wallet_type_id !== input.walletTypeId) return false; + if (policy.network && policy.network !== input.network) return false; + if (!kindMatches(policy.source_wallet_kind, input.sourceKind)) return false; + if (!kindMatches(policy.dest_wallet_kind, input.destKind)) return false; + if (!amountInRange(input.amountRaw, policy.amount_min_raw, policy.amount_max_raw)) return false; + return true; +} + +export async function evaluate(input: EvaluateInput): Promise { + await approvalPolicyRepository.ensureDefaultPoliciesSeeded(); + const policies = await approvalPolicyRepository.listEnabledPolicies(); + for (const policy of policies) { + if (policyMatches(policy, input)) { + return { + policy, + decision: policy.decision, + matchedBy: 'policy', + }; + } + } + return { + policy: null, + decision: FAIL_CLOSED, + matchedBy: 'fail_closed_default', + }; +} + +/** True if approve votes satisfy every quorum slot. */ +export function quorumSatisfied( + quorum: QuorumSlot[], + approveVotes: FundOperationVoteRow[], + voterHasRole: (voterId: string, role: string) => boolean, + voterHasPermission: (voterId: string, permission: string) => boolean +): boolean { + if (!quorum.length) return false; + const used = new Set(); + for (const slot of quorum) { + let filled = 0; + for (const vote of approveVotes) { + if (used.has(vote.voter_id)) continue; + const roleOk = slot.role ? voterHasRole(vote.voter_id, slot.role) || vote.voter_roles.includes(slot.role) : false; + const permOk = slot.permission ? voterHasPermission(vote.voter_id, slot.permission) : false; + // Prefer roles recorded on the vote; async permission checked by caller via cache map + const ok = slot.role + ? vote.voter_roles.includes(slot.role) || roleOk + : permOk; + if (!ok && slot.permission) { + // permission checked externally — caller passes precomputed eligibility + continue; + } + if (slot.role && !vote.voter_roles.includes(slot.role)) continue; + if (!slot.role && slot.permission) { + // handled below with permission set on vote metadata — skip if only permission and not in roles + continue; + } + filled += 1; + used.add(vote.voter_id); + if (filled >= slot.count) break; + } + if (filled < slot.count) return false; + } + return true; +} + +/** + * Count how many approve votes fill each slot (role-based; permission slots need prefilter). + */ +export function countQuorumProgress( + quorum: QuorumSlot[], + approveVotes: FundOperationVoteRow[] +): { required: number; approved: number; slots: Array<{ slot: QuorumSlot; filled: number; needed: number }> } { + const used = new Set(); + const slots = quorum.map((slot) => { + let filled = 0; + for (const vote of approveVotes) { + if (used.has(vote.voter_id)) continue; + const matchesRole = slot.role ? vote.voter_roles.includes(slot.role) : false; + const matchesPerm = + slot.permission && !slot.role + ? vote.voter_roles.includes(`perm:${slot.permission}`) || + vote.voter_roles.includes(slot.permission) + : false; + if (!matchesRole && !matchesPerm) continue; + filled += 1; + used.add(vote.voter_id); + if (filled >= slot.count) break; + } + return { slot, filled, needed: slot.count }; + }); + const required = slots.reduce((s, x) => s + x.needed, 0); + const approved = slots.reduce((s, x) => s + Math.min(x.filled, x.needed), 0); + return { required, approved, slots }; +} + +export function isQuorumComplete( + quorum: QuorumSlot[], + approveVotes: FundOperationVoteRow[] +): boolean { + const progress = countQuorumProgress(quorum, approveVotes); + return progress.slots.every((s) => s.filled >= s.needed); +} + +/** Whether voter can contribute to any unfilled quorum slot. */ +export function voterFillsOpenSlot( + quorum: QuorumSlot[], + approveVotes: FundOperationVoteRow[], + voterRoles: string[], + voterPermissions: string[] +): boolean { + const progress = countQuorumProgress(quorum, approveVotes); + for (const { slot, filled, needed } of progress.slots) { + if (filled >= needed) continue; + if (slot.role && voterRoles.includes(slot.role)) return true; + if (slot.permission && voterPermissions.includes(slot.permission)) return true; + if (slot.permission && voterPermissions.includes(`admin.${slot.permission}`)) return true; + } + return false; +} + +export function annotateVoterRolesForQuorum( + roles: string[], + permissions: string[], + quorum: QuorumSlot[] +): string[] { + const out = [...roles]; + for (const slot of quorum) { + if (slot.permission && permissions.includes(slot.permission)) { + out.push(`perm:${slot.permission}`); + } + } + return [...new Set(out)]; +} diff --git a/backend/src/services/fundApprovalService.ts b/backend/src/services/fundApprovalService.ts index d73e27b0..215878c1 100644 --- a/backend/src/services/fundApprovalService.ts +++ b/backend/src/services/fundApprovalService.ts @@ -1,5 +1,5 @@ /** - * Super-admin approval workflow for sensitive platform fund operations. + * Approval workflow for sensitive platform fund operations (N-of-M + auto-execute). */ import * as fundOperationRequestRepository from '../repositories/fundOperationRequestRepository'; @@ -8,8 +8,10 @@ import type { FundOperationStatus, FundOperationType, } from '../repositories/fundOperationRequestRepository'; +import * as fundOperationVoteRepository from '../repositories/fundOperationVoteRepository'; +import * as approvalPolicyRepository from '../repositories/approvalPolicyRepository'; +import type { PolicyDecision, PolicyInput, QuorumSlot } from '../repositories/approvalPolicyRepository'; import * as roleRepository from '../repositories/roleRepository'; -import * as userRepository from '../repositories/userRepository'; import { bumpUserTokenOnRoleChange } from './rbacService'; import * as auditLogRepository from '../repositories/auditLogRepository'; import * as securityNotificationService from './securityNotificationService'; @@ -17,7 +19,8 @@ import * as adminCreditService from './adminCreditService'; import * as treasuryService from './treasuryService'; import * as bonusPoolRepository from '../repositories/bonusPoolRepository'; import * as sweepService from './sweepService'; -import * as depositSweepBatchRepository from '../repositories/depositSweepBatchRepository'; +import * as approvalPolicyEngine from './approvalPolicyEngine'; +import type { WalletKind } from '../repositories/approvalPolicyRepository'; import type { RoleName } from '../models'; export class FundApprovalError extends Error { @@ -27,6 +30,14 @@ export class FundApprovalError extends Error { } } +export type FundRequestVoteDto = { + voterId: string; + decision: 'approve' | 'reject'; + reason: string | null; + voterRoles: string[]; + createdAt: string; +}; + export type FundRequestDto = { id: string; operationType: FundOperationType; @@ -39,9 +50,57 @@ export type FundRequestDto = { createdAt: string; approvedAt: string | null; executedAt: string | null; + policyId: string | null; + policyName: string | null; + requiredQuorum: QuorumSlot[]; + forbidSelfApprove: boolean; + amountRaw: string | null; + assetCode: string | null; + network: string | null; + fromAddress: string | null; + toAddress: string | null; + votes: FundRequestVoteDto[]; + quorumProgress: { required: number; approved: number }; + canVote: boolean; }; -function toDto(row: FundOperationRequestRow): FundRequestDto { +async function toDto( + row: FundOperationRequestRow, + viewerId?: string | null +): Promise { + const votes = await fundOperationVoteRepository.listByRequest(row.id); + const decision = (row.policy_snapshot as PolicyDecision | null) ?? { + mode: 'require_approvals' as const, + quorum: (row.required_quorum as QuorumSlot[]) ?? [{ role: 'super_admin', count: 1 }], + forbid_self_approve: true, + }; + const quorum = Array.isArray(decision.quorum) ? decision.quorum : []; + const approveVotes = votes.filter((v) => v.decision === 'approve'); + const progress = approvalPolicyEngine.countQuorumProgress(quorum, approveVotes); + + let policyName: string | null = null; + if (row.policy_id) { + const p = await approvalPolicyRepository.findById(row.policy_id); + policyName = p?.name ?? null; + } + + let canVote = false; + if (viewerId && row.status === 'pending_approval') { + const existing = votes.find((v) => v.voter_id === viewerId); + if (!existing) { + if (decision.forbid_self_approve && viewerId === row.requested_by) { + canVote = false; + } else { + const roles = await roleRepository.getUserRoleNames(viewerId); + const perms = await roleRepository.getUserPermissions(viewerId); + const hasApprovePerm = perms.includes('fund_operation.approve'); + canVote = + hasApprovePerm && + approvalPolicyEngine.voterFillsOpenSlot(quorum, approveVotes, roles, perms); + } + } + } + return { id: row.id, operationType: row.operation_type, @@ -54,49 +113,63 @@ function toDto(row: FundOperationRequestRow): FundRequestDto { createdAt: row.created_at.toISOString(), approvedAt: row.approved_at?.toISOString() ?? null, executedAt: row.executed_at?.toISOString() ?? null, + policyId: row.policy_id, + policyName, + requiredQuorum: quorum, + forbidSelfApprove: decision.forbid_self_approve !== false, + amountRaw: row.amount_raw, + assetCode: row.asset_code, + network: row.network, + fromAddress: row.from_address, + toAddress: row.to_address, + votes: votes.map((v) => ({ + voterId: v.voter_id, + decision: v.decision, + reason: v.reason, + voterRoles: v.voter_roles, + createdAt: v.created_at.toISOString(), + })), + quorumProgress: { required: progress.required, approved: progress.approved }, + canVote, }; } -export async function createFundRequest(input: { - operationType: FundOperationType; - payload: Record; - requestedBy: string; -}): Promise { - const canRequest = await roleRepository.userHasPermission( - input.requestedBy, - 'fund_operation.request' - ); - if (!canRequest) throw new FundApprovalError('Permission denied: fund_operation.request'); +function extractContext(operationType: FundOperationType, payload: Record) { + const amountRaw = + (payload.amountRaw as string | undefined) ?? + (payload.amount as string | undefined) ?? + null; + const walletTypeId = + typeof payload.walletTypeId === 'number' + ? payload.walletTypeId + : payload.walletTypeId != null + ? Number(payload.walletTypeId) + : null; + const network = (payload.network as string | undefined) ?? null; + const assetCode = (payload.assetCode as string | undefined) ?? (payload.walletCode as string | undefined) ?? null; + const fromAddress = (payload.fromAddress as string | undefined) ?? null; + const toAddress = (payload.toAddress as string | undefined) ?? null; - let row; - try { - row = await fundOperationRequestRepository.createRequest({ - operationType: input.operationType, - payload: input.payload, - requestedBy: input.requestedBy, - }); - } catch (e) { - const msg = e instanceof Error ? e.message : ''; - if (/operation_type_check|violates check constraint/i.test(msg)) { - throw new FundApprovalError( - 'Database schema is missing this operation type. Run db migrations and restart the backend.' - ); - } - throw e; + let sourceKind: WalletKind = 'any'; + let destKind: WalletKind = 'any'; + if (operationType === 'treasury_hot_to_cold' || operationType === 'treasury_hot_to_cold_gas') { + sourceKind = 'hot'; + destKind = 'cold'; + } else if (operationType === 'treasury_cold_to_hot' || operationType === 'treasury_cold_to_hot_gas') { + sourceKind = 'cold'; + destKind = 'hot'; + } else if (operationType === 'sweep_batch' || operationType === 'sweep_manual') { + sourceKind = 'hd'; + destKind = 'cold'; + } else if (operationType === 'user_withdrawal') { + sourceKind = 'hot'; + destKind = 'user'; } - await auditLogRepository.create({ - userId: input.requestedBy, - action: 'fund_operation_requested', - resourceType: 'fund_operation_request', - resourceId: row.id, - metadata: { operation_type: input.operationType }, - }); - - return toDto(row); + return { amountRaw, walletTypeId, network, assetCode, fromAddress, toAddress, sourceKind, destKind }; } -async function executeApprovedRequest( +export async function executeApprovedRequest( request: FundOperationRequestRow, approverId: string ): Promise> { @@ -111,7 +184,7 @@ async function executeApprovedRequest( amountRaw: string; reason: string; }; - const result = await adminCreditService.grantLedgerCredit({ + return adminCreditService.grantLedgerCredit({ userId, walletTypeId, adjustmentType, @@ -120,7 +193,6 @@ async function executeApprovedRequest( approvedBy, requestedBy: request.requested_by, }); - return result; } case 'treasury_cold_to_hot': { const { walletTypeId, amountRaw, notes } = request.payload as { @@ -128,13 +200,12 @@ async function executeApprovedRequest( amountRaw: string; notes?: string; }; - const result = await treasuryService.requestColdToHotFunding(request.requested_by, { + return treasuryService.requestColdToHotFunding(request.requested_by, { walletTypeId, amountRaw: BigInt(amountRaw), notes, approvedBy, }); - return result; } case 'bonus_pool_fund': { const { walletTypeId, amountRaw } = request.payload as { @@ -147,7 +218,6 @@ async function executeApprovedRequest( return { message: 'Pool funded', pools }; } case 'sweep_manual': { - // 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 }); @@ -172,6 +242,20 @@ async function executeApprovedRequest( approvedBy, }); } + case 'treasury_hot_to_cold': { + const { walletTypeId, amountRaw, notes } = request.payload as { + walletTypeId: number; + amountRaw: string; + notes?: string; + }; + return treasuryService.executeHotToColdUsdt({ + walletTypeId, + amountRaw: BigInt(amountRaw), + notes, + requestedBy: request.requested_by, + approvedBy, + }); + } case 'treasury_cold_to_hot_gas': { const { walletTypeId, amountRaw, notes } = request.payload as { walletTypeId: number; @@ -185,16 +269,198 @@ async function executeApprovedRequest( approvedBy, }); } + case 'user_withdrawal': { + const { broadcastApprovedWithdrawal } = await import('./withdrawalService'); + const { transactionId } = request.payload as { transactionId: string }; + return broadcastApprovedWithdrawal(transactionId, approvedBy); + } + case 'approval_policy_change': { + return applyPolicyChangeFromRequest(request, approvedBy); + } default: - throw new FundApprovalError(`Unknown operation type: ${request.operation_type}`); + throw new FundApprovalError(`Unknown operation type: ${(request as FundOperationRequestRow).operation_type}`); } } -export async function approveFundRequest( +async function applyPolicyChangeFromRequest( + request: FundOperationRequestRow, + actorId: string +): Promise> { + const { after, note } = request.payload as { + after: PolicyInput[]; + note?: string; + }; + if (!Array.isArray(after) || !after.length) { + throw new FundApprovalError('approval_policy_change payload.after must be a non-empty array'); + } + const before = await approvalPolicyRepository.listAllPolicies(); + const applied = await approvalPolicyRepository.replaceAllPolicies(after, actorId); + await approvalPolicyRepository.insertRevision({ + changeRequestId: request.id, + actorId, + beforeSnapshot: before, + afterSnapshot: applied, + note: note ?? null, + }); + await auditLogRepository.create({ + userId: actorId, + action: 'approval_policies_applied', + resourceType: 'approval_policy', + resourceId: request.id, + metadata: { + beforeCount: before.length, + afterCount: applied.length, + note: note ?? null, + }, + }); + return { applied: applied.length }; +} + +export async function createFundRequest(input: { + operationType: FundOperationType; + payload: Record; + requestedBy: string; + /** Skip fund_operation.request check (e.g. user withdrawal). */ + skipRequestPermission?: boolean; + /** Force queue even if policy says auto (unused reserved). */ + forceQueue?: boolean; +}): Promise { + if (!input.skipRequestPermission) { + const canRequest = await roleRepository.userHasPermission( + input.requestedBy, + 'fund_operation.request' + ); + if (!canRequest) throw new FundApprovalError('Permission denied: fund_operation.request'); + } + + const ctx = extractContext(input.operationType, input.payload); + const evaluated = await approvalPolicyEngine.evaluate({ + operationType: input.operationType, + amountRaw: ctx.amountRaw, + walletTypeId: ctx.walletTypeId, + network: ctx.network, + sourceKind: ctx.sourceKind, + destKind: ctx.destKind, + }); + + const decision = evaluated.decision; + const meta = { + policyId: evaluated.policy?.id ?? null, + policySnapshot: decision as unknown as Record, + requiredQuorum: decision.quorum, + amountRaw: ctx.amountRaw, + assetCode: ctx.assetCode, + network: ctx.network, + fromAddress: ctx.fromAddress, + toAddress: ctx.toAddress, + }; + + // Auto-execute path (never for policy changes) + if ( + !input.forceQueue && + decision.mode === 'auto_execute' && + input.operationType !== 'approval_policy_change' + ) { + let row: FundOperationRequestRow; + try { + row = await fundOperationRequestRepository.createRequest({ + operationType: input.operationType, + payload: input.payload, + requestedBy: input.requestedBy, + meta, + }); + } catch (e) { + const msg = e instanceof Error ? e.message : ''; + if (/operation_type_check|violates check constraint/i.test(msg)) { + throw new FundApprovalError( + 'Database schema is missing this operation type. Run db migrations and restart the backend.' + ); + } + throw e; + } + + await fundOperationRequestRepository.markApproved(row.id, input.requestedBy); + await fundOperationRequestRepository.markProcessing(row.id); + try { + const fresh = await fundOperationRequestRepository.findById(row.id); + const executionResult = await executeApprovedRequest(fresh!, input.requestedBy); + await fundOperationRequestRepository.markConfirmed(row.id, executionResult); + await auditLogRepository.create({ + userId: input.requestedBy, + action: 'fund_operation_auto_executed', + resourceType: 'fund_operation_request', + resourceId: row.id, + metadata: { + operation_type: input.operationType, + policy_id: evaluated.policy?.id ?? null, + amount_raw: ctx.amountRaw, + network: ctx.network, + from_address: ctx.fromAddress, + to_address: ctx.toAddress, + execution_result: executionResult, + }, + }); + const final = await fundOperationRequestRepository.findById(row.id); + return { ...(await toDto(final!)), autoExecuted: true }; + } catch (e) { + const msg = e instanceof Error ? e.message : 'Execution failed'; + await fundOperationRequestRepository.markFailed(row.id, msg); + await auditLogRepository.create({ + userId: input.requestedBy, + action: 'fund_operation_failed', + resourceType: 'fund_operation_request', + resourceId: row.id, + metadata: { error: msg, auto: true }, + }); + throw new FundApprovalError(msg); + } + } + + let row: FundOperationRequestRow; + try { + row = await fundOperationRequestRepository.createRequest({ + operationType: input.operationType, + payload: input.payload, + requestedBy: input.requestedBy, + meta, + }); + } catch (e) { + const msg = e instanceof Error ? e.message : ''; + if (/operation_type_check|violates check constraint/i.test(msg)) { + throw new FundApprovalError( + 'Database schema is missing this operation type. Run db migrations and restart the backend.' + ); + } + throw e; + } + + await auditLogRepository.create({ + userId: input.requestedBy, + action: 'fund_operation_requested', + resourceType: 'fund_operation_request', + resourceId: row.id, + metadata: { + operation_type: input.operationType, + policy_id: evaluated.policy?.id ?? null, + amount_raw: ctx.amountRaw, + asset_code: ctx.assetCode, + network: ctx.network, + from_address: ctx.fromAddress, + to_address: ctx.toAddress, + quorum: decision.quorum, + }, + }); + + return toDto(row, input.requestedBy); +} + +export async function castVote( requestId: string, - approverId: string + voterId: string, + decision: 'approve' | 'reject', + reason?: string ): Promise { - const canApprove = await roleRepository.userHasPermission(approverId, 'fund_operation.approve'); + const canApprove = await roleRepository.userHasPermission(voterId, 'fund_operation.approve'); if (!canApprove) throw new FundApprovalError('Permission denied: fund_operation.approve'); const existing = await fundOperationRequestRepository.findById(requestId); @@ -203,26 +469,137 @@ export async function approveFundRequest( throw new FundApprovalError(`Request is not pending (status: ${existing.status})`); } - const approved = await fundOperationRequestRepository.markApproved(requestId, approverId); - if (!approved) throw new FundApprovalError('Failed to approve request'); + const policyDecision = (existing.policy_snapshot as PolicyDecision | null) ?? { + mode: 'require_approvals' as const, + quorum: (existing.required_quorum as QuorumSlot[]) ?? [{ role: 'super_admin', count: 1 }], + forbid_self_approve: true, + }; + const quorum = policyDecision.quorum ?? []; + + if (policyDecision.forbid_self_approve !== false && voterId === existing.requested_by) { + throw new FundApprovalError('Self-approval is not allowed for this operation'); + } + + const prior = await fundOperationVoteRepository.findByRequestAndVoter(requestId, voterId); + if (prior) throw new FundApprovalError('You have already voted on this request'); + + const roles = await roleRepository.getUserRoleNames(voterId); + const perms = await roleRepository.getUserPermissions(voterId); + const annotated = approvalPolicyEngine.annotateVoterRolesForQuorum(roles, perms, quorum); + + if (decision === 'approve') { + const approveVotes = (await fundOperationVoteRepository.listByRequest(requestId)).filter( + (v) => v.decision === 'approve' + ); + if (!approvalPolicyEngine.voterFillsOpenSlot(quorum, approveVotes, roles, perms)) { + throw new FundApprovalError('Your role does not fill an open approval slot for this policy'); + } + } + + if (decision === 'reject') { + const trimmed = reason?.trim(); + if (!trimmed) throw new FundApprovalError('Rejection reason is required'); + await fundOperationVoteRepository.insertVote({ + requestId, + voterId, + decision: 'reject', + reason: trimmed, + voterRoles: annotated, + }); + const rejected = await fundOperationRequestRepository.markRejected(requestId, voterId, trimmed); + if (!rejected) throw new FundApprovalError('Failed to reject request'); + if (existing.operation_type === 'user_withdrawal') { + const { transactionId } = existing.payload as { transactionId?: string }; + if (transactionId) { + const { abandonPendingWithdrawal } = await import('./withdrawalService'); + await abandonPendingWithdrawal(transactionId, trimmed); + } + } + await auditLogRepository.create({ + userId: voterId, + action: 'fund_operation_rejected', + resourceType: 'fund_operation_request', + resourceId: requestId, + metadata: { + reason: trimmed, + operation_type: existing.operation_type, + amount_raw: existing.amount_raw, + network: existing.network, + from_address: existing.from_address, + to_address: existing.to_address, + }, + }); + return toDto(rejected, voterId); + } + + await fundOperationVoteRepository.insertVote({ + requestId, + voterId, + decision: 'approve', + reason: reason?.trim() || null, + voterRoles: annotated, + }); + await fundOperationRequestRepository.touchApprovedBy(requestId, voterId); + + const allVotes = await fundOperationVoteRepository.listByRequest(requestId); + const approveVotes = allVotes.filter((v) => v.decision === 'approve'); + const complete = approvalPolicyEngine.isQuorumComplete(quorum, approveVotes); + + await auditLogRepository.create({ + userId: voterId, + action: 'fund_operation_vote_approved', + resourceType: 'fund_operation_request', + resourceId: requestId, + metadata: { + operation_type: existing.operation_type, + quorum_complete: complete, + progress: approvalPolicyEngine.countQuorumProgress(quorum, approveVotes), + }, + }); + + if (!complete) { + const pending = await fundOperationRequestRepository.findById(requestId); + return toDto(pending!, voterId); + } + + const approved = await fundOperationRequestRepository.markApproved(requestId, voterId); + if (!approved) { + // Race: already approved + const current = await fundOperationRequestRepository.findById(requestId); + return toDto(current!, voterId); + } + + await fundOperationRequestRepository.markProcessing(requestId); try { - const executionResult = await executeApprovedRequest(approved, approverId); - await fundOperationRequestRepository.markExecuted(requestId, executionResult); + const fresh = await fundOperationRequestRepository.findById(requestId); + const executionResult = await executeApprovedRequest(fresh!, voterId); + await fundOperationRequestRepository.markConfirmed(requestId, executionResult); await auditLogRepository.create({ - userId: approverId, + userId: voterId, action: 'fund_operation_approved', resourceType: 'fund_operation_request', resourceId: requestId, - metadata: { operation_type: approved.operation_type, execution_result: executionResult }, + metadata: { + operation_type: approved.operation_type, + execution_result: executionResult, + amount_raw: approved.amount_raw, + network: approved.network, + from_address: approved.from_address, + to_address: approved.to_address, + tx_hash: + (executionResult as { txHash?: string; blockchainTxId?: string }).txHash ?? + (executionResult as { blockchainTxId?: string }).blockchainTxId ?? + null, + }, }); const final = await fundOperationRequestRepository.findById(requestId); - return toDto(final!); + return toDto(final!, voterId); } catch (e) { const msg = e instanceof Error ? e.message : 'Execution failed'; await fundOperationRequestRepository.markFailed(requestId, msg); await auditLogRepository.create({ - userId: approverId, + userId: voterId, action: 'fund_operation_failed', resourceType: 'fund_operation_request', resourceId: requestId, @@ -232,29 +609,19 @@ export async function approveFundRequest( } } +export async function approveFundRequest( + requestId: string, + approverId: string +): Promise { + return castVote(requestId, approverId, 'approve'); +} + export async function rejectFundRequest( requestId: string, approverId: string, reason: string ): Promise { - const canApprove = await roleRepository.userHasPermission(approverId, 'fund_operation.approve'); - if (!canApprove) throw new FundApprovalError('Permission denied: fund_operation.approve'); - - const trimmed = reason?.trim(); - if (!trimmed) throw new FundApprovalError('Rejection reason is required'); - - const rejected = await fundOperationRequestRepository.markRejected(requestId, approverId, trimmed); - if (!rejected) throw new FundApprovalError('Request not found or not pending'); - - await auditLogRepository.create({ - userId: approverId, - action: 'fund_operation_rejected', - resourceType: 'fund_operation_request', - resourceId: requestId, - metadata: { reason: trimmed }, - }); - - return toDto(rejected); + return castVote(requestId, approverId, 'reject', reason); } export async function cancelFundRequest( @@ -275,22 +642,99 @@ export async function cancelFundRequest( const cancelled = await fundOperationRequestRepository.markCancelled(requestId); if (!cancelled) throw new FundApprovalError('Failed to cancel request'); - return toDto(cancelled); + + if (existing.operation_type === 'user_withdrawal') { + const { transactionId } = existing.payload as { transactionId?: string }; + if (transactionId) { + const { abandonPendingWithdrawal } = await import('./withdrawalService'); + await abandonPendingWithdrawal(transactionId, 'cancelled'); + } + } + + await auditLogRepository.create({ + userId: actorId, + action: 'fund_operation_cancelled', + resourceType: 'fund_operation_request', + resourceId: requestId, + metadata: { operation_type: existing.operation_type }, + }); + + return toDto(cancelled, actorId); } -export async function getFundRequest(requestId: string): Promise { +export async function getFundRequest( + requestId: string, + viewerId?: string +): Promise { const row = await fundOperationRequestRepository.findById(requestId); - return row ? toDto(row) : null; + return row ? toDto(row, viewerId) : null; } -export async function listFundRequests(filters: { - status?: FundOperationStatus; - operationType?: FundOperationType; - limit?: number; - offset?: number; -}): Promise<{ items: FundRequestDto[]; total: number }> { +export async function listFundRequests( + filters: { + status?: FundOperationStatus; + operationType?: FundOperationType; + limit?: number; + offset?: number; + }, + viewerId?: string +): Promise<{ items: FundRequestDto[]; total: number }> { const result = await fundOperationRequestRepository.listRequests(filters); - return { items: result.items.map(toDto), total: result.total }; + const items = await Promise.all(result.items.map((r) => toDto(r, viewerId))); + return { items, total: result.total }; +} + +/** Submit a full policy set replacement via Approvals (does not apply immediately). */ +export async function draftPolicyChange(input: { + after: PolicyInput[]; + note?: string; + requestedBy: string; +}): Promise { + const canManage = await roleRepository.userHasPermission( + input.requestedBy, + 'approval_policy.manage' + ); + const canManageGranular = await roleRepository.userHasPermission( + input.requestedBy, + 'admin.approval_policies.manage' + ); + if (!canManage && !canManageGranular) { + throw new FundApprovalError('Permission denied: approval_policy.manage'); + } + if (!Array.isArray(input.after) || !input.after.length) { + throw new FundApprovalError('after must be a non-empty policies array'); + } + const before = await approvalPolicyRepository.listAllPolicies(); + return createFundRequest({ + operationType: 'approval_policy_change', + payload: { + before, + after: input.after, + note: input.note, + }, + requestedBy: input.requestedBy, + }); +} + +export async function listApprovalPolicies(actorId: string) { + const canView = + (await roleRepository.userHasPermission(actorId, 'approval_policy.view')) || + (await roleRepository.userHasPermission(actorId, 'admin.approval_policies.view')) || + (await roleRepository.userHasPermission(actorId, 'approval_policy.manage')) || + (await roleRepository.userHasPermission(actorId, 'admin.approval_policies.manage')) || + (await roleRepository.userHasRole(actorId, 'super_admin')); + if (!canView) throw new FundApprovalError('Permission denied: approval_policy.view'); + await approvalPolicyRepository.ensureDefaultPoliciesSeeded(); + return approvalPolicyRepository.listAllPolicies(); +} + +export async function listPolicyRevisions(actorId: string, limit?: number) { + const canView = + (await roleRepository.userHasPermission(actorId, 'approval_policy.view')) || + (await roleRepository.userHasPermission(actorId, 'admin.approval_policies.view')) || + (await roleRepository.userHasRole(actorId, 'super_admin')); + if (!canView) throw new FundApprovalError('Permission denied: approval_policy.view'); + return approvalPolicyRepository.listRevisions(limit); } export type UserRoleName = RoleName; diff --git a/backend/src/services/treasuryService.ts b/backend/src/services/treasuryService.ts index 8186a9f2..5527d152 100644 --- a/backend/src/services/treasuryService.ts +++ b/backend/src/services/treasuryService.ts @@ -334,6 +334,151 @@ export async function executeHotToColdGas(input: { }; } +function hotUsdtMinReserveRaw(): bigint { + try { + return BigInt(config.treasury.hotUsdtMinReserveRaw || '0'); + } catch { + return 0n; + } +} + +/** Preview USDT (or network token) Hot → Cold: balances, gas, maxSendable after reserve. */ +export async function previewHotToColdUsdt(walletTypeId: number) { + const wt = await walletRepository.getWalletTypeById(walletTypeId); + if (!wt) throw new Error('Unknown wallet type'); + const cold = await coldWalletRepository.getActiveColdWallet(walletTypeId); + const hot = await hotWalletRepository.getActiveHotWallet(walletTypeId); + if (!cold) throw new Error('No active cold wallet for this network'); + if (!hot) throw new Error('No active hot wallet for this network'); + assertValidNativeRecipient(wt.network, cold.address); + + let hotUsdt = 0n; + let hotNative = 0n; + let coldUsdt = 0n; + let nativeSymbol = 'BNB'; + let nativeDecimals = 18; + let minNative = MIN_BNB_WEI_FOR_WITHDRAWAL; + let txBuffer = BSC_NATIVE_TX_BUFFER_WEI; + let tokenContract = ''; + + if (wt.network === 'BSC' || wt.code === USDT_BEP20_CODE) { + tokenContract = bscService.resolveUsdtContract(wt.contract_address); + hotUsdt = await bscService.getUsdtBalanceRaw(hot.address, tokenContract); + coldUsdt = await bscService.getUsdtBalanceRaw(cold.address, tokenContract); + hotNative = await bscService.getNativeBalanceWei(hot.address); + } else if (wt.network === 'TRON' || wt.code === USDT_TRC20_CODE) { + tokenContract = + config.blockchain.tron.usdtTrc20Contract || wt.contract_address || ''; + if (!tokenContract) throw new Error('USDT TRC20 contract not configured'); + hotUsdt = await tronService.getTrc20BalanceRaw(hot.address, tokenContract); + coldUsdt = await tronService.getTrc20BalanceRaw(cold.address, tokenContract); + hotNative = await tronService.getTrxBalanceSun(hot.address); + nativeSymbol = 'TRX'; + nativeDecimals = 6; + minNative = MIN_TRX_SUN_FOR_WITHDRAWAL; + txBuffer = TRON_NATIVE_TX_BUFFER_SUN; + } else { + throw new Error('Hot→Cold USDT is only supported for BEP20 and TRC20'); + } + + const minUsdtReserve = hotUsdtMinReserveRaw(); + const maxSendable = hotUsdt > minUsdtReserve ? hotUsdt - minUsdtReserve : 0n; + const gasOk = hotNative >= minNative + txBuffer; + + return { + walletTypeId, + network: wt.network, + walletCode: wt.code, + tokenSymbol: 'USDT', + tokenDecimals: wt.decimals, + tokenContract, + fromHot: hot.address, + toCold: cold.address, + hotUsdt: hotUsdt.toString(), + coldUsdt: coldUsdt.toString(), + hotNative: hotNative.toString(), + nativeSymbol, + nativeDecimals, + minNativeForWithdraw: minNative.toString(), + txFeeBuffer: txBuffer.toString(), + minUsdtReserve: minUsdtReserve.toString(), + maxSendable: maxSendable.toString(), + gasOk, + gasHint: gasOk + ? null + : `Hot wallet needs ≥ ${(minNative + txBuffer).toString()} ${nativeSymbol} (withdraw reserve + fee buffer) to broadcast`, + }; +} + +/** Platform-signed USDT Hot → Cold after Super Admin approval. */ +export async function executeHotToColdUsdt(input: { + walletTypeId: number; + amountRaw: bigint; + notes?: string; + requestedBy: string; + approvedBy: string; +}) { + if (input.amountRaw <= 0n) throw new Error('Invalid USDT amount'); + const preview = await previewHotToColdUsdt(input.walletTypeId); + if (!preview.gasOk) { + throw new Error(preview.gasHint || 'Hot wallet has insufficient native gas'); + } + if (input.amountRaw > BigInt(preview.maxSendable)) { + throw new Error( + `Amount exceeds max sendable after USDT reserve. Max: ${preview.maxSendable}` + ); + } + + const hot = await hotWalletRepository.getActiveHotWallet(input.walletTypeId); + if (!hot) throw new Error('No active hot wallet'); + const privateKey = decryptPrivateKey(hot.encrypted_private_key); + + const row = await exchangeFundingRepository.createFunding({ + walletTypeId: input.walletTypeId, + direction: 'hot_to_cold', + amount: input.amountRaw, + fromAddress: preview.fromHot, + toAddress: preview.toCold, + notes: input.notes, + requestedBy: input.requestedBy, + approvedBy: input.approvedBy, + }); + + let txId: string; + try { + if (preview.network === 'BSC' || preview.walletCode === USDT_BEP20_CODE) { + txId = await bscService.sendUsdt( + privateKey, + preview.tokenContract, + preview.toCold, + input.amountRaw + ); + } else { + txId = await tronService.sendTrc20( + privateKey, + preview.tokenContract, + preview.toCold, + input.amountRaw + ); + } + } catch (e) { + await exchangeFundingRepository.cancelFunding(row.id); + throw e; + } + + await exchangeFundingRepository.completeFundingBroadcast(row.id, txId, input.approvedBy); + return { + fundingId: row.id, + blockchainTxId: txId, + from: preview.fromHot, + to: preview.toCold, + amount: input.amountRaw.toString(), + symbol: 'USDT', + network: preview.network, + message: 'Sent USDT from hot to cold', + }; +} + export async function requestColdToHotGasFunding( requestedBy: string, input: { diff --git a/backend/src/services/withdrawalService.ts b/backend/src/services/withdrawalService.ts index 1225dd80..fe17cbf1 100644 --- a/backend/src/services/withdrawalService.ts +++ b/backend/src/services/withdrawalService.ts @@ -115,6 +115,8 @@ export type WithdrawalResult = { amount: string; fee: string; totalDebited: string; + fundRequestId?: string; + blockchainTxId?: string | null; }; /** @@ -237,12 +239,140 @@ export async function requestWithdrawal( }, }); + const amountUsd = rawAmountToUsdApprox(USDT_TRC20_CODE, amountRaw, LEDGER_USDT_DECIMALS); + if (amountUsd >= settings.large_withdrawal_threshold_usd) { + await transactionRepository.updateStatus(tx.id, 'pending_approval'); + const { createFundRequest } = await import('./fundApprovalService'); + const fundReq = await createFundRequest({ + operationType: 'user_withdrawal', + payload: { + transactionId: tx.id, + userId, + amountRaw: amountRaw.toString(), + feeRaw: feeRaw.toString(), + walletTypeId: railWalletType.id, + walletCode: walletTypeCode, + assetCode: walletTypeCode, + network, + fromAddress: hotWallet.address, + toAddress, + }, + requestedBy: userId, + skipRequestPermission: true, + }); + return { + transactionId: tx.id, + status: fundReq.autoExecuted ? 'completed' : 'pending_approval', + amount: amountRaw.toString(), + fee: feeRaw.toString(), + totalDebited: totalDebit.toString(), + fundRequestId: fundReq.id, + }; + } + + return broadcastWithdrawalTx({ + txId: tx.id, + userId, + accountId: account.id, + totalDebit, + amountRaw, + feeRaw, + toAddress, + network, + walletTypeCode, + railWalletType, + hotWallet, + ledgerWalletTypeId: ledgerWalletType.id, + }); +} + +/** Resume on-chain broadcast after Approvals quorum for a large withdrawal. */ +export async function broadcastApprovedWithdrawal( + transactionId: string, + approvedBy: string +): Promise> { + const tx = await transactionRepository.findById(transactionId); + if (!tx) throw new Error('Withdrawal transaction not found'); + if (tx.status !== 'pending_approval' && tx.status !== 'pending') { + throw new Error(`Withdrawal is not awaiting approval (status: ${tx.status})`); + } + + const meta = (tx.metadata ?? {}) as Record; + const walletTypeCode = String(meta.rail_wallet_type || ''); + const network = String(meta.network || '') as 'TRON' | 'BSC' | 'POLYGON'; + const railWalletType = await walletRepository.getWalletTypeByCode(walletTypeCode); + if (!railWalletType) throw new Error('Unknown withdrawal rail'); + const hotWallet = await hotWalletRepository.getActiveHotWallet(railWalletType.id); + if (!hotWallet) throw new Error('Withdrawal temporarily unavailable'); + + const ledgerWalletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE); + if (!ledgerWalletType) throw new Error('USDT ledger wallet type not configured'); + const account = await ledgerRepository.getOrCreateAccount(tx.user_id, ledgerWalletType.id); + const amountRaw = BigInt(tx.amount); + const feeRaw = BigInt(tx.fee || '0'); + const totalDebit = amountRaw + feeRaw; + + const result = await broadcastWithdrawalTx({ + txId: tx.id, + userId: tx.user_id, + accountId: account.id, + totalDebit, + amountRaw, + feeRaw, + toAddress: tx.to_address || '', + network: network === 'BSC' || network === 'POLYGON' ? network : 'TRON', + walletTypeCode, + railWalletType, + hotWallet, + ledgerWalletTypeId: ledgerWalletType.id, + }); + + await auditLogRepository.create({ + userId: approvedBy, + action: 'withdrawal_approval_broadcast', + resourceType: 'transaction', + resourceId: tx.id, + metadata: { approvedBy, blockchainTxId: result.blockchainTxId ?? null }, + }); + + return result; +} + +async function broadcastWithdrawalTx(input: { + txId: string; + userId: string; + accountId: string; + totalDebit: bigint; + amountRaw: bigint; + feeRaw: bigint; + toAddress: string; + network: string; + walletTypeCode: string; + railWalletType: WalletType; + hotWallet: { address: string; encrypted_private_key: string }; + ledgerWalletTypeId: number; +}): Promise { + const { + txId, + userId, + accountId, + totalDebit, + amountRaw, + feeRaw, + toAddress, + network, + walletTypeCode, + railWalletType, + hotWallet, + ledgerWalletTypeId, + } = input; + let blockchainTxId: string | null = null; try { const privateKey = decryptPrivateKey(hotWallet.encrypted_private_key); - await transactionRepository.updateStatus(tx.id, 'broadcasting'); + await transactionRepository.updateStatus(txId, 'broadcasting'); if (railWalletType.network === 'TRON') { const trc20Contract = @@ -259,24 +389,24 @@ export async function requestWithdrawal( throw new Error('Unsupported network'); } - await transactionRepository.updateStatus(tx.id, 'confirming', 0, blockchainTxId); + await transactionRepository.updateStatus(txId, 'confirming', 0, blockchainTxId); try { - await ledgerRepository.finalizeWithdrawalFromLocked(account.id, totalDebit, tx.id); - await withdrawalLockRepository.deleteByTransactionId(tx.id); - await transactionRepository.updateStatus(tx.id, 'completed', 1); + await ledgerRepository.finalizeWithdrawalFromLocked(accountId, totalDebit, txId); + await withdrawalLockRepository.deleteByTransactionId(txId); + await transactionRepository.updateStatus(txId, 'completed', 1); } catch (ledgerErr) { - await transactionRepository.updateStatus(tx.id, 'ledger_finalize_failed', 1, blockchainTxId); + await transactionRepository.updateStatus(txId, 'ledger_finalize_failed', 1, blockchainTxId); await raiseAlert({ userId, severity: 'critical', alertType: 'withdrawal_ledger_finalize_failed', title: 'Withdrawal broadcast succeeded but ledger finalization failed', details: - `transaction=${tx.id}, blockchain_tx=${blockchainTxId}, amount=${amountRaw.toString()}, fee=${feeRaw.toString()}. ` + + `transaction=${txId}, blockchain_tx=${blockchainTxId}, amount=${amountRaw.toString()}, fee=${feeRaw.toString()}. ` + `Funds remain locked; manual reconciliation required.`, metadata: { - transactionId: tx.id, + transactionId: txId, blockchainTxId, amount: amountRaw.toString(), fee: feeRaw.toString(), @@ -290,7 +420,7 @@ export async function requestWithdrawal( userId, action: 'withdrawal_completed', resourceType: 'transaction', - resourceId: tx.id, + resourceId: txId, metadata: { amount: amountRaw.toString(), fee: feeRaw.toString(), @@ -305,31 +435,32 @@ export async function requestWithdrawal( try { await referralService.processWithdrawalReferralCommissions({ userId, - withdrawalTransactionId: tx.id, + withdrawalTransactionId: txId, withdrawalAmount: amountRaw, - walletTypeId: ledgerWalletType.id, + walletTypeId: ledgerWalletTypeId, }); } catch (referralErr) { console.error('[referral] Withdrawal commission processing failed:', referralErr); } return { - transactionId: tx.id, + transactionId: txId, status: 'completed', amount: amountRaw.toString(), fee: feeRaw.toString(), totalDebited: totalDebit.toString(), + blockchainTxId, }; } catch (err) { if (!blockchainTxId) { - await ledgerRepository.unlockBalance(account.id, totalDebit); - await withdrawalLockRepository.deleteByTransactionId(tx.id); - await transactionRepository.updateStatus(tx.id, 'failed'); + await ledgerRepository.unlockBalance(accountId, totalDebit); + await withdrawalLockRepository.deleteByTransactionId(txId); + await transactionRepository.updateStatus(txId, 'failed'); await auditLogRepository.create({ userId, action: 'withdrawal_failed', resourceType: 'transaction', - resourceId: tx.id, + resourceId: txId, metadata: { error: String(err) }, }); queueUserAdminStatsRefresh(userId); @@ -339,4 +470,28 @@ export async function requestWithdrawal( } } -export { SecurityBlockedError }; +/** Unlock ledger and fail tx when a large-withdrawal approval is rejected/cancelled. */ +export async function abandonPendingWithdrawal(transactionId: string, reason: string): Promise { + const tx = await transactionRepository.findById(transactionId); + if (!tx) return; + if (tx.status !== 'pending_approval' && tx.status !== 'pending') return; + + const ledgerWalletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE); + if (!ledgerWalletType) return; + const account = await ledgerRepository.getOrCreateAccount(tx.user_id, ledgerWalletType.id); + const amountRaw = BigInt(tx.amount); + const feeRaw = BigInt(tx.fee || '0'); + const totalDebit = amountRaw + feeRaw; + + await ledgerRepository.unlockBalance(account.id, totalDebit); + await withdrawalLockRepository.deleteByTransactionId(tx.id); + await transactionRepository.updateStatus(tx.id, 'failed'); + await auditLogRepository.create({ + userId: tx.user_id, + action: 'withdrawal_approval_abandoned', + resourceType: 'transaction', + resourceId: tx.id, + metadata: { reason }, + }); + queueUserAdminStatsRefresh(tx.user_id); +} diff --git a/backend/src/validation/adminSchemas.ts b/backend/src/validation/adminSchemas.ts index 045cebe7..2e205853 100644 --- a/backend/src/validation/adminSchemas.ts +++ b/backend/src/validation/adminSchemas.ts @@ -94,15 +94,50 @@ export const fundRequestCreateBodySchema = z.object({ operationType: z.enum([ 'ledger_credit', 'treasury_cold_to_hot', + 'treasury_hot_to_cold', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas', + 'user_withdrawal', + 'approval_policy_change', ]), payload: z.record(z.string(), z.unknown()), }); +const quorumSlotSchema = z.object({ + role: z.string().trim().min(1).max(64).optional(), + permission: z.string().trim().min(1).max(128).optional(), + count: z.number().int().min(1).max(20), +}); + +const policyDecisionSchema = z.object({ + mode: z.enum(['auto_execute', 'require_approvals']), + quorum: z.array(quorumSlotSchema).max(20), + forbid_self_approve: z.boolean().optional(), + require_distinct_users: z.boolean().optional(), +}); + +export const approvalPolicyItemSchema = z.object({ + name: z.string().trim().min(1).max(128), + enabled: z.boolean().optional(), + priority: z.number().int().min(0).max(1_000_000).optional(), + operationType: z.string().trim().max(64).nullable().optional(), + walletTypeId: z.number().int().positive().nullable().optional(), + network: z.string().trim().max(32).nullable().optional(), + amountMinRaw: z.string().trim().max(78).nullable().optional(), + amountMaxRaw: z.string().trim().max(78).nullable().optional(), + sourceWalletKind: z.enum(['hot', 'cold', 'hd', 'user', 'any']).optional(), + destWalletKind: z.enum(['hot', 'cold', 'hd', 'user', 'any']).optional(), + decision: policyDecisionSchema, +}); + +export const approvalPolicyDraftBodySchema = z.object({ + after: z.array(approvalPolicyItemSchema).min(1).max(200), + note: z.string().trim().max(2000).optional(), +}); + export const fundRequestRejectBodySchema = z.object({ reason: z.string().trim().min(1).max(2000), }); diff --git a/docker-compose.yml b/docker-compose.yml index e1831bc5..c5e626b8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -66,6 +66,8 @@ x-backend-common: &backend-common 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} + # Optional USDT floor left on hot after Hot→Cold (raw chain units; 0 = no fixed USDT reserve) + HOT_USDT_MIN_RESERVE_RAW: ${HOT_USDT_MIN_RESERVE_RAW:-0} 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 4fef2dc9..220dbe1a 100644 --- a/docs/DEPLOY-VPS.md +++ b/docs/DEPLOY-VPS.md @@ -84,6 +84,8 @@ nano .env # ou vim | `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) | +| `HOT_USDT_MIN_RESERVE_RAW` | Optionnel — plancher USDT laissé sur le hot après Hot→Cold (raw ; `0` = pas de réserve fixe) | +| Approbations (DB) | Règles N-sur-M dans **Options → Règles d’approbation** (pas d’env). Seed défaut = 1 Super Admin + anti auto-approbation. `SWEEP_AUTO_*` reste un fallback / kill-switch pour les sweeps. | | `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 | @@ -496,11 +498,35 @@ Le transfert on-chain est **manuel** (clé cold hors plateforme) ; Prediqo enreg > **Important :** le cold doit être une adresse **externe** (MetaMask / hardware), **pas** une adresse Receive d’un user Prediqo (HD). Sinon vous ne pourrez pas signer le Cold → Hot. -1. Treasury → **Cold → Hot funding** : réseau **USDT (BEP20)**, montant en **USDT** (ex. `2`) → **Request funding** → Approvals. +1. Treasury → **Hot ↔ Cold USDT** : route **Cold → Hot**, réseau **USDT (BEP20)**, montant en **USDT** (ex. `2`) → **Request funding** → Approvals. 2. Après approbation : transferrer manuellement USDT BEP20 **cold → hot** (adresse hot affichée / Copier). 3. Treasury → **Confirm tx** avec le hash BscScan. 4. Vérifier le solde USDT hot on-chain (Treasury / explorateur). +#### B2. Hot → Cold USDT (excédent hot → cold) + +Après Approvals, la **plateforme** signe depuis le hot (pas MetaMask). Destination = cold **actif** en base uniquement. + +1. Treasury → **Hot ↔ Cold USDT** : route **Hot → Cold**, réseau, montant (ou **Max**) → **Request hot → cold**. +2. Approvals → Super Admin approuve `treasury_hot_to_cold` → broadcast on-chain automatique. +3. Contrôles : solde USDT hot, gas natif ≥ min retrait, plancher optionnel `HOT_USDT_MIN_RESERVE_RAW` (défaut `0` = pas de réserve USDT fixe ; max envoyable = solde − réserve). + +```bash +# Exemple .env / docker-compose (défaut) +HOT_USDT_MIN_RESERVE_RAW=0 +# Ex. BEP20 : garder ~10 USDT sur le hot → 10000000000000000000 +``` + +Différence vs gas Hot→Cold : ici c’est de l’**USDT** ; le gas Hot→Cold reste la carte « Gas transfer » (BNB / TRX). + +### Règles d’approbation (N-sur-M) + +Après migration DB, les tables `approval_policies` / `fund_operation_votes` sont créées et seedées (1× Super Admin, `forbid_self_approve`). + +- **UI** : Options → **Règles d’approbation** (`/admin/approval-policies`). Les changements passent par Approvals (`approval_policy_change`) — pas de save silencieux. +- **Retraits** : au-dessus de `large_withdrawal_threshold_usd` (Settings) → file Approvals `user_withdrawal` ; en dessous → broadcast immédiat (comportement historique). +- **Sweeps** : `SWEEP_AUTO_EXECUTE` / `SWEEP_AUTO_MAX_AMOUNT_RAW` continuent de fonctionner. Vous pouvez aussi ajouter une policy DB `sweep_batch` en `auto_execute` avec `amount_max_raw` ; la policy DB s’applique aux demandes créées via `createFundRequest`. + ##### Récupérer des USDT bloqués sur une « fausse » cold (adresse HD user) Si une adresse Receive Prediqo a été enregistrée comme cold par erreur : diff --git a/prediqo_mobile/android/build/reports/problems/problems-report.html b/prediqo_mobile/android/build/reports/problems/problems-report.html index d3f963a9..06960060 100644 --- a/prediqo_mobile/android/build/reports/problems/problems-report.html +++ b/prediqo_mobile/android/build/reports/problems/problems-report.html @@ -650,7 +650,7 @@ code + .copy-button { diff --git a/prediqo_web/src/app/router/router.tsx b/prediqo_web/src/app/router/router.tsx index ef7a1af2..9c4b9da6 100644 --- a/prediqo_web/src/app/router/router.tsx +++ b/prediqo_web/src/app/router/router.tsx @@ -22,6 +22,7 @@ import { HomePage } from '../../features/home/HomePage'; import { CatalogAdminPage } from '../../features/catalog/CatalogAdminPage'; import { TreasuryAdminPage } from '../../features/treasury/TreasuryAdminPage'; import { ApprovalsPage } from '../../features/approvals/ApprovalsPage'; +import { ApprovalPoliciesPage } from '../../features/approvals/ApprovalPoliciesPage'; import { ReferralAdminPage } from '../../features/referral/ReferralAdminPage'; import { ReferralPage } from '../../features/referral/ReferralPage'; import { ReferralFraudDashboardPage } from '../../features/referral/ReferralFraudDashboardPage'; @@ -109,6 +110,7 @@ export const router = createBrowserRouter([ { path: 'admin/catalog', element: }, { path: 'admin/treasury', element: }, { path: 'admin/approvals', element: }, + { path: 'admin/approval-policies', element: }, { path: 'admin/security', element: }, { path: 'admin/referral', element: }, { path: 'admin/referral/fraud', element: }, diff --git a/prediqo_web/src/features/approvals/ApprovalPoliciesPage.tsx b/prediqo_web/src/features/approvals/ApprovalPoliciesPage.tsx new file mode 100644 index 00000000..9535b981 --- /dev/null +++ b/prediqo_web/src/features/approvals/ApprovalPoliciesPage.tsx @@ -0,0 +1,525 @@ +/** + * Admin UI for configurable approval policies (N-of-M). + * Changes are submitted to Approvals — never applied silently. + */ +import { + Alert, + Box, + Button, + Card, + CardContent, + Chip, + FormControl, + FormControlLabel, + InputLabel, + MenuItem, + Select, + Stack, + Switch, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + TextField, + Typography, +} from '@mui/material'; +import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; +import { useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { api } from '../../shared/services/api'; +import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; +import { useAuth } from '../../shared/auth/AuthContext'; +import { hasPermission } from '../../shared/auth/permissions'; +import { ScrollableTable } from '../../shared/components/ScrollableTable'; +import { apiErrorMessage } from '../../shared/utils/apiError'; + +type QuorumSlot = { role?: string; permission?: string; count: number }; +type PolicyDecision = { + mode: 'auto_execute' | 'require_approvals'; + quorum: QuorumSlot[]; + forbid_self_approve: boolean; + require_distinct_users?: boolean; +}; + +type Policy = { + id?: string; + name: string; + enabled: boolean; + priority: number; + operation_type: string | null; + wallet_type_id: number | null; + network: string | null; + amount_min_raw: string | null; + amount_max_raw: string | null; + source_wallet_kind: string; + dest_wallet_kind: string; + decision: PolicyDecision; +}; + +type PolicyDraft = { + name: string; + enabled: boolean; + priority: number; + operationType: string | null; + walletTypeId: number | null; + network: string | null; + amountMinRaw: string | null; + amountMaxRaw: string | null; + sourceWalletKind: string; + destWalletKind: string; + decision: PolicyDecision; +}; + +const OP_TYPES = [ + '', + 'ledger_credit', + 'treasury_cold_to_hot', + 'treasury_hot_to_cold', + 'treasury_hot_to_cold_gas', + 'treasury_cold_to_hot_gas', + 'sweep_batch', + 'sweep_manual', + 'bonus_pool_fund', + 'user_withdrawal', + 'approval_policy_change', +]; + +function toDraft(p: Policy): PolicyDraft { + return { + name: p.name, + enabled: p.enabled, + priority: p.priority, + operationType: p.operation_type, + walletTypeId: p.wallet_type_id, + network: p.network, + amountMinRaw: p.amount_min_raw, + amountMaxRaw: p.amount_max_raw, + sourceWalletKind: p.source_wallet_kind || 'any', + destWalletKind: p.dest_wallet_kind || 'any', + decision: { + mode: p.decision?.mode === 'auto_execute' ? 'auto_execute' : 'require_approvals', + quorum: p.decision?.quorum?.length + ? p.decision.quorum.map((s) => ({ ...s, count: s.count || 1 })) + : [{ role: 'super_admin', count: 1 }], + forbid_self_approve: p.decision?.forbid_self_approve !== false, + require_distinct_users: p.decision?.require_distinct_users !== false, + }, + }; +} + +const emptyPolicy = (): PolicyDraft => ({ + name: 'New policy', + enabled: true, + priority: 100, + operationType: null, + walletTypeId: null, + network: null, + amountMinRaw: null, + amountMaxRaw: null, + sourceWalletKind: 'any', + destWalletKind: 'any', + decision: { + mode: 'require_approvals', + quorum: [{ role: 'super_admin', count: 1 }], + forbid_self_approve: true, + require_distinct_users: true, + }, +}); + +export function ApprovalPoliciesPage() { + const { t } = useTranslation(); + const qc = useQueryClient(); + const { permissions } = useAuth(); + const canView = + hasPermission(permissions, 'approval_policy.view') || + hasPermission(permissions, 'admin.approval_policies.view') || + hasPermission(permissions, 'approval_policy.manage') || + hasPermission(permissions, 'admin.approval_policies.manage'); + const canManage = + hasPermission(permissions, 'approval_policy.manage') || + hasPermission(permissions, 'admin.approval_policies.manage'); + + const [drafts, setDrafts] = useState([]); + const [note, setNote] = useState(''); + const [message, setMessage] = useState(null); + const [error, setError] = useState(null); + + const listQ = useQuery({ + queryKey: ['admin-approval-policies'], + queryFn: async () => { + const res = await api.get<{ items: Policy[] }>('/api/v1/admin/approval-policies'); + return res.data.items; + }, + enabled: canView, + }); + + const revisionsQ = useQuery({ + queryKey: ['admin-approval-policy-revisions'], + queryFn: async () => { + const res = await api.get<{ + items: Array<{ id: string; created_at: string; note: string | null; actor_id: string | null }>; + }>('/api/v1/admin/approval-policies/revisions'); + return res.data.items; + }, + enabled: canView, + }); + + useEffect(() => { + if (listQ.data) setDrafts(listQ.data.map(toDraft)); + }, [listQ.data]); + + const submitMut = useMutation({ + mutationFn: () => + api.post('/api/v1/admin/approval-policies/draft-change', { + after: drafts, + note: note || undefined, + }), + onSuccess: () => { + setMessage(t('admin.approvalPolicies.submitted')); + setError(null); + setNote(''); + void qc.invalidateQueries({ queryKey: ['admin-fund-requests'] }); + }, + onError: (err) => setError(apiErrorMessage(err, t('admin.approvalPolicies.submitFailed'))), + }); + + if (!canView) { + return {t('admin.approvalPolicies.noPermission')}; + } + + return ( + + } + title={t('admin.approvalPolicies.title')} + subtitle={t('admin.approvalPolicies.subtitle')} + actions={ + void listQ.refetch()} + /> + } + /> + + {message && ( + setMessage(null)} sx={{ mb: 2 }}> + {message} + + )} + {error && ( + setError(null)} sx={{ mb: 2 }}> + {error} + + )} + + + {t('admin.approvalPolicies.submitHint')} + + + + {drafts.map((p, idx) => ( + + + + + { + const next = [...drafts]; + next[idx] = { ...p, name: e.target.value }; + setDrafts(next); + }} + sx={{ minWidth: 220, flex: 1 }} + /> + { + const next = [...drafts]; + next[idx] = { ...p, priority: Number(e.target.value) || 0 }; + setDrafts(next); + }} + sx={{ width: 120 }} + /> + + {t('admin.approvalPolicies.operationType')} + + + + {t('admin.approvalPolicies.mode')} + + + { + const next = [...drafts]; + next[idx] = { ...p, enabled: e.target.checked }; + setDrafts(next); + }} + /> + } + label={t('admin.approvalPolicies.enabled')} + /> + + + + { + const next = [...drafts]; + next[idx] = { ...p, amountMinRaw: e.target.value || null }; + setDrafts(next); + }} + sx={{ width: 180 }} + /> + { + const next = [...drafts]; + next[idx] = { ...p, amountMaxRaw: e.target.value || null }; + setDrafts(next); + }} + sx={{ width: 180 }} + /> + { + const next = [...drafts]; + next[idx] = { ...p, network: e.target.value || null }; + setDrafts(next); + }} + placeholder="BSC / TRON" + sx={{ width: 140 }} + /> + { + const next = [...drafts]; + next[idx] = { + ...p, + decision: { ...p.decision, forbid_self_approve: e.target.checked }, + }; + setDrafts(next); + }} + /> + } + label={t('admin.approvalPolicies.forbidSelf')} + /> + + + + {t('admin.approvalPolicies.quorumHint')} + + + {p.decision.quorum.map((slot, sIdx) => ( + + { + const next = [...drafts]; + const quorum = [...p.decision.quorum]; + quorum[sIdx] = { ...slot, role: e.target.value || undefined }; + next[idx] = { ...p, decision: { ...p.decision, quorum } }; + setDrafts(next); + }} + sx={{ width: 140 }} + /> + { + const next = [...drafts]; + const quorum = [...p.decision.quorum]; + quorum[sIdx] = { ...slot, count: Math.max(1, Number(e.target.value) || 1) }; + next[idx] = { ...p, decision: { ...p.decision, quorum } }; + setDrafts(next); + }} + sx={{ width: 90 }} + /> + {canManage && ( + + )} + + ))} + {canManage && ( + + )} + + + {canManage && ( + + )} + + + + ))} + + + {canManage && ( + + + setNote(e.target.value)} + sx={{ minWidth: 260, flex: 1 }} + /> + + + )} + + + {t('admin.approvalPolicies.history')} + + + + + + {t('admin.approvalPolicies.when')} + {t('admin.approvalPolicies.actor')} + {t('admin.approvalPolicies.note')} + + + + {(revisionsQ.data ?? []).length === 0 ? ( + + + + {t('admin.approvalPolicies.noHistory')} + + + + ) : ( + (revisionsQ.data ?? []).map((r) => ( + + {new Date(r.created_at).toLocaleString()} + + {r.actor_id ? `${r.actor_id.slice(0, 8)}…` : '—'} + + + {r.note || '—'} + + + )) + )} + +
+
+
+ ); +} diff --git a/prediqo_web/src/features/approvals/ApprovalsPage.tsx b/prediqo_web/src/features/approvals/ApprovalsPage.tsx index 9f31501b..af269201 100644 --- a/prediqo_web/src/features/approvals/ApprovalsPage.tsx +++ b/prediqo_web/src/features/approvals/ApprovalsPage.tsx @@ -1,5 +1,5 @@ /** - * Super-admin inbox for pending fund operation approvals. + * Super-admin inbox for pending fund operation approvals (N-of-M). */ import { Alert, @@ -27,6 +27,7 @@ import { api } from '../../shared/services/api'; import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader'; import { useAuth } from '../../shared/auth/AuthContext'; import { ScrollableTable } from '../../shared/components/ScrollableTable'; +import { apiErrorMessage } from '../../shared/utils/apiError'; type FundRequest = { id: string; @@ -37,18 +38,40 @@ type FundRequest = { approvedBy: string | null; rejectionReason: string | null; createdAt: string; + policyName: string | null; + amountRaw: string | null; + assetCode: string | null; + network: string | null; + fromAddress: string | null; + toAddress: string | null; + quorumProgress: { required: number; approved: number }; + canVote: boolean; + forbidSelfApprove: boolean; + votes: Array<{ voterId: string; decision: string; createdAt: string }>; }; const OP_TYPE_KEYS = [ 'ledger_credit', 'treasury_cold_to_hot', + 'treasury_hot_to_cold', 'bonus_pool_fund', 'sweep_manual', 'sweep_batch', 'treasury_hot_to_cold_gas', 'treasury_cold_to_hot_gas', + 'user_withdrawal', + 'approval_policy_change', ] as const; +function shortId(id: string) { + return id.length > 10 ? `${id.slice(0, 8)}…` : id; +} + +function shortAddr(a: string | null) { + if (!a) return '—'; + return a.length > 14 ? `${a.slice(0, 8)}…${a.slice(-4)}` : a; +} + export function ApprovalsPage() { const { t } = useTranslation(); const qc = useQueryClient(); @@ -56,6 +79,7 @@ export function ApprovalsPage() { const [rejectId, setRejectId] = useState(null); const [rejectReason, setRejectReason] = useState(''); const [message, setMessage] = useState(null); + const [error, setError] = useState(null); const listQ = useQuery({ queryKey: ['admin-fund-requests'], @@ -72,8 +96,10 @@ export function ApprovalsPage() { mutationFn: (id: string) => api.post(`/api/v1/admin/fund-requests/${id}/approve`), onSuccess: () => { setMessage(t('admin.approvals.approved')); + setError(null); void qc.invalidateQueries({ queryKey: ['admin-fund-requests'] }); }, + onError: (err) => setError(apiErrorMessage(err, t('admin.approvals.approveFailed'))), }); const rejectMut = useMutation({ @@ -83,8 +109,10 @@ export function ApprovalsPage() { setRejectId(null); setRejectReason(''); setMessage(t('admin.approvals.rejected')); + setError(null); void qc.invalidateQueries({ queryKey: ['admin-fund-requests'] }); }, + onError: (err) => setError(apiErrorMessage(err, t('admin.approvals.rejectFailed'))), }); const opLabel = (operationType: string) => { @@ -116,6 +144,11 @@ export function ApprovalsPage() { {message} )} + {error && ( + setError(null)} sx={{ mb: 2 }}> + {error} + + )} {listQ.isError && ( @@ -123,11 +156,13 @@ export function ApprovalsPage() { )} - + {t('admin.approvals.type')} + {t('admin.approvals.details')} + {t('admin.approvals.quorum')} {t('admin.approvals.requestedBy')} {t('admin.approvals.created')} {t('common.status')} @@ -137,7 +172,7 @@ export function ApprovalsPage() { {items.length === 0 ? ( - + {t('admin.approvals.noPending')} @@ -146,9 +181,40 @@ export function ApprovalsPage() { ) : ( items.map((r) => ( - {opLabel(r.operationType)} + + + + {opLabel(r.operationType)} + + {r.policyName && ( + + {r.policyName} + + )} + + + + + {(r.amountRaw || r.assetCode) && ( + + {r.amountRaw ?? '—'} {r.assetCode ?? ''} + {r.network ? ` · ${r.network}` : ''} + + )} + + {shortAddr(r.fromAddress)} → {shortAddr(r.toAddress)} + + + + + 0 ? 'info' : 'default'} + /> + - {r.requestedBy.slice(0, 8)}… + {shortId(r.requestedBy)} {new Date(r.createdAt).toLocaleString()} @@ -159,12 +225,17 @@ export function ApprovalsPage() { - diff --git a/prediqo_web/src/features/options/OptionsPage.tsx b/prediqo_web/src/features/options/OptionsPage.tsx index ee23b170..7189b707 100644 --- a/prediqo_web/src/features/options/OptionsPage.tsx +++ b/prediqo_web/src/features/options/OptionsPage.tsx @@ -20,6 +20,7 @@ import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded'; import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded'; import AdminPanelSettingsRoundedIcon from '@mui/icons-material/AdminPanelSettingsRounded'; import ManageAccountsRoundedIcon from '@mui/icons-material/ManageAccountsRounded'; +import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { useAuth } from '../../shared/auth/AuthContext'; @@ -30,6 +31,7 @@ type OptionCardKey = | 'settings' | 'catalog' | 'treasury' + | 'approvalPolicies' | 'referral' | 'referralFraud' | 'testWallet' @@ -90,6 +92,15 @@ const OPTION_CARDS: OptionCardConfig[] = [ bg: 'rgba(41,182,246,0.16)', border: 'rgba(41,182,246,0.22)', }, + { + key: 'approvalPolicies', + path: '/admin/approval-policies', + icon: RuleFolderRoundedIcon, + badgeKey: 'nOfM', + badgeColor: 'warning', + bg: 'rgba(255,152,0,0.14)', + border: 'rgba(255,152,0,0.28)', + }, { key: 'referral', path: '/admin/referral', diff --git a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx index de95e403..48bd3f4f 100644 --- a/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx +++ b/prediqo_web/src/features/treasury/TreasuryAdminPage.tsx @@ -1,5 +1,5 @@ /** - * Admin treasury: cold wallets, sweeps, cold → hot funding. + * Admin treasury: cold wallets, sweeps, Hot ↔ Cold USDT funding, gas transfers. * Admins work in human USDT; raw chain units are derived for the API. */ import { @@ -135,6 +135,27 @@ type GasPreview = { maxSendable: string; }; +type HotToColdUsdtPreview = { + walletTypeId: number; + network: string; + walletCode: string; + tokenSymbol: string; + tokenDecimals: number; + fromHot: string; + toCold: string; + hotUsdt: string; + coldUsdt: string; + hotNative: string; + nativeSymbol: string; + nativeDecimals: number; + minNativeForWithdraw: string; + txFeeBuffer: string; + minUsdtReserve: string; + maxSendable: string; + gasOk: boolean; + gasHint: string | null; +}; + /** Precise human → raw (avoids float errors on 18-decimal BEP20). */ function humanAmountToRaw(human: string, decimals: number): string { const cleaned = human.replace(/,/g, '').replace(/\s/g, '').trim(); @@ -270,6 +291,7 @@ export function TreasuryAdminPage() { const [coldForms, setColdForms] = useState>({}); const [fundingForm, setFundingForm] = useState({ walletTypeId: 0, + direction: 'cold_to_hot' as 'cold_to_hot' | 'hot_to_cold', amountUsdt: '', notes: '', }); @@ -398,6 +420,20 @@ export function TreasuryAdminPage() { }); const gasPreview = gasPreviewQ.data; + const hotToColdUsdtPreviewQ = useQuery({ + queryKey: ['admin-treasury-hot-to-cold-usdt-preview', fundingForm.walletTypeId], + queryFn: async () => { + const res = await api.get( + '/api/v1/admin/treasury/funding/hot-to-cold/preview', + { params: { walletTypeId: fundingForm.walletTypeId } } + ); + return res.data; + }, + enabled: fundingForm.walletTypeId > 0 && fundingForm.direction === 'hot_to_cold', + retry: false, + }); + const hotToColdUsdtPreview = hotToColdUsdtPreviewQ.data; + const setColdMut = useMutation({ mutationFn: (body: { walletTypeId: number; address: string; label?: string }) => api.post('/api/v1/admin/treasury/cold-wallets', body), @@ -416,14 +452,39 @@ export function TreasuryAdminPage() { }); const requestFundingMut = useMutation({ - mutationFn: (body: { walletTypeId: number; amount: string; notes?: string }) => - api.post<{ message?: string }>('/api/v1/admin/treasury/funding', body), - onSuccess: (res) => { - setPendingMsg(res.data.message ?? t('admin.treasury.fundingPending')); + mutationFn: (body: { + walletTypeId: number; + amount: string; + notes?: string; + direction: 'cold_to_hot' | 'hot_to_cold'; + }) => + body.direction === 'hot_to_cold' + ? api.post<{ message?: string }>('/api/v1/admin/treasury/funding/hot-to-cold', { + walletTypeId: body.walletTypeId, + amount: body.amount, + notes: body.notes, + }) + : api.post<{ message?: string }>('/api/v1/admin/treasury/funding', { + walletTypeId: body.walletTypeId, + amount: body.amount, + notes: body.notes, + }), + onSuccess: (res, vars) => { + setPendingMsg( + res.data.message ?? + (vars.direction === 'hot_to_cold' + ? t('admin.treasury.hotToColdPending') + : t('admin.treasury.fundingPending')) + ); void qc.invalidateQueries({ queryKey: ['admin-treasury-overview'] }); + void qc.invalidateQueries({ queryKey: ['admin-treasury-hot-to-cold-usdt-preview'] }); + void qc.invalidateQueries({ queryKey: ['admin-fund-requests'] }); setFundingForm((f) => ({ ...f, amountUsdt: '', notes: '' })); setFundingError(null); }, + onError: (err) => { + setFundingError(apiErrorMessage(err, t('admin.treasury.fundingRequestFailed'))); + }, }); const requestGasMut = useMutation({ @@ -478,10 +539,30 @@ export function TreasuryAdminPage() { setFundingError(t('admin.treasury.invalidAmount')); return; } + if (fundingForm.direction === 'hot_to_cold') { + if (!hotToColdUsdtPreview) { + setFundingError(t('admin.treasury.hotToColdPreviewError')); + return; + } + if (!hotToColdUsdtPreview.gasOk) { + setFundingError(hotToColdUsdtPreview.gasHint ?? t('admin.treasury.hotToColdGasInsufficient')); + return; + } + try { + if (BigInt(raw) > BigInt(hotToColdUsdtPreview.maxSendable)) { + setFundingError(t('admin.treasury.hotToColdExceedsMax')); + return; + } + } catch { + setFundingError(t('admin.treasury.invalidAmount')); + return; + } + } void requestFundingMut.mutateAsync({ walletTypeId: fundingForm.walletTypeId, amount: raw, notes: fundingForm.notes || undefined, + direction: fundingForm.direction, }); }; @@ -955,7 +1036,7 @@ export function TreasuryAdminPage() { - {/* Cold → Hot */} + {/* Hot ↔ Cold USDT */} @@ -964,13 +1045,15 @@ export function TreasuryAdminPage() { {t('admin.treasury.fundingTitle')} - + {t('admin.treasury.fundingSubtitle')} - {t('admin.treasury.fundingSteps')} + {fundingForm.direction === 'hot_to_cold' + ? t('admin.treasury.fundingStepsHotToCold') + : t('admin.treasury.fundingSteps')} + + {t('admin.treasury.fundingDirection')} + + USDT, }} helperText={ - fundingRawPreview !== '0' - ? t('admin.treasury.amountRawPreview', { - raw: fundingRawPreview, - decimals: fundingDecimals, + fundingForm.direction === 'hot_to_cold' && hotToColdUsdtPreview + ? t('admin.treasury.hotToColdMaxSendable', { + amount: rawToHuman( + hotToColdUsdtPreview.maxSendable, + hotToColdUsdtPreview.tokenDecimals + ), }) - : t('admin.treasury.amountUsdtHint') + : fundingRawPreview !== '0' + ? t('admin.treasury.amountRawPreview', { + raw: fundingRawPreview, + decimals: fundingDecimals, + }) + : t('admin.treasury.amountUsdtHint') } sx={{ width: { xs: '100%', sm: 160 }, flex: '0 0 auto' }} /> + {fundingForm.direction === 'hot_to_cold' && + hotToColdUsdtPreview && + BigInt(hotToColdUsdtPreview.maxSendable) > 0n && ( + + )} @@ -1044,6 +1178,27 @@ export function TreasuryAdminPage() { sx={{ maxWidth: 360, width: '100%' }} /> + {fundingForm.direction === 'hot_to_cold' && hotToColdUsdtPreview && ( + + {hotToColdUsdtPreview.gasHint ?? + t('admin.treasury.hotToColdPreviewHint', { + hot: rawToHuman(hotToColdUsdtPreview.hotUsdt, hotToColdUsdtPreview.tokenDecimals), + cold: rawToHuman(hotToColdUsdtPreview.coldUsdt, hotToColdUsdtPreview.tokenDecimals), + reserve: rawToHuman( + hotToColdUsdtPreview.minUsdtReserve, + hotToColdUsdtPreview.tokenDecimals + ), + native: rawToHuman( + hotToColdUsdtPreview.hotNative, + hotToColdUsdtPreview.nativeDecimals + ), + symbol: hotToColdUsdtPreview.nativeSymbol, + })} + + )} + {fundingForm.direction === 'hot_to_cold' && hotToColdUsdtPreviewQ.isError && ( + {t('admin.treasury.hotToColdPreviewError')} + )} {fundingError && ( setFundingError(null)}> {fundingError} @@ -1054,18 +1209,41 @@ export function TreasuryAdminPage() { {t('admin.treasury.fundingAddresses')} - - + {fundingForm.direction === 'hot_to_cold' ? ( + <> + + + + ) : ( + <> + + + + )} )} @@ -1085,13 +1263,15 @@ export function TreasuryAdminPage() { {overview.pendingColdToHotFunding.map((f) => { const wt = walletById.get(f.walletTypeId); const asset = assets.find((a) => a.walletType.id === f.walletTypeId); - const isGas = (f.direction ?? '').includes('_gas'); + const dir = f.direction ?? 'cold_to_hot'; + const isGas = dir.includes('_gas'); + const isHotToColdUsdt = dir === 'hot_to_cold'; const dec = isGas ? (asset?.nativeDecimals ?? (wt?.network === 'TRON' ? 6 : 18)) : (wt?.decimals ?? 18); const symbol = isGas ? (asset?.nativeSymbol ?? 'BNB') : 'USDT'; const needsConfirm = - !isGas || f.direction === 'cold_to_hot_gas'; + (!isGas && !isHotToColdUsdt) || dir === 'cold_to_hot_gas'; return ( @@ -1102,7 +1282,9 @@ export function TreasuryAdminPage() { label={ isGas ? t('admin.treasury.fundingKindGas') - : t('admin.treasury.fundingKindUsdt') + : isHotToColdUsdt + ? t('admin.treasury.fundingKindHotToCold') + : t('admin.treasury.fundingKindUsdt') } /> diff --git a/prediqo_web/src/shared/auth/permissions.ts b/prediqo_web/src/shared/auth/permissions.ts index f1246650..ec3d8007 100644 --- a/prediqo_web/src/shared/auth/permissions.ts +++ b/prediqo_web/src/shared/auth/permissions.ts @@ -21,6 +21,8 @@ const LEGACY_IMPLIES: Record = { 'user.manage_roles': ['admin.rbac.view', 'admin.rbac.manage'], 'fund_operation.request': ['admin.fund_operations.request'], 'fund_operation.approve': ['admin.fund_operations.approve'], + 'approval_policy.view': ['admin.approval_policies.view'], + 'approval_policy.manage': ['admin.approval_policies.manage'], }; function expand(userPerms: string[]): Set { @@ -58,6 +60,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record = { '/admin/catalog': 'admin.games.view', '/admin/treasury': 'admin.treasury.view', '/admin/approvals': 'admin.fund_operations.approve', + '/admin/approval-policies': 'admin.approval_policies.view', '/admin/security': 'admin.security.view', '/admin/referral': 'admin.referral.view', '/admin/referral/fraud': 'admin.referral_fraud.view', @@ -77,6 +80,7 @@ export const OPTIONS_CARD_PERMISSIONS: Record = { settings: 'admin.settings.view', catalog: 'admin.games.view', treasury: 'admin.treasury.view', + approvalPolicies: 'admin.approval_policies.view', referral: 'admin.referral.view', referralFraud: 'admin.referral_fraud.view', testWallet: 'admin.test_wallet.view', diff --git a/prediqo_web/src/shared/i18n/locales/en.ts b/prediqo_web/src/shared/i18n/locales/en.ts index 83285396..7bd21d83 100644 --- a/prediqo_web/src/shared/i18n/locales/en.ts +++ b/prediqo_web/src/shared/i18n/locales/en.ts @@ -65,6 +65,7 @@ export const en = { faq: 'FAQ', support: 'Support', approvals: 'Approvals', + approvalPolicies: 'Approval policies', overview: 'Overview', reports: 'Reports', options: 'Options', @@ -957,6 +958,7 @@ export const en = { dynamic: 'Dynamic', catalog: 'Catalog', coldHot: 'Cold / Hot', + nOfM: 'N-of-M', levelsBonus: 'Levels / Bonus', sybilReview: 'Sybil / Review / Clawback', playMoney: 'Play money', @@ -986,6 +988,11 @@ export const en = { title: 'Treasury', description: 'Cold wallet addresses, deposit sweeps, and hot wallet funding from cold storage.', }, + approvalPolicies: { + title: 'Approval policies', + description: + 'N-of-M rules, amount thresholds, auto-execute, and self-approval controls for sensitive ops.', + }, referral: { title: 'Referral program', description: 'Multi-level commissions, bonus pool, eligibility rules, and signup analytics.', @@ -1117,14 +1124,18 @@ export const en = { }, approvals: { title: 'Approvals', - subtitle: 'Review and approve sensitive fund operations', + subtitle: 'Review and approve sensitive fund operations (N-of-M when configured)', refresh: 'Refresh approvals', noPermission: 'You do not have permission to approve fund operations.', - approved: 'Request approved and executed.', + approved: 'Vote recorded — executed when quorum is complete.', rejected: 'Request rejected.', + approveFailed: 'Approval failed', + rejectFailed: 'Rejection failed', loadError: 'Failed to load approval queue.', noPending: 'No pending approvals.', type: 'Type', + details: 'Details', + quorum: 'Quorum', requestedBy: 'Requested by', created: 'Created', status: 'Status', @@ -1137,13 +1148,51 @@ export const en = { opTypes: { ledger_credit: 'Ledger credit', treasury_cold_to_hot: 'Cold → Hot funding', + treasury_hot_to_cold: 'Hot → Cold funding', bonus_pool_fund: 'Bonus pool fund', sweep_manual: 'Manual sweeps', sweep_batch: 'Auto sweep batch', treasury_hot_to_cold_gas: 'Hot → Cold gas (BNB / TRX)', treasury_cold_to_hot_gas: 'Cold → Hot gas (BNB / TRX)', + user_withdrawal: 'Large user withdrawal', + approval_policy_change: 'Approval policy change', }, }, + approvalPolicies: { + title: 'Approval policies', + subtitle: + 'Configure who must approve sensitive operations, amount thresholds, auto-execute, and self-approval rules.', + refresh: 'Refresh policies', + noPermission: 'You do not have permission to view approval policies.', + submitHint: + 'Edits are not saved directly. Submit a change to Approvals; another Super Admin must approve before it applies.', + submitted: 'Policy change submitted — pending Approvals', + submitFailed: 'Could not submit policy change', + name: 'Name', + priority: 'Priority', + operationType: 'Operation', + anyOp: 'Any operation', + mode: 'Mode', + modeRequire: 'Require approvals', + modeAuto: 'Auto-execute', + enabled: 'Enabled', + amountMin: 'Min amount (raw)', + amountMax: 'Max amount (raw)', + network: 'Network', + forbidSelf: 'Forbid self-approval', + quorumHint: 'Quorum slots (role × count). First matching policy by priority wins.', + role: 'Role', + count: 'Count', + addSlot: 'Add slot', + removePolicy: 'Remove policy', + addPolicy: 'Add policy', + note: 'Change note', + submitChange: 'Submit change for approval', + history: 'Applied revisions', + when: 'When', + actor: 'Actor', + noHistory: 'No revisions yet.', + }, users: { title: 'Users', subtitle: 'Advanced user table — filter, sort, select multiple users, and run batch actions.', @@ -1574,6 +1623,7 @@ export const en = { gasRequestFailed: 'Gas transfer request failed', fundingKindUsdt: 'USDT', fundingKindGas: 'Gas', + fundingKindHotToCold: 'Hot → Cold', confirmDialogHintGas: 'Paste the blockchain transaction hash after you sent BNB or TRX from cold to hot.', viewOnExplorer: 'Explorer', @@ -1581,10 +1631,15 @@ export const en = { coldAddress: 'Cold wallet address', label: 'Label', saveCold: 'Save cold', - fundingTitle: 'Cold → Hot funding', + fundingTitle: 'Hot ↔ Cold USDT', fundingSubtitle: - 'Request approval, send USDT manually from cold to hot, then confirm with the blockchain transaction ID.', + 'Move USDT between hot and cold. Cold → Hot is manual (MetaMask + Confirm). Hot → Cold is signed by the platform after Approvals.', fundingSteps: '1) Request · 2) Approve · 3) Transfer on-chain · 4) Confirm tx', + fundingStepsHotToCold: + '1) Request · 2) Super Admin approves · 3) Platform sends USDT from hot to cold (no MetaMask)', + fundingDirection: 'Route', + fundingDirColdToHot: 'Cold → Hot (manual)', + fundingDirHotToCold: 'Hot → Cold (platform)', network: 'Network', amountUsdt: 'Amount', amountUsdtHint: 'Enter a human amount, e.g. 0.50', @@ -1595,9 +1650,21 @@ export const en = { fundingAddresses: 'Addresses for the on-chain transfer', copyColdForTransfer: 'From (cold) — source of funds', copyHotDestination: 'To (hot) — paste this on your exchange / wallet', + copyHotSource: 'From (hot) — platform-signed source', + copyColdDestination: 'To (cold) — active cold only', notes: 'Notes', notesOptional: 'Optional', requestFunding: 'Request funding', + requestHotToCold: 'Request hot → cold', + hotToColdMaxSendable: 'Max sendable: {{amount}} USDT (after reserve)', + hotToColdPreviewHint: + 'Hot {{hot}} USDT · Cold {{cold}} USDT · Reserve {{reserve}} USDT · Hot gas {{native}} {{symbol}}', + hotToColdPreviewError: 'Could not load hot → cold balances for this network', + hotToColdGasInsufficient: 'Hot wallet needs more native gas before this transfer', + hotToColdExceedsMax: 'Amount exceeds max sendable after the USDT reserve', + hotToColdPending: + 'Hot → cold request submitted — after approval the platform sends from hot', + fundingRequestFailed: 'Funding request failed', amount: 'Amount', fromTo: 'From → To', confirmTx: 'Confirm tx', diff --git a/prediqo_web/src/shared/i18n/locales/fr.ts b/prediqo_web/src/shared/i18n/locales/fr.ts index 61be9b32..e052423b 100644 --- a/prediqo_web/src/shared/i18n/locales/fr.ts +++ b/prediqo_web/src/shared/i18n/locales/fr.ts @@ -65,6 +65,7 @@ export const fr = { faq: 'FAQ', support: 'Assistance', approvals: 'Approbations', + approvalPolicies: 'Règles d’approbation', overview: 'Vue d’ensemble', reports: 'Rapports', options: 'Options', @@ -971,6 +972,7 @@ export const fr = { dynamic: 'Dynamique', catalog: 'Catalogue', coldHot: 'Froid / Chaud', + nOfM: 'N-sur-M', levelsBonus: 'Niveaux / Bonus', sybilReview: 'Sybil / Revue / Récupération', playMoney: 'Argent fictif', @@ -1000,6 +1002,11 @@ export const fr = { title: 'Trésorerie', description: 'Adresses cold wallet, sweeps de dépôts et alimentation du hot wallet depuis le cold storage.', }, + approvalPolicies: { + title: 'Règles d’approbation', + description: + 'Règles N-sur-M, seuils de montant, auto-exécution et contrôle d’auto-approbation.', + }, referral: { title: 'Programme de parrainage', description: 'Commissions multi-niveaux, pool bonus, règles d’éligibilité et statistiques d’inscription.', @@ -1133,14 +1140,18 @@ export const fr = { }, approvals: { title: 'Approbations', - subtitle: 'Examiner et approuver les opérations de fonds sensibles', + subtitle: 'Examiner et approuver les opérations de fonds sensibles (N-sur-M si configuré)', refresh: 'Actualiser les approbations', noPermission: 'Vous n’avez pas la permission d’approuver les opérations de fonds.', - approved: 'Demande approuvée et exécutée.', + approved: 'Vote enregistré — exécution quand le quorum est atteint.', rejected: 'Demande rejetée.', + approveFailed: 'Échec de l’approbation', + rejectFailed: 'Échec du rejet', loadError: 'Impossible de charger la file d’approbation.', noPending: 'Aucune approbation en attente.', type: 'Type', + details: 'Détails', + quorum: 'Quorum', requestedBy: 'Demandé par', created: 'Créé le', status: 'Statut', @@ -1153,13 +1164,51 @@ export const fr = { opTypes: { ledger_credit: 'Crédit grand livre', treasury_cold_to_hot: 'Alimentation Froid → Chaud', + treasury_hot_to_cold: 'Alimentation Chaud → Froid', bonus_pool_fund: 'Alimentation pool bonus', sweep_manual: 'Sweeps manuels', sweep_batch: 'Lot de sweeps auto', treasury_hot_to_cold_gas: 'Gas Hot → Cold (BNB / TRX)', treasury_cold_to_hot_gas: 'Gas Cold → Hot (BNB / TRX)', + user_withdrawal: 'Retrait utilisateur important', + approval_policy_change: 'Changement de règles d’approbation', }, }, + approvalPolicies: { + title: 'Règles d’approbation', + subtitle: + 'Configurer qui doit approuver, les seuils, l’auto-exécution et l’interdiction d’auto-approbation.', + refresh: 'Actualiser les règles', + noPermission: 'Vous n’avez pas la permission de voir les règles d’approbation.', + submitHint: + 'Les modifications ne sont pas enregistrées directement. Soumettez un changement vers Approvals ; un autre Super Admin doit approuver avant application.', + submitted: 'Changement de règles soumis — en attente d’Approvals', + submitFailed: 'Impossible de soumettre le changement', + name: 'Nom', + priority: 'Priorité', + operationType: 'Opération', + anyOp: 'Toute opération', + mode: 'Mode', + modeRequire: 'Approbations requises', + modeAuto: 'Exécution auto', + enabled: 'Activée', + amountMin: 'Montant min (brut)', + amountMax: 'Montant max (brut)', + network: 'Réseau', + forbidSelf: 'Interdire l’auto-approbation', + quorumHint: 'Slots de quorum (rôle × nombre). La première règle matchée par priorité gagne.', + role: 'Rôle', + count: 'Nombre', + addSlot: 'Ajouter un slot', + removePolicy: 'Supprimer la règle', + addPolicy: 'Ajouter une règle', + note: 'Note du changement', + submitChange: 'Soumettre pour approbation', + history: 'Révisions appliquées', + when: 'Quand', + actor: 'Acteur', + noHistory: 'Aucune révision pour le moment.', + }, users: { title: 'Utilisateurs', subtitle: 'Table avancée — filtrer, trier, sélectionner plusieurs utilisateurs et actions groupées.', @@ -1590,6 +1639,7 @@ export const fr = { gasRequestFailed: 'La demande de transfert de gas a échoué', fundingKindUsdt: 'USDT', fundingKindGas: 'Gas', + fundingKindHotToCold: 'Hot → Cold', confirmDialogHintGas: 'Collez le hash de transaction après avoir envoyé du BNB ou TRX du cold vers le hot.', viewOnExplorer: 'Explorateur', @@ -1597,10 +1647,15 @@ export const fr = { coldAddress: 'Adresse cold wallet', label: 'Libellé', saveCold: 'Enregistrer cold', - fundingTitle: 'Alimentation Cold → Hot', + fundingTitle: 'USDT Hot ↔ Cold', fundingSubtitle: - 'Demandez l’approbation, envoyez l’USDT manuellement du cold vers le hot, puis confirmez avec l’ID de transaction blockchain.', + 'Déplacez l’USDT entre hot et cold. Cold → Hot est manuel (MetaMask + Confirmer). Hot → Cold est signé par la plateforme après Approvals.', fundingSteps: '1) Demande · 2) Approbation · 3) Transfert on-chain · 4) Confirmer la tx', + fundingStepsHotToCold: + '1) Demande · 2) Super Admin approuve · 3) La plateforme envoie l’USDT du hot vers le cold (pas de MetaMask)', + fundingDirection: 'Parcours', + fundingDirColdToHot: 'Cold → Hot (manuel)', + fundingDirHotToCold: 'Hot → Cold (plateforme)', network: 'Réseau', amountUsdt: 'Montant', amountUsdtHint: 'Saisissez un montant lisible, ex. 0.50', @@ -1611,9 +1666,21 @@ export const fr = { fundingAddresses: 'Adresses pour le transfert on-chain', copyColdForTransfer: 'De (cold) — source des fonds', copyHotDestination: 'Vers (hot) — à coller dans l’échangeur / wallet', + copyHotSource: 'De (hot) — source signée par la plateforme', + copyColdDestination: 'Vers (cold) — cold actif uniquement', notes: 'Notes', notesOptional: 'Facultatif', requestFunding: 'Demander le financement', + requestHotToCold: 'Demander hot → cold', + hotToColdMaxSendable: 'Max envoyable : {{amount}} USDT (après réserve)', + hotToColdPreviewHint: + 'Hot {{hot}} USDT · Cold {{cold}} USDT · Réserve {{reserve}} USDT · Gas hot {{native}} {{symbol}}', + hotToColdPreviewError: 'Impossible de charger les soldes hot → cold pour ce réseau', + hotToColdGasInsufficient: 'Le hot wallet a besoin de plus de gas natif avant ce transfert', + hotToColdExceedsMax: 'Le montant dépasse le maximum envoyable après la réserve USDT', + hotToColdPending: + 'Demande hot → cold soumise — après approbation la plateforme envoie depuis le hot', + fundingRequestFailed: 'La demande de financement a échoué', amount: 'Montant', fromTo: 'De → Vers', confirmTx: 'Confirmer tx', diff --git a/prediqo_web/src/shared/layout/AppShell.tsx b/prediqo_web/src/shared/layout/AppShell.tsx index 8ed1318c..63b8220f 100644 --- a/prediqo_web/src/shared/layout/AppShell.tsx +++ b/prediqo_web/src/shared/layout/AppShell.tsx @@ -27,6 +27,7 @@ import AssessmentRoundedIcon from '@mui/icons-material/AssessmentRounded'; import SecurityRoundedIcon from '@mui/icons-material/SecurityRounded'; import HeadsetMicRoundedIcon from '@mui/icons-material/HeadsetMicRounded'; import GavelRoundedIcon from '@mui/icons-material/GavelRounded'; +import RuleFolderRoundedIcon from '@mui/icons-material/RuleFolderRounded'; import { PrediqoLogo } from '../brand/PrediqoLogo'; import HelpOutlineRoundedIcon from '@mui/icons-material/HelpOutlineRounded'; import Badge from '@mui/material/Badge'; @@ -184,9 +185,18 @@ export function AppShell() { ...(canApproveFundOps ? [{ label: t('nav.approvals'), to: '/admin/approvals', icon: }] : []), + ...(can('admin.approval_policies.view') || can('approval_policy.view') + ? [ + { + label: t('nav.approvalPolicies'), + to: '/admin/approval-policies', + icon: , + }, + ] + : []), ...(hasAdminPanel || isAdmin ? adminNavItems : []), ] as const, - [t, isAdmin, hasAdminPanel, isStaff, canApproveFundOps, unreadSupport, adminNavItems] + [t, isAdmin, hasAdminPanel, isStaff, canApproveFundOps, can, unreadSupport, adminNavItems] ); const drawer = (