After adding additionnel configuration for validations1
This commit is contained in:
parent
add1e69f5b
commit
fd5bac3cc8
2
backend/dist/bootstrap/appBootstrap.d.ts.map
vendored
2
backend/dist/bootstrap/appBootstrap.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"appBootstrap.d.ts","sourceRoot":"","sources":["../../src/bootstrap/appBootstrap.ts"],"names":[],"mappings":"AAAA;;GAEG;AA2HH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,2FAA2F;IAC3F,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,kCAAkC;IAClC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF,yDAAyD;AACzD,wBAAsB,aAAa,CAAC,IAAI,GAAE,gBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAiD9E"}
|
||||
{"version":3,"file":"appBootstrap.d.ts","sourceRoot":"","sources":["../../src/bootstrap/appBootstrap.ts"],"names":[],"mappings":"AAAA;;GAEG;AA8IH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,+EAA+E;IAC/E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,2FAA2F;IAC3F,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,kCAAkC;IAClC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEF,yDAAyD;AACzD,wBAAsB,aAAa,CAAC,IAAI,GAAE,gBAAqB,GAAG,OAAO,CAAC,IAAI,CAAC,CAiD9E"}
|
||||
23
backend/dist/bootstrap/appBootstrap.js
vendored
23
backend/dist/bootstrap/appBootstrap.js
vendored
@ -13,6 +13,7 @@ const securityService_1 = require("../services/securityService");
|
||||
const fileIntegrityService_1 = require("../services/fileIntegrityService");
|
||||
const dbTamperService_1 = require("../services/dbTamperService");
|
||||
const sweepBatchService_1 = require("../services/sweepBatchService");
|
||||
const sweepService_1 = require("../services/sweepService");
|
||||
const countryService_1 = require("../services/countryService");
|
||||
const userAdminStatsService_1 = require("../services/userAdminStatsService");
|
||||
const adminUserExportService_1 = require("../services/adminUserExportService");
|
||||
@ -84,19 +85,35 @@ function startDbTamperMonitor() {
|
||||
setTimeout(run, 15000);
|
||||
}
|
||||
function startSweepBatchMonitor() {
|
||||
const auto = config_1.config.treasury.sweepEnabled && config_1.config.treasury.sweepAutoExecute;
|
||||
console.log(`[sweep] monitor start: SWEEP_ENABLED=${config_1.config.treasury.sweepEnabled} ` +
|
||||
`SWEEP_AUTO_EXECUTE=${config_1.config.treasury.sweepAutoExecute} ` +
|
||||
`allowlist=${config_1.config.treasury.sweepColdAllowlist.length} addr(s) ` +
|
||||
`maxRaw=${config_1.config.treasury.sweepAutoMaxAmountRaw || '(none)'}`);
|
||||
const run = async () => {
|
||||
try {
|
||||
if (config_1.config.treasury.sweepEnabled && config_1.config.treasury.sweepAutoExecute) {
|
||||
const nAuto = await (0, sweepService_1.processAutoEligibleSweeps)();
|
||||
if (nAuto > 0) {
|
||||
console.log(`[sweep] auto-executed ${nAuto} sweep(s)`);
|
||||
}
|
||||
}
|
||||
// Creates Approvals only when needed; also cancels orphan batches already auto-swept.
|
||||
const n = await (0, sweepBatchService_1.createSweepBatchApprovalRequests)();
|
||||
if (n > 0 && process.env.NODE_ENV !== 'production') {
|
||||
if (n > 0) {
|
||||
console.log(`[sweep-batch] Enqueued ${n} batch approval request(s)`);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error('Sweep batch job error:', e);
|
||||
}
|
||||
setTimeout(run, sweepBatchService_1.SWEEP_BATCH_INTERVAL_MS);
|
||||
const nextMs = auto
|
||||
? Math.min(sweepBatchService_1.SWEEP_BATCH_INTERVAL_MS, (0, sweepService_1.getSweepPollIntervalMs)())
|
||||
: sweepBatchService_1.SWEEP_BATCH_INTERVAL_MS;
|
||||
setTimeout(run, nextMs);
|
||||
};
|
||||
setTimeout(run, 60000);
|
||||
// First pass quickly so a pending sweep after deploy does not wait a full minute
|
||||
setTimeout(run, auto ? 10000 : 60000);
|
||||
}
|
||||
function startReferralCommissionMonitor() {
|
||||
const intervalMs = (0, referralService_1.getReferralCommissionPollIntervalMs)();
|
||||
|
||||
2
backend/dist/bootstrap/appBootstrap.js.map
vendored
2
backend/dist/bootstrap/appBootstrap.js.map
vendored
File diff suppressed because one or more lines are too long
28
backend/dist/config/index.d.ts
vendored
28
backend/dist/config/index.d.ts
vendored
@ -37,7 +37,8 @@ export declare const config: {
|
||||
rpcUrl: string;
|
||||
/**
|
||||
* Extra RPCs tried for eth_getLogs when the primary returns -32005 / limit exceeded.
|
||||
* Public Binance dataseeds often ban getLogs; 1rpc / 48.club usually still work.
|
||||
* Public Binance dataseeds often ban getLogs; rpc-bsc.48.club is the reliable free fallback.
|
||||
* (1rpc.io often returns 403 from datacenter / VPS IPs — do not list it by default.)
|
||||
*/
|
||||
rpcFallbacks: string[];
|
||||
/** Optional override; otherwise DB wallet_types.contract_address for USDT_BEP20 */
|
||||
@ -52,8 +53,9 @@ export declare const config: {
|
||||
/** Re-scan overlap each poll to survive empty eth_getLogs / late indexing. */
|
||||
depositOverlapLookbackBlocks: number;
|
||||
/**
|
||||
* When HD still holds USDT (missed credit), rescan only this many recent blocks
|
||||
* via getLogs — not the full 7-day window (public RPCs time out).
|
||||
* When HD still holds USDT (missed credit), rescan this many recent blocks via getLogs.
|
||||
* Must be wide enough for deposits missed while public RPCs were rate-limiting
|
||||
* (≈3s/block → 200000 ≈ 7 days). Used as floor with depositInitialLookbackBlocks.
|
||||
*/
|
||||
unpaidLookbackBlocks: number;
|
||||
/** Optional Etherscan V2 / BscScan key for unpaid deposit fallback. */
|
||||
@ -90,11 +92,31 @@ export declare const config: {
|
||||
treasury: {
|
||||
/** Moves on-chain deposits from user addresses to cold storage */
|
||||
sweepEnabled: boolean;
|
||||
/**
|
||||
* When true, pending sweeps execute on-chain without Approvals (after safety checks).
|
||||
* Default false — keep human approval for cold destination / amount review.
|
||||
*/
|
||||
sweepAutoExecute: boolean;
|
||||
/**
|
||||
* Optional raw-unit cap for auto-execute. Above this amount, sweep stays pending
|
||||
* for Submit sweeps → Approvals. Empty = no cap when SWEEP_AUTO_EXECUTE=true.
|
||||
*/
|
||||
sweepAutoMaxAmountRaw: string;
|
||||
/**
|
||||
* Optional comma-separated cold addresses allowed as sweep destinations (EVM lowercased).
|
||||
* When set, active cold must match; blocks sweeps if DB cold was changed to an unknown address.
|
||||
*/
|
||||
sweepColdAllowlist: string[];
|
||||
sweepPollIntervalMs: number;
|
||||
/** Minimum token amount (raw units) to sweep */
|
||||
sweepMinAmountRaw: string;
|
||||
/** TRX sent from hot wallet to fund TRC20 sweeps (sun) */
|
||||
tronGasTopUpSun: string;
|
||||
/**
|
||||
* 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: string;
|
||||
/** MATIC sent from hot wallet to fund USDC sweeps (wei) */
|
||||
polygonGasTopUpWei: string;
|
||||
};
|
||||
|
||||
2
backend/dist/config/index.d.ts.map
vendored
2
backend/dist/config/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmEH,kFAAkF;AAClF,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;YAoBb,kIAAkI;;;;;;;YAOlI,iFAAiF;;;;;YAKjF;;;eAGG;;YAKH,mFAAmF;;;;YAInF;;;eAGG;;YAKH,8EAA8E;;YAK9E;;;eAGG;;YAEH,uEAAuE;;YAEvE;;;eAGG;;YAEH,4DAA4D;;;;;;;;;;;;QAgB9D,kFAAkF;;QAElF,4FAA4F;;;;;QAQ5F,6FAA6F;;QAE7F,8EAA8E;;;;QAI9E,kEAAkE;;;QAGlE,gDAAgD;;QAEhD,0DAA0D;;QAE1D,2DAA2D;;;;QAI3D,iFAAiF;;;;QAIjF,yDAAyD;;;;QAOzD,6FAA6F;;;;QAI7F,gEAAgE;;;;;;;;;;QAUhE,+DAA+D;;;;;;;;;;;;;;QAc/D,iEAAiE;;QAEjE,8DAA8D;;QAE9D,4DAA4D;;;;;QAK5D,oEAAoE;;QAIpE,6DAA6D;;QAE7D,2EAA2E;;;;;;;;;;IAU7E,mFAAmF;;;QAGjF;;;WAGG;;;;;;;;;;;;;;;;;CAsBN,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmEH,kFAAkF;AAClF,eAAO,MAAM,MAAM;;;;;;;;;;;;;;;;;;;;YAoBb,kIAAkI;;;;;;;YAOlI,iFAAiF;;;;;YAKjF;;;;eAIG;;YAKH,mFAAmF;;;;YAInF;;;eAGG;;YAKH,8EAA8E;;YAK9E;;;;eAIG;;YAEH,uEAAuE;;YAEvE;;;eAGG;;YAEH,4DAA4D;;;;;;;;;;;;QAgB9D,kFAAkF;;QAElF,4FAA4F;;;;;QAQ5F,6FAA6F;;QAE7F,8EAA8E;;;;QAI9E,kEAAkE;;QAElE;;;WAGG;;QAEH;;;WAGG;;QAEH;;;WAGG;;;QAMH,gDAAgD;;QAEhD,0DAA0D;;QAE1D;;;WAGG;;QAEH,2DAA2D;;;;QAI3D,iFAAiF;;;;QAIjF,yDAAyD;;;;QAOzD,6FAA6F;;;;QAI7F,gEAAgE;;;;;;;;;;QAUhE,+DAA+D;;;;;;;;;;;;;;QAc/D,iEAAiE;;QAEjE,8DAA8D;;QAE9D,4DAA4D;;;;;QAK5D,oEAAoE;;QAIpE,6DAA6D;;QAE7D,2EAA2E;;;;;;;;;;IAU7E,mFAAmF;;;QAGjF;;;WAGG;;;;;;;;;;;;;;;;;CAsBN,CAAC"}
|
||||
35
backend/dist/config/index.js
vendored
35
backend/dist/config/index.js
vendored
@ -101,9 +101,10 @@ exports.config = {
|
||||
rpcUrl: process.env.BSC_RPC_URL || 'https://bsc-dataseed.binance.org',
|
||||
/**
|
||||
* Extra RPCs tried for eth_getLogs when the primary returns -32005 / limit exceeded.
|
||||
* Public Binance dataseeds often ban getLogs; 1rpc / 48.club usually still work.
|
||||
* Public Binance dataseeds often ban getLogs; rpc-bsc.48.club is the reliable free fallback.
|
||||
* (1rpc.io often returns 403 from datacenter / VPS IPs — do not list it by default.)
|
||||
*/
|
||||
rpcFallbacks: (process.env.BSC_RPC_FALLBACKS || 'https://1rpc.io/bnb,https://rpc-bsc.48.club')
|
||||
rpcFallbacks: (process.env.BSC_RPC_FALLBACKS || 'https://rpc-bsc.48.club')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
@ -119,10 +120,11 @@ exports.config = {
|
||||
/** Re-scan overlap each poll to survive empty eth_getLogs / late indexing. */
|
||||
depositOverlapLookbackBlocks: parseInt(process.env.BSC_DEPOSIT_OVERLAP_LOOKBACK_BLOCKS || '5000', 10),
|
||||
/**
|
||||
* When HD still holds USDT (missed credit), rescan only this many recent blocks
|
||||
* via getLogs — not the full 7-day window (public RPCs time out).
|
||||
* When HD still holds USDT (missed credit), rescan this many recent blocks via getLogs.
|
||||
* Must be wide enough for deposits missed while public RPCs were rate-limiting
|
||||
* (≈3s/block → 200000 ≈ 7 days). Used as floor with depositInitialLookbackBlocks.
|
||||
*/
|
||||
unpaidLookbackBlocks: parseInt(process.env.BSC_UNPAID_LOOKBACK_BLOCKS || '30000', 10),
|
||||
unpaidLookbackBlocks: parseInt(process.env.BSC_UNPAID_LOOKBACK_BLOCKS || '200000', 10),
|
||||
/** Optional Etherscan V2 / BscScan key for unpaid deposit fallback. */
|
||||
explorerApiKey: process.env.BSCSCAN_API_KEY || process.env.ETHERSCAN_API_KEY || '',
|
||||
/**
|
||||
@ -158,11 +160,34 @@ exports.config = {
|
||||
treasury: {
|
||||
/** Moves on-chain deposits from user addresses to cold storage */
|
||||
sweepEnabled: process.env.SWEEP_ENABLED === 'true',
|
||||
/**
|
||||
* When true, pending sweeps execute on-chain without Approvals (after safety checks).
|
||||
* Default false — keep human approval for cold destination / amount review.
|
||||
*/
|
||||
sweepAutoExecute: process.env.SWEEP_AUTO_EXECUTE === 'true',
|
||||
/**
|
||||
* Optional raw-unit cap for auto-execute. Above this amount, sweep stays pending
|
||||
* for Submit sweeps → Approvals. Empty = no cap when SWEEP_AUTO_EXECUTE=true.
|
||||
*/
|
||||
sweepAutoMaxAmountRaw: (process.env.SWEEP_AUTO_MAX_AMOUNT_RAW || '').trim(),
|
||||
/**
|
||||
* Optional comma-separated cold addresses allowed as sweep destinations (EVM lowercased).
|
||||
* When set, active cold must match; blocks sweeps if DB cold was changed to an unknown address.
|
||||
*/
|
||||
sweepColdAllowlist: (process.env.SWEEP_COLD_ALLOWLIST || '')
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
sweepPollIntervalMs: parseInt(process.env.SWEEP_POLL_INTERVAL_MS || '120000', 10),
|
||||
/** Minimum token amount (raw units) to sweep */
|
||||
sweepMinAmountRaw: process.env.SWEEP_MIN_AMOUNT_RAW || '1000000',
|
||||
/** 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',
|
||||
},
|
||||
|
||||
2
backend/dist/config/index.js.map
vendored
2
backend/dist/config/index.js.map
vendored
File diff suppressed because one or more lines are too long
@ -9,6 +9,8 @@ export declare function requestFunding(req: AuthRequest, res: Response): Promise
|
||||
export declare function confirmFunding(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function listFunding(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function cancelFunding(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function previewHotToColdUsdt(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function requestHotToColdUsdt(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function listStuckDeposits(_req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function scanStuckDeposits(_req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function previewGasTransfer(req: AuthRequest, res: Response): Promise<void>;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"treasuryController.d.ts","sourceRoot":"","sources":["../../src/controllers/treasuryController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAKjD,wBAAsB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOjF;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAMrF;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBlF;AAED,wBAAsB,UAAU,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAU/E;AAED,wBAAsB,SAAS,CAAC,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAe/E;AAED,wBAAsB,cAAc,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA4BnF;AAED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AAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgDvF"}
|
||||
57
backend/dist/controllers/treasuryController.js
vendored
57
backend/dist/controllers/treasuryController.js
vendored
@ -42,6 +42,8 @@ exports.requestFunding = requestFunding;
|
||||
exports.confirmFunding = confirmFunding;
|
||||
exports.listFunding = listFunding;
|
||||
exports.cancelFunding = cancelFunding;
|
||||
exports.previewHotToColdUsdt = previewHotToColdUsdt;
|
||||
exports.requestHotToColdUsdt = requestHotToColdUsdt;
|
||||
exports.listStuckDeposits = listStuckDeposits;
|
||||
exports.scanStuckDeposits = scanStuckDeposits;
|
||||
exports.previewGasTransfer = previewGasTransfer;
|
||||
@ -171,6 +173,61 @@ async function cancelFunding(req, res) {
|
||||
res.status(400).json({ error: e instanceof Error ? e.message : 'Cancel failed' });
|
||||
}
|
||||
}
|
||||
async function previewHotToColdUsdt(req, res) {
|
||||
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' });
|
||||
}
|
||||
}
|
||||
async function requestHotToColdUsdt(req, res) {
|
||||
try {
|
||||
const { walletTypeId, amount, notes } = req.body;
|
||||
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' });
|
||||
}
|
||||
}
|
||||
async function listStuckDeposits(_req, res) {
|
||||
try {
|
||||
res.json(await treasuryService.listStuckDeposits());
|
||||
|
||||
File diff suppressed because one or more lines are too long
2
backend/dist/db/connection.d.ts.map
vendored
2
backend/dist/db/connection.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/db/connection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAuFtC,QAAA,MAAM,IAAI,MAIT,CAAC;AAUF,sGAAsG;AACtG,wBAAsB,sBAAsB,CAAC,MAAM,EAAE;IACnD,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC/D,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhB;AAED,kFAAkF;AAClF,wBAAsB,0BAA0B,CAAC,MAAM,EAAE;IACvD,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,O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B,OAAO,CAAC,EAAE;IAAE,kBAAkB,CAAC,EAAE,MAAM,CAAA;CAAE,GACxC,OAAO,CAAC,CAAC,CAAC,CAkBZ;AAED,4DAA4D;AAC5D,wBAAsB,SAAS,IAAI,OAAO,CAAC,UAAU,CAAC,CAErD;AAED;;;;GAIG;AACH,wBAAsB,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC,CAwBnD;AAED,6DAA6D;AAC7D,eAAe,IAAI,CAAC"}
|
||||
2
backend/dist/db/connection.js
vendored
2
backend/dist/db/connection.js
vendored
@ -192,6 +192,8 @@ async function runMigrations() {
|
||||
await client.query(sql);
|
||||
const { syncPermissionCatalog } = await Promise.resolve().then(() => __importStar(require('../rbac/syncPermissions')));
|
||||
await syncPermissionCatalog();
|
||||
const { ensureDefaultPoliciesSeeded } = await Promise.resolve().then(() => __importStar(require('../repositories/approvalPolicyRepository')));
|
||||
await ensureDefaultPoliciesSeeded();
|
||||
}
|
||||
finally {
|
||||
client.release();
|
||||
|
||||
2
backend/dist/db/connection.js.map
vendored
2
backend/dist/db/connection.js.map
vendored
File diff suppressed because one or more lines are too long
2
backend/dist/models/transaction.model.d.ts
vendored
2
backend/dist/models/transaction.model.d.ts
vendored
@ -10,7 +10,7 @@ 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;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"transaction.model.d.ts","sourceRoot":"","sources":["../../src/models/transaction.model.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,8CAA8C;AAC9C,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAA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AAC;IACtC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACzC,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,CAAC;CAClB"}
|
||||
2
backend/dist/routes/index.d.ts.map
vendored
2
backend/dist/routes/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA6HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAqZxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA8HH,QAAA,MAAM,MAAM,4CAAW,CAAC;AA0axB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
5
backend/dist/routes/index.js
vendored
5
backend/dist/routes/index.js
vendored
@ -214,6 +214,9 @@ router.get('/admin/fund-requests/:id', (0, auth_1.requireRoles)('admin'), (0, au
|
||||
router.post('/admin/fund-requests/:id/approve', (0, auth_1.requirePermissions)('fund_operation.approve'), fundApprovalController.approveFundRequest);
|
||||
router.post('/admin/fund-requests/:id/reject', (0, auth_1.requirePermissions)('fund_operation.approve'), (0, validate_1.validateBody)(adminSchemas_1.fundRequestRejectBodySchema), fundApprovalController.rejectFundRequest);
|
||||
router.delete('/admin/fund-requests/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.request'), fundApprovalController.cancelFundRequest);
|
||||
router.get('/admin/approval-policies', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('approval_policy.view'), fundApprovalController.listApprovalPolicies);
|
||||
router.get('/admin/approval-policies/revisions', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('approval_policy.view'), fundApprovalController.listPolicyRevisions);
|
||||
router.post('/admin/approval-policies/draft-change', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('approval_policy.manage'), (0, validate_1.validateBody)(adminSchemas_1.approvalPolicyDraftBodySchema), fundApprovalController.draftPolicyChange);
|
||||
router.post('/admin/users/:userId/verify-email', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('users.admin'), adminController.verifyUserEmail);
|
||||
router.patch('/admin/users/:userId/security', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('security.admin'), (0, validate_1.validateBody)(adminSchemas_1.adminUserSecurityBodySchema), securityController.updateUserSecurity);
|
||||
router.get('/admin/security/alerts', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('security.admin'), (0, validate_1.validateQuery)(querySchemas_1.securityAlertsQuerySchema), securityController.listAlerts);
|
||||
@ -269,6 +272,8 @@ router.get('/admin/treasury/sweeps', (0, auth_1.requireRoles)('admin'), (0, auth
|
||||
router.post('/admin/treasury/sweeps/run', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), treasuryController.runSweeps);
|
||||
router.get('/admin/treasury/funding', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), treasuryController.listFunding);
|
||||
router.post('/admin/treasury/funding', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), (0, validate_1.validateBody)(adminSchemas_1.treasuryFundingBodySchema), treasuryController.requestFunding);
|
||||
router.get('/admin/treasury/funding/hot-to-cold/preview', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), treasuryController.previewHotToColdUsdt);
|
||||
router.post('/admin/treasury/funding/hot-to-cold', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), (0, validate_1.validateBody)(adminSchemas_1.treasuryFundingBodySchema), treasuryController.requestHotToColdUsdt);
|
||||
router.patch('/admin/treasury/funding/:fundingId/confirm', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), (0, validate_1.validateBody)(adminSchemas_1.treasuryFundingConfirmBodySchema), treasuryController.confirmFunding);
|
||||
router.delete('/admin/treasury/funding/:fundingId', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), treasuryController.cancelFunding);
|
||||
router.get('/admin/treasury/stuck-deposits', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('treasury.view'), treasuryController.listStuckDeposits);
|
||||
|
||||
2
backend/dist/routes/index.js.map
vendored
2
backend/dist/routes/index.js.map
vendored
File diff suppressed because one or more lines are too long
@ -15,6 +15,7 @@ export declare function processBscDeposits(): Promise<void>;
|
||||
*/
|
||||
export declare function creditBscDepositByTxHash(txHash: string): Promise<{
|
||||
credited: boolean;
|
||||
alreadyCredited?: boolean;
|
||||
userId?: string;
|
||||
ledgerAmount?: string;
|
||||
reason?: string;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"depositMonitorService.d.ts","sourceRoot":"","sources":["../../src/services/depositMonitorService.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgCH,8EAA8E;AAC9E,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC,CAGxD;AAED,8EAA8E;AAC9E,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAqGzD;AAED,6FAA6F;AAC7F,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC,CAyKxD;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACtE,QAAQ,EAAE,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC,CA2ED"}
|
||||
{"version":3,"file":"depositMonitorService.d.ts","sourceRoot":"","sources":["../../src/services/depositMonitorService.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAgCH,8EAA8E;AAC9E,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC,CAGxD;AAED,8EAA8E;AAC9E,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAqGzD;AAED,6FAA6F;AAC7F,wBAAsB,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC,CAiMxD;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IACtE,QAAQ,EAAE,OAAO,CAAC;IAClB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC,CAqFD"}
|
||||
60
backend/dist/services/depositMonitorService.js
vendored
60
backend/dist/services/depositMonitorService.js
vendored
@ -186,7 +186,11 @@ async function processBscDeposits() {
|
||||
overlapLookback,
|
||||
});
|
||||
const contract = bscService.resolveUsdtContract(custodyType.contract_address);
|
||||
const unpaidAddresses = new Set();
|
||||
const custodyDecimals = custodyType.decimals ?? usdtUnits_1.BEP20_USDT_DECIMALS;
|
||||
/** HD still holding USDT that is not yet covered by ledger deposits (needs credit recover). */
|
||||
const uncreditedHd = new Set();
|
||||
/** HD with any on-chain USDT (ops log / sweep path). */
|
||||
let hdHoldingCount = 0;
|
||||
for (const { address, user_id } of userWallets) {
|
||||
try {
|
||||
const bal = await bscService.getUsdtBalanceRaw(address, contract);
|
||||
@ -196,15 +200,22 @@ async function processBscDeposits() {
|
||||
address,
|
||||
onChainAmount: bal,
|
||||
});
|
||||
if (bal > 0n)
|
||||
unpaidAddresses.add(address.toLowerCase());
|
||||
if (bal <= 0n)
|
||||
continue;
|
||||
hdHoldingCount += 1;
|
||||
const caughtUp = await depositHdSnapshotRepository.isAddressLedgerCaughtUp(address, bal, custodyDecimals);
|
||||
if (!caughtUp)
|
||||
uncreditedHd.add(address.toLowerCase());
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`[deposit] USDT_BEP20: balance check failed for ${address}:`, e);
|
||||
}
|
||||
}
|
||||
if (unpaidAddresses.size > 0) {
|
||||
console.warn(`[deposit] USDT_BEP20: ${unpaidAddresses.size} HD address(es) still hold USDT — will recover via logs + explorer`);
|
||||
if (hdHoldingCount > 0) {
|
||||
console.warn(`[deposit] USDT_BEP20: ${hdHoldingCount} HD address(es) still hold USDT` +
|
||||
(uncreditedHd.size > 0
|
||||
? ` — ${uncreditedHd.size} not yet credited (recover)`
|
||||
: ' — all already credited (awaiting sweep)'));
|
||||
}
|
||||
console.log(`[deposit] USDT_BEP20 (id=${custodyType.id}): ${userWallets.length} wallets, fromBlock=${fromBlock}, tip=${currentBlock}`);
|
||||
for (const { address, user_id } of userWallets) {
|
||||
@ -246,17 +257,19 @@ async function processBscDeposits() {
|
||||
}
|
||||
}
|
||||
// Receipt-based catch-up for HDs that still hold USDT (missed credit).
|
||||
// Order: explorer (if keyed) → getLogs via primary+fallback RPCs on a short window.
|
||||
// Public Binance dataseed often returns -32005 on eth_getLogs; fallbacks (1rpc, 48.club) work.
|
||||
const unpaidLookback = config_1.config.blockchain.bsc.unpaidLookbackBlocks;
|
||||
// Lookback must cover deposits missed while eth_getLogs was broken (days, not ~1 day).
|
||||
// Newest-first scan stops once Transfer values cover the on-chain balance.
|
||||
const unpaidLookback = Math.max(config_1.config.blockchain.bsc.unpaidLookbackBlocks, config_1.config.blockchain.bsc.depositInitialLookbackBlocks);
|
||||
for (const { address } of userWallets) {
|
||||
if (!unpaidAddresses.has(address.toLowerCase()))
|
||||
if (!uncreditedHd.has(address.toLowerCase()))
|
||||
continue;
|
||||
try {
|
||||
const still = await bscService.getUsdtBalanceRaw(address, contract);
|
||||
if (still <= 0n)
|
||||
continue;
|
||||
console.warn(`[deposit] USDT_BEP20 unpaid recover for ${address} (on-chain=${still.toString()})`);
|
||||
const recentFrom = Math.max(0, currentBlock - unpaidLookback);
|
||||
console.warn(`[deposit] USDT_BEP20 unpaid recover for ${address} (on-chain=${still.toString()}) ` +
|
||||
`lookback=${unpaidLookback} fromBlock=${recentFrom} tip=${currentBlock}`);
|
||||
const hashes = new Set();
|
||||
const viaExplorer = await bscService.listIncomingUsdtTxHashesViaExplorer(address, contract);
|
||||
for (const h of viaExplorer)
|
||||
@ -265,8 +278,8 @@ async function processBscDeposits() {
|
||||
console.log(`[deposit] USDT_BEP20 unpaid explorer found ${viaExplorer.length} tx(s) for ${address}`);
|
||||
}
|
||||
try {
|
||||
const recentFrom = Math.max(0, currentBlock - unpaidLookback);
|
||||
const recent = await bscService.getUsdtTransfersToAddress(address, contract, recentFrom, currentBlock);
|
||||
const recent = await bscService.getUsdtTransfersToAddressUntilValue(address, contract, recentFrom, currentBlock, still);
|
||||
console.log(`[deposit] USDT_BEP20 unpaid getLogs hits=${recent.length} for ${address}`);
|
||||
for (const t of recent)
|
||||
hashes.add(t.txHash);
|
||||
}
|
||||
@ -274,8 +287,8 @@ async function processBscDeposits() {
|
||||
console.warn(`[deposit] USDT_BEP20 unpaid getLogs failed for ${address}:`, e instanceof Error ? e.message : e);
|
||||
}
|
||||
if (hashes.size === 0) {
|
||||
console.error(`[deposit] USDT_BEP20 unpaid ${address}: no tx hashes (RPC getLogs + explorer empty). ` +
|
||||
`Set BSC_RPC_FALLBACKS / BSCSCAN_API_KEY or use a paid BSC RPC.`);
|
||||
console.error(`[deposit] USDT_BEP20 unpaid ${address}: no tx hashes in blocks ${recentFrom}-${currentBlock}. ` +
|
||||
`Set BSC_RPC_FALLBACKS (e.g. https://rpc-bsc.48.club) or BSCSCAN_API_KEY.`);
|
||||
continue;
|
||||
}
|
||||
for (const txHash of hashes) {
|
||||
@ -283,6 +296,9 @@ async function processBscDeposits() {
|
||||
if (result.credited) {
|
||||
console.log(`[deposit] USDT_BEP20 recovered unpaid via tx=${txHash} user=${result.userId}`);
|
||||
}
|
||||
else if (result.alreadyCredited) {
|
||||
// idempotent — expected when re-scanning
|
||||
}
|
||||
else if (result.reason && !/already|idempotent/i.test(result.reason)) {
|
||||
console.warn(`[deposit] USDT_BEP20 unpaid recover skipped tx=${txHash}: ${result.reason}`);
|
||||
}
|
||||
@ -347,7 +363,7 @@ async function creditBscDepositByTxHash(txHash) {
|
||||
const ledgerAmount = (0, usdtUnits_1.scaleChainToLedger)(transfer.value, usdtUnits_1.BEP20_USDT_DECIMALS, usdtUnits_1.LEDGER_USDT_DECIMALS);
|
||||
if (ledgerAmount <= 0n)
|
||||
return { credited: false, reason: 'amount too small after scale' };
|
||||
await creditDeposit({
|
||||
const inserted = await creditDeposit({
|
||||
userId: wallet.user_id,
|
||||
ledgerWalletTypeId: ledgerType.id,
|
||||
custodyWalletTypeId: custodyType.id,
|
||||
@ -361,6 +377,15 @@ async function creditBscDepositByTxHash(txHash) {
|
||||
confirmations,
|
||||
requiredConfirmations: BSC_CONFIRMATIONS,
|
||||
});
|
||||
if (!inserted) {
|
||||
return {
|
||||
credited: false,
|
||||
alreadyCredited: true,
|
||||
userId: wallet.user_id,
|
||||
ledgerAmount: ledgerAmount.toString(),
|
||||
reason: 'already credited (idempotent)',
|
||||
};
|
||||
}
|
||||
return {
|
||||
credited: true,
|
||||
userId: wallet.user_id,
|
||||
@ -391,7 +416,7 @@ async function creditDeposit(opts) {
|
||||
});
|
||||
if (!tx) {
|
||||
await client.query('COMMIT');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
await ledgerRepository.creditUsingClient(client, account.id, opts.ledgerAmount, 'deposit', 'transaction', tx.id);
|
||||
await networkInventoryRepository.creditUsingClient(client, opts.userId, opts.network, opts.ledgerAmount);
|
||||
@ -406,7 +431,7 @@ async function creditDeposit(opts) {
|
||||
client.release();
|
||||
}
|
||||
if (!tx)
|
||||
return;
|
||||
return false;
|
||||
await referralService.processFirstDepositReferralCommissions({
|
||||
userId: opts.userId,
|
||||
depositTransactionId: tx.id,
|
||||
@ -429,5 +454,6 @@ async function creditDeposit(opts) {
|
||||
// Sweep uses custody type + on-chain amount
|
||||
await (0, sweepService_1.enqueueSweepAfterDeposit)(opts.userId, opts.custodyWalletTypeId, opts.chainAmount, tx.id);
|
||||
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(opts.userId);
|
||||
return true;
|
||||
}
|
||||
//# sourceMappingURL=depositMonitorService.js.map
|
||||
File diff suppressed because one or more lines are too long
5
backend/dist/services/sweepService.d.ts
vendored
5
backend/dist/services/sweepService.d.ts
vendored
@ -12,6 +12,11 @@ export declare function processPendingSweeps(opts?: {
|
||||
batchId?: string;
|
||||
limit?: number;
|
||||
}): Promise<number>;
|
||||
/**
|
||||
* Auto path: execute pending sweeps that pass SWEEP_AUTO_EXECUTE + optional max amount,
|
||||
* without going through Approvals. Large sweeps (over max) stay queued for manual approval.
|
||||
*/
|
||||
export declare function processAutoEligibleSweeps(): Promise<number>;
|
||||
export declare function executeApprovedBatch(batchId: string): Promise<number>;
|
||||
export declare function getSweepPollIntervalMs(): number;
|
||||
//# sourceMappingURL=sweepService.d.ts.map
|
||||
2
backend/dist/services/sweepService.d.ts.map
vendored
2
backend/dist/services/sweepService.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"sweepService.d.ts","sourceRoot":"","sources":["../../src/services/sweepService.ts"],"names":[],"mappings":"AAAA;;GAEG;AA8CH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,oBAAoB,EAAE,MAAM,GAC3B,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAED,wBAAsB,kCAAkC,IAAI,OAAO,CAAC;IAClE,YAAY,EAAE,OAAO,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC,CAoCD;AAsFD,wBAAsB,oBAAoB,CAAC,IAAI,CAAC,EAAE;IAChD,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC,MAAM,CAAC,CAwBlB;AAED,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAU3E;AAED,wBAAgB,sBAAsB,IAAI,MAAM,CAE/C"}
|
||||
{"version":3,"file":"sweepService.d.ts","sourceRoot":"","sources":["../../src/services/sweepService.ts"],"names":[],"mappings":"AAAA;;GAEG;AAwIH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,MAAM,EACpB,MAAM,EAAE,MAAM,EACd,oBAAoB,EAAE,MAAM,GAC3B,OAAO,CAAC,IAAI,CAAC,CA8Cf;AAED,wBAAsB,kCAAkC,IAAI,OAAO,CAAC;IAClE,YAAY,EAAE,OAAO,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC,CAoCD;AAuID,wBAAsB,oBAAoB,CAAC,IAAI,CAAC,EAAE;IAChD,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC,MAAM,CAAC,CAsBlB;AAED;;;GAGG;AACH,wBAAsB,yBAAyB,IAAI,OAAO,CAAC,MAAM,CAAC,CAgEjE;AAED,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAU3E;AAED,wBAAgB,sBAAsB,IAAI,MAAM,CAE/C"}
|
||||
201
backend/dist/services/sweepService.js
vendored
201
backend/dist/services/sweepService.js
vendored
@ -39,6 +39,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.enqueueSweepAfterDeposit = enqueueSweepAfterDeposit;
|
||||
exports.enqueueSweepsForCreditedHdBalances = enqueueSweepsForCreditedHdBalances;
|
||||
exports.processPendingSweeps = processPendingSweeps;
|
||||
exports.processAutoEligibleSweeps = processAutoEligibleSweeps;
|
||||
exports.executeApprovedBatch = executeApprovedBatch;
|
||||
exports.getSweepPollIntervalMs = getSweepPollIntervalMs;
|
||||
const bip39 = __importStar(require("bip39"));
|
||||
@ -66,6 +67,80 @@ function getMnemonic() {
|
||||
function minSweepAmount() {
|
||||
return BigInt(config_1.config.treasury.sweepMinAmountRaw);
|
||||
}
|
||||
function normalizeChainAddress(network, address) {
|
||||
const a = address.trim();
|
||||
if (network === 'BSC' || network === 'POLYGON' || a.startsWith('0x') || a.startsWith('0X')) {
|
||||
return a.toLowerCase();
|
||||
}
|
||||
return a;
|
||||
}
|
||||
function addressesMatch(network, a, b) {
|
||||
return normalizeChainAddress(network, a) === normalizeChainAddress(network, b);
|
||||
}
|
||||
function isColdOnAllowlist(network, coldAddress) {
|
||||
const list = config_1.config.treasury.sweepColdAllowlist;
|
||||
if (list.length === 0)
|
||||
return true;
|
||||
const want = normalizeChainAddress(network, coldAddress);
|
||||
return list.some((entry) => normalizeChainAddress(network, entry) === want);
|
||||
}
|
||||
function isAutoExecuteEligible(amount) {
|
||||
if (!config_1.config.treasury.sweepAutoExecute)
|
||||
return false;
|
||||
const maxRaw = config_1.config.treasury.sweepAutoMaxAmountRaw;
|
||||
if (maxRaw) {
|
||||
try {
|
||||
if (amount > BigInt(maxRaw))
|
||||
return false;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Re-validates destination + amount immediately before broadcast.
|
||||
* Prevents sweeping to a cold address that changed / is not allowlisted.
|
||||
*/
|
||||
async function assertSweepSafeToExecute(sweep) {
|
||||
const walletType = await walletRepository.getWalletTypeById(sweep.wallet_type_id);
|
||||
if (!walletType)
|
||||
throw new Error('Unknown wallet type');
|
||||
const amount = BigInt(sweep.amount);
|
||||
if (amount < minSweepAmount()) {
|
||||
throw new Error(`Sweep amount below SWEEP_MIN_AMOUNT_RAW (${amount} < ${minSweepAmount()})`);
|
||||
}
|
||||
const cold = await coldWalletRepository.getActiveColdWallet(sweep.wallet_type_id);
|
||||
if (!cold)
|
||||
throw new Error('No active cold wallet for this network');
|
||||
if (!addressesMatch(walletType.network, cold.address, sweep.to_cold_address)) {
|
||||
throw new Error(`Sweep destination mismatch: queued=${sweep.to_cold_address} activeCold=${cold.address}`);
|
||||
}
|
||||
if (!isColdOnAllowlist(walletType.network, cold.address)) {
|
||||
throw new Error(`Cold address ${cold.address} is not in SWEEP_COLD_ALLOWLIST — refusing sweep`);
|
||||
}
|
||||
// On-chain balance must cover the queued amount (guards against stale / wrong enqueue).
|
||||
if (walletType.network === 'BSC' || walletType.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
||||
const contract = bscService.resolveUsdtContract(walletType.contract_address);
|
||||
const bal = await bscService.getUsdtBalanceRaw(sweep.from_address, contract);
|
||||
if (bal < amount) {
|
||||
throw new Error(`HD balance ${bal.toString()} < sweep amount ${amount.toString()} for ${sweep.from_address}`);
|
||||
}
|
||||
}
|
||||
else if (walletType.network === 'TRON') {
|
||||
const trc20Contract = walletType.code === walletCapabilities_1.USDT_TRC20_CODE && config_1.config.blockchain.tron.usdtTrc20Contract
|
||||
? config_1.config.blockchain.tron.usdtTrc20Contract
|
||||
: walletType.contract_address;
|
||||
if (trc20Contract) {
|
||||
const bal = await tronService.getTrc20BalanceRaw(sweep.from_address, trc20Contract);
|
||||
if (bal < amount) {
|
||||
throw new Error(`HD balance ${bal.toString()} < sweep amount ${amount.toString()} for ${sweep.from_address}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { network: walletType.network, walletType };
|
||||
}
|
||||
function deriveDepositPrivateKey(network, derivationIndex) {
|
||||
const mnemonic = getMnemonic();
|
||||
if (network === 'TRON') {
|
||||
@ -89,6 +164,13 @@ async function enqueueSweepAfterDeposit(userId, walletTypeId, amount, depositTra
|
||||
}
|
||||
return;
|
||||
}
|
||||
const walletType = await walletRepository.getWalletTypeById(walletTypeId);
|
||||
if (!walletType)
|
||||
return;
|
||||
if (!isColdOnAllowlist(walletType.network, cold.address)) {
|
||||
console.error(`[sweep] Active cold ${cold.address} not in SWEEP_COLD_ALLOWLIST — not enqueueing`);
|
||||
return;
|
||||
}
|
||||
const userWallet = await walletRepository.getUserWallet(userId, walletTypeId);
|
||||
if (!userWallet)
|
||||
return;
|
||||
@ -105,6 +187,12 @@ async function enqueueSweepAfterDeposit(userId, walletTypeId, amount, depositTra
|
||||
batchId: batch.id,
|
||||
});
|
||||
await depositSweepBatchRepository.incrementBatchCount(batch.id);
|
||||
// Don't wait for the 1–2 min poll — run auto path right after enqueue.
|
||||
if (isAutoExecuteEligible(amount)) {
|
||||
void processAutoEligibleSweeps().catch((e) => {
|
||||
console.error('[sweep] post-enqueue auto-execute error:', e);
|
||||
});
|
||||
}
|
||||
}
|
||||
async function enqueueSweepsForCreditedHdBalances() {
|
||||
if (!config_1.config.treasury.sweepEnabled) {
|
||||
@ -170,12 +258,13 @@ async function ensurePolygonGasForUsdcSweep(depositAddress, hotPrivateKey) {
|
||||
await polygonService.sendMatic(hotPrivateKey, depositAddress, topUp);
|
||||
}
|
||||
async function executeSweep(sweep) {
|
||||
const walletType = await walletRepository.getWalletTypeById(sweep.wallet_type_id);
|
||||
if (!walletType)
|
||||
throw new Error('Unknown wallet type');
|
||||
const { walletType } = await assertSweepSafeToExecute(sweep);
|
||||
const userWallet = await walletRepository.getUserWallet(sweep.user_id, sweep.wallet_type_id);
|
||||
if (!userWallet)
|
||||
throw new Error('User deposit wallet not found');
|
||||
if (!addressesMatch(walletType.network, userWallet.address, sweep.from_address)) {
|
||||
throw new Error(`Sweep from_address mismatch: queued=${sweep.from_address} userWallet=${userWallet.address}`);
|
||||
}
|
||||
const amount = BigInt(sweep.amount);
|
||||
const privateKey = deriveDepositPrivateKey(walletType.network, userWallet.derivation_index);
|
||||
await depositSweepRepository.updateSweepStatus(sweep.id, 'broadcasting');
|
||||
@ -219,6 +308,47 @@ async function executeSweep(sweep) {
|
||||
throw new Error('Unsupported network');
|
||||
}
|
||||
await depositSweepRepository.updateSweepStatus(sweep.id, 'completed', { blockchainTxId: txId });
|
||||
// Treasury "USDT still on HD" reads deposit_hd_snapshots; refresh so the row clears
|
||||
// without waiting for the next deposit-monitor poll / manual Scan & credit.
|
||||
try {
|
||||
let remaining = 0n;
|
||||
if (walletType.network === 'TRON') {
|
||||
const trc20Contract = walletType.code === walletCapabilities_1.USDT_TRC20_CODE && config_1.config.blockchain.tron.usdtTrc20Contract
|
||||
? config_1.config.blockchain.tron.usdtTrc20Contract
|
||||
: walletType.contract_address;
|
||||
if (trc20Contract) {
|
||||
remaining = await tronService.getTrc20BalanceRaw(sweep.from_address, trc20Contract);
|
||||
}
|
||||
}
|
||||
else if (walletType.network === 'BSC' || walletType.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
||||
const contract = bscService.resolveUsdtContract(walletType.contract_address);
|
||||
remaining = await bscService.getUsdtBalanceRaw(sweep.from_address, contract);
|
||||
}
|
||||
else if (walletType.network === 'POLYGON') {
|
||||
remaining = await polygonService.getUsdcBalanceRaw(sweep.from_address);
|
||||
}
|
||||
const { upsertSnapshot } = await Promise.resolve().then(() => __importStar(require('../repositories/depositHdSnapshotRepository')));
|
||||
await upsertSnapshot({
|
||||
userId: sweep.user_id,
|
||||
walletTypeId: sweep.wallet_type_id,
|
||||
address: sweep.from_address,
|
||||
onChainAmount: remaining,
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
console.warn(`[sweep] HD balance re-read failed after sweep ${sweep.id}:`, e instanceof Error ? e.message : e);
|
||||
try {
|
||||
const { decreaseSnapshotBy } = await Promise.resolve().then(() => __importStar(require('../repositories/depositHdSnapshotRepository')));
|
||||
await decreaseSnapshotBy({
|
||||
userId: sweep.user_id,
|
||||
walletTypeId: sweep.wallet_type_id,
|
||||
amount,
|
||||
});
|
||||
}
|
||||
catch (e2) {
|
||||
console.warn(`[sweep] HD snapshot decrease failed after sweep ${sweep.id}:`, e2 instanceof Error ? e2.message : e2);
|
||||
}
|
||||
}
|
||||
}
|
||||
async function processPendingSweeps(opts) {
|
||||
if (!config_1.config.treasury.sweepEnabled)
|
||||
@ -232,9 +362,7 @@ async function processPendingSweeps(opts) {
|
||||
try {
|
||||
await executeSweep(sweep);
|
||||
processed++;
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(`[sweep] Completed sweep ${sweep.id} → cold`);
|
||||
}
|
||||
console.log(`[sweep] Completed sweep ${sweep.id} → ${sweep.to_cold_address}`);
|
||||
}
|
||||
catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
@ -244,6 +372,67 @@ async function processPendingSweeps(opts) {
|
||||
}
|
||||
return processed;
|
||||
}
|
||||
/**
|
||||
* Auto path: execute pending sweeps that pass SWEEP_AUTO_EXECUTE + optional max amount,
|
||||
* without going through Approvals. Large sweeps (over max) stay queued for manual approval.
|
||||
*/
|
||||
async function processAutoEligibleSweeps() {
|
||||
if (!config_1.config.treasury.sweepEnabled) {
|
||||
console.warn('[sweep] auto-execute skipped: SWEEP_ENABLED is not true');
|
||||
return 0;
|
||||
}
|
||||
if (!config_1.config.treasury.sweepAutoExecute) {
|
||||
console.warn('[sweep] auto-execute skipped: SWEEP_AUTO_EXECUTE is not true');
|
||||
return 0;
|
||||
}
|
||||
const pending = await depositSweepRepository.listPendingSweeps(25);
|
||||
if (pending.length === 0)
|
||||
return 0;
|
||||
console.log(`[sweep] auto-execute: ${pending.length} pending sweep(s) to consider`);
|
||||
let processed = 0;
|
||||
let skippedMax = 0;
|
||||
for (const sweep of pending) {
|
||||
const amount = BigInt(sweep.amount);
|
||||
if (!isAutoExecuteEligible(amount)) {
|
||||
skippedMax += 1;
|
||||
console.warn(`[sweep] skip ${sweep.id}: amount ${sweep.amount} above SWEEP_AUTO_MAX_AMOUNT_RAW=` +
|
||||
`${config_1.config.treasury.sweepAutoMaxAmountRaw || '(unset)'} (BEP20 uses 18 decimals)`);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await executeSweep(sweep);
|
||||
processed += 1;
|
||||
console.log(`[sweep] auto-executed ${sweep.id} amount=${sweep.amount} → ${sweep.to_cold_address}`);
|
||||
try {
|
||||
const auditLogRepository = await Promise.resolve().then(() => __importStar(require('../repositories/auditLogRepository')));
|
||||
await auditLogRepository.create({
|
||||
userId: sweep.user_id,
|
||||
action: 'sweep_auto_executed',
|
||||
resourceType: 'deposit_sweep',
|
||||
resourceId: sweep.id,
|
||||
metadata: {
|
||||
amount: sweep.amount,
|
||||
from: sweep.from_address,
|
||||
to: sweep.to_cold_address,
|
||||
walletTypeId: sweep.wallet_type_id,
|
||||
},
|
||||
});
|
||||
}
|
||||
catch {
|
||||
// audit must not block sweep success
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
console.error(`[sweep] auto-execute failed ${sweep.id}:`, msg);
|
||||
await depositSweepRepository.updateSweepStatus(sweep.id, 'failed', { errorMessage: msg });
|
||||
}
|
||||
}
|
||||
if (skippedMax > 0) {
|
||||
console.warn(`[sweep] ${skippedMax} sweep(s) left for Approvals (over SWEEP_AUTO_MAX_AMOUNT_RAW)`);
|
||||
}
|
||||
return processed;
|
||||
}
|
||||
async function executeApprovedBatch(batchId) {
|
||||
await depositSweepBatchRepository.markBatchStatus(batchId, 'executing');
|
||||
try {
|
||||
|
||||
2
backend/dist/services/sweepService.js.map
vendored
2
backend/dist/services/sweepService.js.map
vendored
File diff suppressed because one or more lines are too long
39
backend/dist/services/treasuryService.d.ts
vendored
39
backend/dist/services/treasuryService.d.ts
vendored
@ -111,6 +111,45 @@ export declare function executeHotToColdGas(input: {
|
||||
symbol: string;
|
||||
message: string;
|
||||
}>;
|
||||
/** Preview USDT (or network token) Hot → Cold: balances, gas, maxSendable after reserve. */
|
||||
export declare function previewHotToColdUsdt(walletTypeId: number): Promise<{
|
||||
walletTypeId: number;
|
||||
network: string;
|
||||
walletCode: string;
|
||||
tokenSymbol: string;
|
||||
tokenDecimals: number;
|
||||
tokenContract: string;
|
||||
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;
|
||||
}>;
|
||||
/** Platform-signed USDT Hot → Cold after Super Admin approval. */
|
||||
export declare function executeHotToColdUsdt(input: {
|
||||
walletTypeId: number;
|
||||
amountRaw: bigint;
|
||||
notes?: string;
|
||||
requestedBy: string;
|
||||
approvedBy: string;
|
||||
}): Promise<{
|
||||
fundingId: string;
|
||||
blockchainTxId: string;
|
||||
from: string;
|
||||
to: string;
|
||||
amount: string;
|
||||
symbol: string;
|
||||
network: string;
|
||||
message: string;
|
||||
}>;
|
||||
export declare function requestColdToHotGasFunding(requestedBy: string, input: {
|
||||
walletTypeId: number;
|
||||
amountRaw: bigint;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"treasuryService.d.ts","sourceRoot":"","sources":["../../src/services/treasuryService.ts"],"names":[],"mappings":"AAAA;;GAEG;AAuDH,wBAAsB,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwGxC;AAED,wBAAsB,aAAa,CAAC,KAAK,EAAE;IACzC,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;;;;;GAcA;AAED,wBAAsB,eAAe;;;;;;;KAUpC;AAED,wBAAsB,UAAU,CAAC,IAAI,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE;;;;;;;;;;;;;;;GAoB1F;AAqBD,wBAAsB,mBAAmB,CAAC,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S,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;;;;;;;;GAwBF;AAED,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,KAAK,EAAE;IACL,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;;;;;;;GA4BF;AAED,wBAAsB,uBAAuB,CAC3C,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,cAAc,EAAE,MAAM;;;;GAmBvB;AA+FD,wBAAsB,WAAW,CAAC,IAAI,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE;;;;;;;;;;;;;;;GAkB3F;AAED,wBAAsB,aAAa,CAAC,SAAS,EAAE,MAAM,iBAEpD;AAED,MAAM,MAAM,iBAAiB,GACzB,YAAY,GACZ,yBAAyB,GACzB,cAAc,GACd,sBAAsB,CAAC;AAa3B,wBAAsB,iBAAiB;;;;;;;;;;;;;;;;GAmBtC;AAED,wBAAsB,iBAAiB;;;;;;;;;;;;;;;;;;;GAYtC"}
|
||||
211
backend/dist/services/treasuryService.js
vendored
211
backend/dist/services/treasuryService.js
vendored
@ -42,6 +42,8 @@ exports.listColdWallets = listColdWallets;
|
||||
exports.listSweeps = listSweeps;
|
||||
exports.previewHotToColdGas = previewHotToColdGas;
|
||||
exports.executeHotToColdGas = executeHotToColdGas;
|
||||
exports.previewHotToColdUsdt = previewHotToColdUsdt;
|
||||
exports.executeHotToColdUsdt = executeHotToColdUsdt;
|
||||
exports.requestColdToHotGasFunding = requestColdToHotGasFunding;
|
||||
exports.requestColdToHotFunding = requestColdToHotFunding;
|
||||
exports.confirmColdToHotFunding = confirmColdToHotFunding;
|
||||
@ -356,6 +358,133 @@ async function executeHotToColdGas(input) {
|
||||
message: `Sent ${preview.symbol} from hot to cold`,
|
||||
};
|
||||
}
|
||||
function hotUsdtMinReserveRaw() {
|
||||
try {
|
||||
return BigInt(config_1.config.treasury.hotUsdtMinReserveRaw || '0');
|
||||
}
|
||||
catch {
|
||||
return 0n;
|
||||
}
|
||||
}
|
||||
/** Preview USDT (or network token) Hot → Cold: balances, gas, maxSendable after reserve. */
|
||||
async function previewHotToColdUsdt(walletTypeId) {
|
||||
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 = hotLiquidityService_1.MIN_BNB_WEI_FOR_WITHDRAWAL;
|
||||
let txBuffer = BSC_NATIVE_TX_BUFFER_WEI;
|
||||
let tokenContract = '';
|
||||
if (wt.network === 'BSC' || wt.code === walletCapabilities_1.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 === walletCapabilities_1.USDT_TRC20_CODE) {
|
||||
tokenContract =
|
||||
config_1.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 = hotLiquidityService_1.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. */
|
||||
async function executeHotToColdUsdt(input) {
|
||||
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 = (0, hdWallet_1.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;
|
||||
try {
|
||||
if (preview.network === 'BSC' || preview.walletCode === walletCapabilities_1.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',
|
||||
};
|
||||
}
|
||||
async function requestColdToHotGasFunding(requestedBy, input) {
|
||||
const preview = await previewHotToColdGas(input.walletTypeId);
|
||||
if (input.amountRaw <= 0n)
|
||||
@ -409,9 +538,15 @@ async function requestColdToHotFunding(requestedBy, input) {
|
||||
};
|
||||
}
|
||||
async function confirmColdToHotFunding(adminUserId, fundingId, blockchainTxId) {
|
||||
if (!blockchainTxId?.trim())
|
||||
const txId = blockchainTxId?.trim();
|
||||
if (!txId)
|
||||
throw new Error('blockchainTxId is required');
|
||||
const row = await exchangeFundingRepository.confirmFunding(fundingId, blockchainTxId.trim(), adminUserId);
|
||||
const funding = await exchangeFundingRepository.findFundingById(fundingId);
|
||||
if (!funding || funding.status !== 'pending') {
|
||||
throw new Error('Funding request not found or not pending');
|
||||
}
|
||||
await assertFundingTxMatchesRequest(funding, txId);
|
||||
const row = await exchangeFundingRepository.confirmFunding(fundingId, txId, adminUserId);
|
||||
if (!row)
|
||||
throw new Error('Funding request not found or not pending');
|
||||
return {
|
||||
@ -420,6 +555,78 @@ async function confirmColdToHotFunding(adminUserId, fundingId, blockchainTxId) {
|
||||
blockchainTxId: row.blockchain_tx_id,
|
||||
};
|
||||
}
|
||||
function addrEq(a, b) {
|
||||
if (!a || !b)
|
||||
return false;
|
||||
const na = a.trim();
|
||||
const nb = b.trim();
|
||||
if (na.startsWith('0x') || nb.startsWith('0x'))
|
||||
return na.toLowerCase() === nb.toLowerCase();
|
||||
return na === nb;
|
||||
}
|
||||
/**
|
||||
* Reject Confirm when the pasted tx does not match the pending funding row
|
||||
* (wrong amount / addresses / asset) so history stays consistent with chain.
|
||||
*/
|
||||
async function assertFundingTxMatchesRequest(funding, txId) {
|
||||
const walletType = await walletRepository.getWalletTypeById(funding.wallet_type_id);
|
||||
if (!walletType)
|
||||
throw new Error('Unknown wallet type for funding request');
|
||||
const expectedAmount = BigInt(funding.amount);
|
||||
const isGas = funding.direction === 'cold_to_hot_gas' || funding.direction === 'hot_to_cold_gas';
|
||||
if (walletType.network === 'BSC' || walletType.code === walletCapabilities_1.USDT_BEP20_CODE) {
|
||||
if (!/^0x[0-9a-fA-F]{64}$/.test(txId)) {
|
||||
throw new Error('Invalid BSC transaction hash (expected 0x + 64 hex chars)');
|
||||
}
|
||||
const receipt = await bscService.getTransactionReceipt(txId);
|
||||
if (!receipt)
|
||||
throw new Error('Transaction not found on BSC (wait for confirmation, then retry)');
|
||||
if (receipt.status !== 1)
|
||||
throw new Error('Transaction failed on-chain');
|
||||
if (isGas) {
|
||||
const native = await bscService.getNativeTransfer(txId);
|
||||
if (!native)
|
||||
throw new Error('Transaction not found on BSC (wait for confirmation, then retry)');
|
||||
if (native.status !== 1)
|
||||
throw new Error('Transaction failed on-chain');
|
||||
if (!addrEq(native.from, funding.from_address)) {
|
||||
throw new Error(`Tx from ${native.from} does not match funding from ${funding.from_address}`);
|
||||
}
|
||||
if (!addrEq(native.to, funding.to_address)) {
|
||||
throw new Error(`Tx to ${native.to} does not match funding to ${funding.to_address}`);
|
||||
}
|
||||
if (native.value !== expectedAmount) {
|
||||
throw new Error(`On-chain amount ${native.value.toString()} wei does not match funding request ${expectedAmount.toString()} wei. Cancel and recreate the request with the real amount, or send exactly the requested amount.`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const contract = bscService.resolveUsdtContract(walletType.contract_address).toLowerCase();
|
||||
const match = receipt.transfers.find((t) => t.contract.toLowerCase() === contract &&
|
||||
addrEq(t.from, funding.from_address) &&
|
||||
addrEq(t.to, funding.to_address) &&
|
||||
t.value === expectedAmount);
|
||||
if (!match) {
|
||||
const usdtToHot = receipt.transfers.filter((t) => t.contract.toLowerCase() === contract &&
|
||||
addrEq(t.to, funding.to_address));
|
||||
if (usdtToHot.length === 0) {
|
||||
throw new Error('No USDT BEP20 Transfer to the hot wallet found in this tx. Check the hash and destination.');
|
||||
}
|
||||
const got = usdtToHot.map((t) => t.value.toString()).join(', ');
|
||||
throw new Error(`On-chain USDT amount(s) [${got}] do not match funding request ${expectedAmount.toString()} (raw). ` +
|
||||
`Send exactly the requested amount, or Cancel this request and create a new one for the amount you actually sent.`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (walletType.network === 'TRON') {
|
||||
// TRON receipt verification is limited here; still require a plausible tx id length.
|
||||
if (!/^[0-9a-fA-F]{64}$/.test(txId)) {
|
||||
throw new Error('Invalid TRON transaction id (expected 64 hex characters)');
|
||||
}
|
||||
console.warn(`[treasury] confirm ${funding.id}: TRON tx ${txId} accepted without full amount verify yet`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`Unsupported network for funding confirm: ${walletType.network}`);
|
||||
}
|
||||
async function listFunding(opts) {
|
||||
const result = await exchangeFundingRepository.listFunding(opts);
|
||||
return {
|
||||
|
||||
2
backend/dist/services/treasuryService.js.map
vendored
2
backend/dist/services/treasuryService.js.map
vendored
File diff suppressed because one or more lines are too long
8
backend/dist/services/withdrawalService.d.ts
vendored
8
backend/dist/services/withdrawalService.d.ts
vendored
@ -4,13 +4,14 @@
|
||||
* rail hot wallet (TRC20 or BEP20). Network need not match deposit history —
|
||||
* liquidity is gated by hot float (USDT + gas), not user inventory.
|
||||
*/
|
||||
import { SecurityBlockedError } from './securityService';
|
||||
export type WithdrawalResult = {
|
||||
transactionId: string;
|
||||
status: string;
|
||||
amount: string;
|
||||
fee: string;
|
||||
totalDebited: string;
|
||||
fundRequestId?: string;
|
||||
blockchainTxId?: string | null;
|
||||
};
|
||||
/**
|
||||
* Submits a withdrawal: locks unified ledger, verifies hot float, pays from rail hot wallet.
|
||||
@ -18,5 +19,8 @@ export type WithdrawalResult = {
|
||||
* `amountRaw` is always in ledger micro-USDT (6 decimals).
|
||||
*/
|
||||
export declare function requestWithdrawal(userId: string, walletTypeCode: string, toAddress: string, amountRaw: bigint, totpCode?: string): Promise<WithdrawalResult>;
|
||||
export { SecurityBlockedError };
|
||||
/** Resume on-chain broadcast after Approvals quorum for a large withdrawal. */
|
||||
export declare function broadcastApprovedWithdrawal(transactionId: string, approvedBy: string): Promise<Record<string, unknown>>;
|
||||
/** Unlock ledger and fail tx when a large-withdrawal approval is rejected/cancelled. */
|
||||
export declare function abandonPendingWithdrawal(transactionId: string, reason: string): Promise<void>;
|
||||
//# sourceMappingURL=withdrawalService.d.ts.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"withdrawalService.d.ts","sourceRoot":"","sources":["../../src/services/withdrawalService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAeH,OAAO,EAGL,oBAAoB,EACrB,MAAM,mBAAmB,CAAC;AAuF3B,MAAM,MAAM,gBAAgB,GAAG;IAC7B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,gBAAgB,CAAC,CAiN3B;AAED,OAAO,EAAE,oBAAoB,EAAE,CAAC"}
|
||||
{"version":3,"file":"withdrawalService.d.ts","sourceRoot":"","sources":["../../src/services/withdrawalService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA0GH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC,CAAC;AAEF;;;;GAIG;AACH,wBAAsB,iBAAiB,CACrC,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,QAAQ,CAAC,EAAE,MAAM,GAChB,OAAO,CAAC,gBAAgB,CAAC,CA0J3B;AAED,+EAA+E;AAC/E,wBAAsB,2BAA2B,CAC/C,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CA8ClC;AAsID,wFAAwF;AACxF,wBAAsB,wBAAwB,CAAC,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAuBnG"}
|
||||
157
backend/dist/services/withdrawalService.js
vendored
157
backend/dist/services/withdrawalService.js
vendored
@ -39,8 +39,9 @@ var __importStar = (this && this.__importStar) || (function () {
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.SecurityBlockedError = void 0;
|
||||
exports.requestWithdrawal = requestWithdrawal;
|
||||
exports.broadcastApprovedWithdrawal = broadcastApprovedWithdrawal;
|
||||
exports.abandonPendingWithdrawal = abandonPendingWithdrawal;
|
||||
const config_1 = require("../config");
|
||||
const hdWallet_1 = require("./hdWallet");
|
||||
const ledgerRepository = __importStar(require("../repositories/ledgerRepository"));
|
||||
@ -55,7 +56,6 @@ const polygonService = __importStar(require("./blockchain/polygonService"));
|
||||
const bscService = __importStar(require("./blockchain/bscService"));
|
||||
const withdrawalFee_1 = require("../utils/withdrawalFee");
|
||||
const securityService_1 = require("./securityService");
|
||||
Object.defineProperty(exports, "SecurityBlockedError", { enumerable: true, get: function () { return securityService_1.SecurityBlockedError; } });
|
||||
const authService = __importStar(require("./authService"));
|
||||
const userAdminStatsService_1 = require("./userAdminStatsService");
|
||||
const referralService = __importStar(require("./referralService"));
|
||||
@ -215,10 +215,104 @@ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, t
|
||||
network,
|
||||
},
|
||||
});
|
||||
const amountUsd = (0, withdrawalLimits_1.rawAmountToUsdApprox)(walletCapabilities_1.USDT_TRC20_CODE, amountRaw, usdtUnits_1.LEDGER_USDT_DECIMALS);
|
||||
if (amountUsd >= settings.large_withdrawal_threshold_usd) {
|
||||
await transactionRepository.updateStatus(tx.id, 'pending_approval');
|
||||
const { createFundRequest } = await Promise.resolve().then(() => __importStar(require('./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. */
|
||||
async function broadcastApprovedWithdrawal(transactionId, approvedBy) {
|
||||
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 ?? {});
|
||||
const walletTypeCode = String(meta.rail_wallet_type || '');
|
||||
const network = String(meta.network || '');
|
||||
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(walletCapabilities_1.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) {
|
||||
const { txId, userId, accountId, totalDebit, amountRaw, feeRaw, toAddress, network, walletTypeCode, railWalletType, hotWallet, ledgerWalletTypeId, } = input;
|
||||
let blockchainTxId = null;
|
||||
try {
|
||||
const privateKey = (0, hdWallet_1.decryptPrivateKey)(hotWallet.encrypted_private_key);
|
||||
await transactionRepository.updateStatus(tx.id, 'broadcasting');
|
||||
await transactionRepository.updateStatus(txId, 'broadcasting');
|
||||
if (railWalletType.network === 'TRON') {
|
||||
const trc20Contract = config_1.config.blockchain.tron.usdtTrc20Contract || railWalletType.contract_address;
|
||||
if (!trc20Contract)
|
||||
@ -236,23 +330,23 @@ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, t
|
||||
else {
|
||||
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 (0, securityService_1.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()}. ` +
|
||||
details: `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(),
|
||||
@ -265,7 +359,7 @@ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, t
|
||||
userId,
|
||||
action: 'withdrawal_completed',
|
||||
resourceType: 'transaction',
|
||||
resourceId: tx.id,
|
||||
resourceId: txId,
|
||||
metadata: {
|
||||
amount: amountRaw.toString(),
|
||||
fee: feeRaw.toString(),
|
||||
@ -279,32 +373,33 @@ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, t
|
||||
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) },
|
||||
});
|
||||
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(userId);
|
||||
@ -314,4 +409,30 @@ async function requestWithdrawal(userId, walletTypeCode, toAddress, amountRaw, t
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
/** Unlock ledger and fail tx when a large-withdrawal approval is rejected/cancelled. */
|
||||
async function abandonPendingWithdrawal(transactionId, reason) {
|
||||
const tx = await transactionRepository.findById(transactionId);
|
||||
if (!tx)
|
||||
return;
|
||||
if (tx.status !== 'pending_approval' && tx.status !== 'pending')
|
||||
return;
|
||||
const ledgerWalletType = await walletRepository.getWalletTypeByCode(walletCapabilities_1.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 },
|
||||
});
|
||||
(0, userAdminStatsService_1.queueUserAdminStatsRefresh)(tx.user_id);
|
||||
}
|
||||
//# sourceMappingURL=withdrawalService.js.map
|
||||
File diff suppressed because one or more lines are too long
@ -34,6 +34,8 @@
|
||||
"rotate-deposit-addresses:prod": "node dist/scripts/rotateDepositAddresses.js",
|
||||
"verify-deposit-addresses": "ts-node --transpile-only src/scripts/verifyDepositAddresses.ts",
|
||||
"verify-deposit-addresses:prod": "node dist/scripts/verifyDepositAddresses.js",
|
||||
"smoke-approval-policies": "ts-node --transpile-only src/scripts/smokeApprovalPolicies.ts",
|
||||
"smoke-approval-policies:prod": "node dist/scripts/smokeApprovalPolicies.js",
|
||||
"verify-smtp": "ts-node --transpile-only src/scripts/verifySmtp.ts",
|
||||
"verify-smtp:prod": "node dist/scripts/verifySmtp.js",
|
||||
"rotate-encryption-key": "ts-node --transpile-only src/scripts/rotateEncryptionKey.ts",
|
||||
|
||||
256
backend/src/scripts/smokeApprovalPolicies.ts
Normal file
256
backend/src/scripts/smokeApprovalPolicies.ts
Normal file
@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Smoke check for the approval-policy engine — no on-chain transfers.
|
||||
*
|
||||
* Verifies:
|
||||
* - approval_* / fund_operation_votes tables exist
|
||||
* - default policies can be seeded / listed
|
||||
* - evaluate() returns a decision for key operation types
|
||||
* - N-of-M helpers behave on a synthetic quorum
|
||||
*
|
||||
* Does NOT create fund requests, approve, or broadcast transactions.
|
||||
*
|
||||
* Local:
|
||||
* npx ts-node --transpile-only src/scripts/smokeApprovalPolicies.ts
|
||||
*
|
||||
* VPS:
|
||||
* sudo docker compose run --rm --no-deps --build backend \
|
||||
* node dist/scripts/smokeApprovalPolicies.js
|
||||
*/
|
||||
|
||||
import './loadEnv';
|
||||
import { query } from '../db/connection';
|
||||
import * as approvalPolicyRepository from '../repositories/approvalPolicyRepository';
|
||||
import {
|
||||
countQuorumProgress,
|
||||
evaluate,
|
||||
isQuorumComplete,
|
||||
policyMatches,
|
||||
} from '../services/approvalPolicyEngine';
|
||||
|
||||
type Check = { name: string; ok: boolean; detail?: string };
|
||||
|
||||
async function tableExists(name: string): Promise<boolean> {
|
||||
const rows = await query<{ exists: boolean }[]>(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM information_schema.tables
|
||||
WHERE table_schema = 'public' AND table_name = $1
|
||||
) AS exists`,
|
||||
[name]
|
||||
);
|
||||
return Boolean(rows[0]?.exists);
|
||||
}
|
||||
|
||||
async function columnExists(table: string, column: string): Promise<boolean> {
|
||||
const rows = await query<{ exists: boolean }[]>(
|
||||
`SELECT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = $1 AND column_name = $2
|
||||
) AS exists`,
|
||||
[table, column]
|
||||
);
|
||||
return Boolean(rows[0]?.exists);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const checks: Check[] = [];
|
||||
console.log('=== smokeApprovalPolicies (read-mostly, no on-chain) ===\n');
|
||||
|
||||
for (const table of [
|
||||
'approval_policies',
|
||||
'approval_policy_revisions',
|
||||
'fund_operation_votes',
|
||||
'fund_operation_requests',
|
||||
]) {
|
||||
const ok = await tableExists(table);
|
||||
checks.push({ name: `table ${table}`, ok, detail: ok ? 'present' : 'MISSING — run migrations' });
|
||||
}
|
||||
|
||||
const schemaOk = checks.every((c) => c.ok);
|
||||
if (!schemaOk) {
|
||||
console.log('Results (schema incomplete — skipping seed/evaluate):');
|
||||
for (const c of checks) {
|
||||
console.log(` [${c.ok ? 'OK ' : 'FAIL'}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
|
||||
}
|
||||
console.error('\nSmoke FAILED: run DB migrations first, then re-run this script.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
for (const col of [
|
||||
'policy_id',
|
||||
'policy_snapshot',
|
||||
'required_quorum',
|
||||
'amount_raw',
|
||||
'network',
|
||||
'from_address',
|
||||
'to_address',
|
||||
]) {
|
||||
const ok = await columnExists('fund_operation_requests', col);
|
||||
checks.push({
|
||||
name: `fund_operation_requests.${col}`,
|
||||
ok,
|
||||
detail: ok ? 'present' : 'MISSING — run migrations',
|
||||
});
|
||||
}
|
||||
|
||||
if (checks.some((c) => !c.ok)) {
|
||||
console.log('Results (columns incomplete — skipping seed/evaluate):');
|
||||
for (const c of checks) {
|
||||
console.log(` [${c.ok ? 'OK ' : 'FAIL'}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
|
||||
}
|
||||
console.error('\nSmoke FAILED: run DB migrations first, then re-run this script.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// May insert default seed if empty (safe, no chain)
|
||||
await approvalPolicyRepository.ensureDefaultPoliciesSeeded();
|
||||
const policies = await approvalPolicyRepository.listAllPolicies();
|
||||
checks.push({
|
||||
name: 'default policies seeded',
|
||||
ok: policies.length > 0,
|
||||
detail: `${policies.length} policy(ies)`,
|
||||
});
|
||||
|
||||
const hasPolicyChange = policies.some((p) => p.operation_type === 'approval_policy_change');
|
||||
const hasCatchAll = policies.some((p) => p.operation_type == null && p.enabled);
|
||||
checks.push({
|
||||
name: 'seed includes approval_policy_change rule',
|
||||
ok: hasPolicyChange,
|
||||
});
|
||||
checks.push({
|
||||
name: 'seed includes catch-all / wildcard rule',
|
||||
ok: hasCatchAll,
|
||||
});
|
||||
|
||||
const sampleOps = [
|
||||
'treasury_hot_to_cold',
|
||||
'treasury_cold_to_hot',
|
||||
'treasury_hot_to_cold_gas',
|
||||
'sweep_batch',
|
||||
'user_withdrawal',
|
||||
'approval_policy_change',
|
||||
'ledger_credit',
|
||||
] as const;
|
||||
|
||||
for (const op of sampleOps) {
|
||||
const result = await evaluate({
|
||||
operationType: op,
|
||||
amountRaw: op === 'user_withdrawal' ? '50000000' : '1000000',
|
||||
network: 'BSC',
|
||||
sourceKind: op.includes('hot_to_cold') ? 'hot' : op.includes('cold_to_hot') ? 'cold' : 'any',
|
||||
destKind: op.includes('hot_to_cold') ? 'cold' : op.includes('cold_to_hot') ? 'hot' : 'any',
|
||||
});
|
||||
const ok =
|
||||
result.decision.mode === 'require_approvals' || result.decision.mode === 'auto_execute';
|
||||
checks.push({
|
||||
name: `evaluate(${op})`,
|
||||
ok,
|
||||
detail: `${result.matchedBy} → ${result.decision.mode} quorum=${JSON.stringify(result.decision.quorum)} forbid_self=${result.decision.forbid_self_approve !== false}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Pure N-of-M sanity (no DB)
|
||||
const quorum = [
|
||||
{ role: 'admin', count: 1 },
|
||||
{ role: 'super_admin', count: 1 },
|
||||
];
|
||||
const incomplete = isQuorumComplete(quorum, [
|
||||
{
|
||||
id: '1',
|
||||
request_id: 'r',
|
||||
voter_id: 'a',
|
||||
decision: 'approve',
|
||||
reason: null,
|
||||
voter_roles: ['admin'],
|
||||
created_at: new Date(),
|
||||
},
|
||||
]);
|
||||
const complete = isQuorumComplete(quorum, [
|
||||
{
|
||||
id: '1',
|
||||
request_id: 'r',
|
||||
voter_id: 'a',
|
||||
decision: 'approve',
|
||||
reason: null,
|
||||
voter_roles: ['admin'],
|
||||
created_at: new Date(),
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
request_id: 'r',
|
||||
voter_id: 's',
|
||||
decision: 'approve',
|
||||
reason: null,
|
||||
voter_roles: ['super_admin'],
|
||||
created_at: new Date(),
|
||||
},
|
||||
]);
|
||||
const progress = countQuorumProgress(quorum, [
|
||||
{
|
||||
id: '1',
|
||||
request_id: 'r',
|
||||
voter_id: 'a',
|
||||
decision: 'approve',
|
||||
reason: null,
|
||||
voter_roles: ['admin'],
|
||||
created_at: new Date(),
|
||||
},
|
||||
]);
|
||||
checks.push({
|
||||
name: 'N-of-M incomplete until both slots filled',
|
||||
ok: incomplete === false && complete === true && progress.approved === 1,
|
||||
detail: `progress ${progress.approved}/${progress.required}`,
|
||||
});
|
||||
|
||||
// Priority: more specific policy wins when evaluating first match — verify match ordering logic
|
||||
const specific = {
|
||||
id: 's',
|
||||
name: 'specific',
|
||||
enabled: true,
|
||||
priority: 10,
|
||||
operation_type: 'treasury_hot_to_cold',
|
||||
wallet_type_id: null,
|
||||
network: null,
|
||||
amount_min_raw: null,
|
||||
amount_max_raw: null,
|
||||
source_wallet_kind: 'any' as const,
|
||||
dest_wallet_kind: 'any' as const,
|
||||
decision: {
|
||||
mode: 'auto_execute' as const,
|
||||
quorum: [],
|
||||
forbid_self_approve: true,
|
||||
},
|
||||
version: 1,
|
||||
updated_by: null,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
};
|
||||
checks.push({
|
||||
name: 'policyMatches specific hot→cold',
|
||||
ok: policyMatches(specific, { operationType: 'treasury_hot_to_cold' }),
|
||||
});
|
||||
checks.push({
|
||||
name: 'policyMatches specific rejects other ops',
|
||||
ok: !policyMatches(specific, { operationType: 'ledger_credit' }),
|
||||
});
|
||||
|
||||
console.log('Results:');
|
||||
let failed = 0;
|
||||
for (const c of checks) {
|
||||
const mark = c.ok ? 'OK ' : 'FAIL';
|
||||
if (!c.ok) failed += 1;
|
||||
console.log(` [${mark}] ${c.name}${c.detail ? ` — ${c.detail}` : ''}`);
|
||||
}
|
||||
|
||||
console.log(`\n${checks.length - failed}/${checks.length} checks passed.`);
|
||||
if (failed > 0) {
|
||||
console.error('\nSmoke FAILED. Fix migrations / seed before relying on Approvals in prod.');
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('\nSmoke OK. No on-chain transactions were sent.');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('Smoke crashed:', e instanceof Error ? e.message : e);
|
||||
process.exit(1);
|
||||
});
|
||||
@ -146,9 +146,10 @@ export function countQuorumProgress(
|
||||
approveVotes: FundOperationVoteRow[]
|
||||
): { required: number; approved: number; slots: Array<{ slot: QuorumSlot; filled: number; needed: number }> } {
|
||||
const used = new Set<string>();
|
||||
const onlyApproves = approveVotes.filter((v) => v.decision === 'approve');
|
||||
const slots = quorum.map((slot) => {
|
||||
let filled = 0;
|
||||
for (const vote of approveVotes) {
|
||||
for (const vote of onlyApproves) {
|
||||
if (used.has(vote.voter_id)) continue;
|
||||
const matchesRole = slot.role ? vote.voter_roles.includes(slot.role) : false;
|
||||
const matchesPerm =
|
||||
@ -204,5 +205,5 @@ export function annotateVoterRolesForQuorum(
|
||||
out.push(`perm:${slot.permission}`);
|
||||
}
|
||||
}
|
||||
return [...new Set(out)];
|
||||
return Array.from(new Set(out));
|
||||
}
|
||||
|
||||
204
backend/src/tests/approvalPolicyEngine.test.ts
Normal file
204
backend/src/tests/approvalPolicyEngine.test.ts
Normal file
@ -0,0 +1,204 @@
|
||||
/**
|
||||
* Unit tests for the approval policy engine (pure matching + N-of-M quorum).
|
||||
* No DB and no on-chain calls.
|
||||
*/
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
annotateVoterRolesForQuorum,
|
||||
countQuorumProgress,
|
||||
isQuorumComplete,
|
||||
policyMatches,
|
||||
voterFillsOpenSlot,
|
||||
} from '../services/approvalPolicyEngine';
|
||||
import type { ApprovalPolicyRow } from '../repositories/approvalPolicyRepository';
|
||||
import type { FundOperationVoteRow } from '../repositories/fundOperationVoteRepository';
|
||||
|
||||
function policy(partial: Partial<ApprovalPolicyRow>): ApprovalPolicyRow {
|
||||
return {
|
||||
id: 'p1',
|
||||
name: 'test',
|
||||
enabled: true,
|
||||
priority: 100,
|
||||
operation_type: null,
|
||||
wallet_type_id: null,
|
||||
network: null,
|
||||
amount_min_raw: null,
|
||||
amount_max_raw: null,
|
||||
source_wallet_kind: 'any',
|
||||
dest_wallet_kind: 'any',
|
||||
decision: {
|
||||
mode: 'require_approvals',
|
||||
quorum: [{ role: 'super_admin', count: 1 }],
|
||||
forbid_self_approve: true,
|
||||
},
|
||||
version: 1,
|
||||
updated_by: null,
|
||||
created_at: new Date(),
|
||||
updated_at: new Date(),
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
function vote(
|
||||
voterId: string,
|
||||
roles: string[],
|
||||
decision: 'approve' | 'reject' = 'approve'
|
||||
): FundOperationVoteRow {
|
||||
return {
|
||||
id: `v-${voterId}`,
|
||||
request_id: 'r1',
|
||||
voter_id: voterId,
|
||||
decision,
|
||||
reason: null,
|
||||
voter_roles: roles,
|
||||
created_at: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('policyMatches', () => {
|
||||
test('wildcard policy matches any operation', () => {
|
||||
assert.equal(
|
||||
policyMatches(policy({}), {
|
||||
operationType: 'treasury_hot_to_cold',
|
||||
amountRaw: '1000',
|
||||
}),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('disabled policy never matches', () => {
|
||||
assert.equal(
|
||||
policyMatches(policy({ enabled: false }), { operationType: 'ledger_credit' }),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('operation_type filter', () => {
|
||||
const p = policy({ operation_type: 'user_withdrawal' });
|
||||
assert.equal(policyMatches(p, { operationType: 'user_withdrawal' }), true);
|
||||
assert.equal(policyMatches(p, { operationType: 'ledger_credit' }), false);
|
||||
});
|
||||
|
||||
test('network and wallet_type_id filters', () => {
|
||||
const p = policy({ network: 'BSC', wallet_type_id: 2 });
|
||||
assert.equal(
|
||||
policyMatches(p, { operationType: 'x', network: 'BSC', walletTypeId: 2 }),
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
policyMatches(p, { operationType: 'x', network: 'TRON', walletTypeId: 2 }),
|
||||
false
|
||||
);
|
||||
assert.equal(
|
||||
policyMatches(p, { operationType: 'x', network: 'BSC', walletTypeId: 3 }),
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('amount min/max bounds (inclusive)', () => {
|
||||
const p = policy({ amount_min_raw: '100', amount_max_raw: '1000' });
|
||||
assert.equal(policyMatches(p, { operationType: 'x', amountRaw: '100' }), true);
|
||||
assert.equal(policyMatches(p, { operationType: 'x', amountRaw: '1000' }), true);
|
||||
assert.equal(policyMatches(p, { operationType: 'x', amountRaw: '99' }), false);
|
||||
assert.equal(policyMatches(p, { operationType: 'x', amountRaw: '1001' }), false);
|
||||
});
|
||||
|
||||
test('policy with amount bounds rejects missing amount', () => {
|
||||
const p = policy({ amount_min_raw: '1' });
|
||||
assert.equal(policyMatches(p, { operationType: 'x' }), false);
|
||||
assert.equal(policyMatches(p, { operationType: 'x', amountRaw: '' }), false);
|
||||
});
|
||||
|
||||
test('source/dest wallet kinds', () => {
|
||||
const p = policy({ source_wallet_kind: 'hot', dest_wallet_kind: 'cold' });
|
||||
assert.equal(
|
||||
policyMatches(p, {
|
||||
operationType: 'treasury_hot_to_cold',
|
||||
sourceKind: 'hot',
|
||||
destKind: 'cold',
|
||||
}),
|
||||
true
|
||||
);
|
||||
assert.equal(
|
||||
policyMatches(p, {
|
||||
operationType: 'treasury_cold_to_hot',
|
||||
sourceKind: 'cold',
|
||||
destKind: 'hot',
|
||||
}),
|
||||
false
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('N-of-M quorum', () => {
|
||||
test('single super_admin slot: 0/1 then 1/1', () => {
|
||||
const quorum = [{ role: 'super_admin', count: 1 }];
|
||||
assert.equal(isQuorumComplete(quorum, []), false);
|
||||
const progress0 = countQuorumProgress(quorum, []);
|
||||
assert.equal(progress0.required, 1);
|
||||
assert.equal(progress0.approved, 0);
|
||||
|
||||
const votes = [vote('sa1', ['super_admin'])];
|
||||
assert.equal(isQuorumComplete(quorum, votes), true);
|
||||
const progress1 = countQuorumProgress(quorum, votes);
|
||||
assert.equal(progress1.approved, 1);
|
||||
});
|
||||
|
||||
test('dual approval: admin + super_admin', () => {
|
||||
const quorum = [
|
||||
{ role: 'admin', count: 1 },
|
||||
{ role: 'super_admin', count: 1 },
|
||||
];
|
||||
const onlyAdmin = [vote('a1', ['admin'])];
|
||||
assert.equal(isQuorumComplete(quorum, onlyAdmin), false);
|
||||
|
||||
const both = [vote('a1', ['admin']), vote('sa1', ['super_admin'])];
|
||||
assert.equal(isQuorumComplete(quorum, both), true);
|
||||
});
|
||||
|
||||
test('same voter cannot fill two slots', () => {
|
||||
const quorum = [
|
||||
{ role: 'admin', count: 1 },
|
||||
{ role: 'super_admin', count: 1 },
|
||||
];
|
||||
// One person with both roles — still only one vote row, used once
|
||||
const dualRole = [vote('u1', ['admin', 'super_admin'])];
|
||||
assert.equal(isQuorumComplete(quorum, dualRole), false);
|
||||
});
|
||||
|
||||
test('N=2 of same role', () => {
|
||||
const quorum = [{ role: 'admin', count: 2 }];
|
||||
assert.equal(isQuorumComplete(quorum, [vote('a1', ['admin'])]), false);
|
||||
assert.equal(
|
||||
isQuorumComplete(quorum, [vote('a1', ['admin']), vote('a2', ['admin'])]),
|
||||
true
|
||||
);
|
||||
});
|
||||
|
||||
test('permission-annotated votes fill permission slots', () => {
|
||||
const quorum = [{ permission: 'fund_operation.approve', count: 1 }];
|
||||
const annotated = annotateVoterRolesForQuorum(
|
||||
['admin'],
|
||||
['fund_operation.approve'],
|
||||
quorum
|
||||
);
|
||||
assert.ok(annotated.includes('perm:fund_operation.approve'));
|
||||
assert.equal(isQuorumComplete(quorum, [vote('u1', annotated)]), true);
|
||||
});
|
||||
|
||||
test('voterFillsOpenSlot respects already-filled slots', () => {
|
||||
const quorum = [
|
||||
{ role: 'admin', count: 1 },
|
||||
{ role: 'super_admin', count: 1 },
|
||||
];
|
||||
const votes = [vote('a1', ['admin'])];
|
||||
assert.equal(voterFillsOpenSlot(quorum, votes, ['admin'], []), false);
|
||||
assert.equal(voterFillsOpenSlot(quorum, votes, ['super_admin'], []), true);
|
||||
});
|
||||
|
||||
test('reject votes do not count toward quorum', () => {
|
||||
const quorum = [{ role: 'super_admin', count: 1 }];
|
||||
assert.equal(isQuorumComplete(quorum, [vote('sa1', ['super_admin'], 'reject')]), false);
|
||||
});
|
||||
});
|
||||
@ -952,6 +952,7 @@ Local Docker : `npm run docker:local:break-glass-reset-2fa -- …` (fichier `.en
|
||||
| Remise à zéro DB | [§4.1](#41-remise-à-zéro--supprimer-et-recréer-la-base-avant-tests-réels) |
|
||||
| Seed hot wallets (TRON + BSC) | `docker compose run --rm --no-deps backend node dist/scripts/seedHotWallets.js` |
|
||||
| Vérifier adresses HD | `npm run phase-b:verify-deposit-addresses` |
|
||||
| Smoke règles d’approbation (sans on-chain) | `sudo docker compose run --rm --no-deps backend node dist/scripts/smokeApprovalPolicies.js` |
|
||||
| Reconstruire après changement `VITE_*` | `npm run phase-b:up` (HTTP) ou `phase-b:up:https` |
|
||||
|
||||
Logs d’un service précis :
|
||||
|
||||
Loading…
Reference in New Issue
Block a user