After adding the fonctionnality to monitor the withdrawals
This commit is contained in:
parent
ebf64f40d7
commit
697b9e7675
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;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"}
|
||||
{"version":3,"file":"appBootstrap.d.ts","sourceRoot":"","sources":["../../src/bootstrap/appBootstrap.ts"],"names":[],"mappings":"AAAA;;GAEG;AA8JH,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,CAkD9E"}
|
||||
51
backend/dist/bootstrap/appBootstrap.js
vendored
51
backend/dist/bootstrap/appBootstrap.js
vendored
@ -2,6 +2,39 @@
|
||||
/**
|
||||
* Shared application bootstrap (migrations, background jobs, game registration).
|
||||
*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.bootstrapCore = bootstrapCore;
|
||||
const config_1 = require("../config");
|
||||
@ -24,6 +57,23 @@ const networkGuard_1 = require("../safety/networkGuard");
|
||||
const productionSecretsGuard_1 = require("../safety/productionSecretsGuard");
|
||||
const client_1 = require("../realtime/redis/client");
|
||||
const DEPOSIT_POLL_INTERVAL_MS = 60 * 1000;
|
||||
const WITHDRAWAL_MONITOR_INTERVAL_MS = 20 * 1000;
|
||||
/** Confirms broadcast payouts on-chain (completed only after required confirmations). */
|
||||
function startWithdrawalMonitor() {
|
||||
const run = async () => {
|
||||
try {
|
||||
const { runWithdrawalMonitorCycle } = await Promise.resolve().then(() => __importStar(require('../services/withdrawalService')));
|
||||
const r = await runWithdrawalMonitorCycle();
|
||||
if (r.completed > 0)
|
||||
console.log(`[withdrawal] ${r.completed} payout(s) confirmed`);
|
||||
}
|
||||
catch (e) {
|
||||
console.error('Withdrawal monitor error:', e);
|
||||
}
|
||||
setTimeout(run, WITHDRAWAL_MONITOR_INTERVAL_MS);
|
||||
};
|
||||
setTimeout(run, 20 * 1000);
|
||||
}
|
||||
async function startDepositMonitor() {
|
||||
const run = async () => {
|
||||
try {
|
||||
@ -162,6 +212,7 @@ async function bootstrapCore(opts = {}) {
|
||||
(0, adminUserExportService_1.startAdminExportWorker)();
|
||||
(0, analyticsMaterializedViews_1.scheduleAnalyticsMaterializedViewRefresh)();
|
||||
startDepositMonitor();
|
||||
startWithdrawalMonitor();
|
||||
startLedgerIntegrityMonitor();
|
||||
startFileIntegrityMonitor();
|
||||
startDbTamperMonitor();
|
||||
|
||||
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
@ -1,13 +1,20 @@
|
||||
/**
|
||||
* Withdrawal controller — HTTP handler for submitting on-chain withdrawal requests.
|
||||
* Withdrawal controllers — user submission / cancellation and the admin withdrawal queue.
|
||||
*/
|
||||
import { Response } from 'express';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
/**
|
||||
* Submits a withdrawal request to send funds from the user's wallet to an external address.
|
||||
* May require a TOTP code when 2FA is enabled for the user.
|
||||
* @param req - Authenticated request. Body: `walletType`, `toAddress`, `amount`, optional `totpCode`.
|
||||
* @param res - JSON `{ transactionId, status }` on success, 400 on validation or withdrawal failure.
|
||||
* Records a withdrawal request (status `pending`, amount + fee reserved).
|
||||
* Body: `walletType`, `toAddress`, `amount`, optional `totpCode`, optional `idempotencyKey`
|
||||
* (also accepted as the `Idempotency-Key` header).
|
||||
*/
|
||||
export declare function withdraw(req: AuthRequest, res: Response): Promise<void>;
|
||||
/** User cancels their own withdrawal while it is still pending (refund to available balance). */
|
||||
export declare function cancelOwnWithdrawal(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function adminListWithdrawals(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function adminGetWithdrawal(req: AuthRequest, res: Response): Promise<void>;
|
||||
/** Starts (or retries) the payout. Returns the resulting status (processing / pending / failed). */
|
||||
export declare function adminProcessWithdrawal(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function adminRequeueWithdrawal(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function adminRejectWithdrawal(req: AuthRequest, res: Response): Promise<void>;
|
||||
//# sourceMappingURL=withdrawalController.d.ts.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"withdrawalController.d.ts","sourceRoot":"","sources":["../../src/controllers/withdrawalController.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD;;;;;GAKG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgB7E"}
|
||||
{"version":3,"file":"withdrawalController.d.ts","sourceRoot":"","sources":["../../src/controllers/withdrawalController.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAGnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEjD;;;;GAIG;AACH,wBAAsB,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAkB7E;AAED,iGAAiG;AACjG,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAKxF;AAED,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAczF;AAED,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAOvF;AAED,oGAAoG;AACpG,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAM3F;AAED,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAG3F;AAED,wBAAsB,qBAAqB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1F"}
|
||||
68
backend/dist/controllers/withdrawalController.js
vendored
68
backend/dist/controllers/withdrawalController.js
vendored
@ -1,6 +1,6 @@
|
||||
"use strict";
|
||||
/**
|
||||
* Withdrawal controller — HTTP handler for submitting on-chain withdrawal requests.
|
||||
* Withdrawal controllers — user submission / cancellation and the admin withdrawal queue.
|
||||
*/
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
@ -37,12 +37,18 @@ var __importStar = (this && this.__importStar) || (function () {
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.withdraw = withdraw;
|
||||
exports.cancelOwnWithdrawal = cancelOwnWithdrawal;
|
||||
exports.adminListWithdrawals = adminListWithdrawals;
|
||||
exports.adminGetWithdrawal = adminGetWithdrawal;
|
||||
exports.adminProcessWithdrawal = adminProcessWithdrawal;
|
||||
exports.adminRequeueWithdrawal = adminRequeueWithdrawal;
|
||||
exports.adminRejectWithdrawal = adminRejectWithdrawal;
|
||||
const withdrawalService = __importStar(require("../services/withdrawalService"));
|
||||
const withdrawalAdminService = __importStar(require("../services/withdrawals/withdrawalAdminService"));
|
||||
/**
|
||||
* Submits a withdrawal request to send funds from the user's wallet to an external address.
|
||||
* May require a TOTP code when 2FA is enabled for the user.
|
||||
* @param req - Authenticated request. Body: `walletType`, `toAddress`, `amount`, optional `totpCode`.
|
||||
* @param res - JSON `{ transactionId, status }` on success, 400 on validation or withdrawal failure.
|
||||
* Records a withdrawal request (status `pending`, amount + fee reserved).
|
||||
* Body: `walletType`, `toAddress`, `amount`, optional `totpCode`, optional `idempotencyKey`
|
||||
* (also accepted as the `Idempotency-Key` header).
|
||||
*/
|
||||
async function withdraw(req, res) {
|
||||
const userId = req.user.userId;
|
||||
@ -51,8 +57,58 @@ async function withdraw(req, res) {
|
||||
res.status(400).json({ error: 'walletType, toAddress and amount required' });
|
||||
return;
|
||||
}
|
||||
const headerKey = req.header('Idempotency-Key')?.trim();
|
||||
const amountRaw = BigInt(amount);
|
||||
const result = await withdrawalService.requestWithdrawal(userId, walletType, toAddress, amountRaw, req.body.totpCode);
|
||||
const result = await withdrawalService.requestWithdrawal(userId, walletType, toAddress, amountRaw, req.body.totpCode, { idempotencyKey: req.body.idempotencyKey ?? headerKey ?? null });
|
||||
res.json(result);
|
||||
}
|
||||
/** User cancels their own withdrawal while it is still pending (refund to available balance). */
|
||||
async function cancelOwnWithdrawal(req, res) {
|
||||
const row = await withdrawalService.cancelWithdrawal(String(req.params.id), {
|
||||
userId: req.user.userId,
|
||||
});
|
||||
res.json({ transactionId: row.id, status: row.status });
|
||||
}
|
||||
async function adminListWithdrawals(req, res) {
|
||||
const q = req.query;
|
||||
const result = await withdrawalAdminService.listWithdrawals({
|
||||
status: q.status,
|
||||
network: q.network,
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
minAmount: q.minAmount,
|
||||
maxAmount: q.maxAmount,
|
||||
search: q.search,
|
||||
limit: q.limit ? Number(q.limit) : undefined,
|
||||
offset: q.offset ? Number(q.offset) : undefined,
|
||||
});
|
||||
res.json(result);
|
||||
}
|
||||
async function adminGetWithdrawal(req, res) {
|
||||
const detail = await withdrawalAdminService.getWithdrawalDetail(String(req.params.id));
|
||||
if (!detail) {
|
||||
res.status(404).json({ error: 'Withdrawal not found', code: 'WITHDRAWAL_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
res.json(detail);
|
||||
}
|
||||
/** Starts (or retries) the payout. Returns the resulting status (processing / pending / failed). */
|
||||
async function adminProcessWithdrawal(req, res) {
|
||||
const result = await withdrawalService.processWithdrawal(String(req.params.id), {
|
||||
actorType: 'admin',
|
||||
actorUserId: req.user.userId,
|
||||
});
|
||||
res.json(result);
|
||||
}
|
||||
async function adminRequeueWithdrawal(req, res) {
|
||||
const row = await withdrawalService.requeueWithdrawal(String(req.params.id), req.user.userId);
|
||||
res.json({ transactionId: row.id, status: row.status });
|
||||
}
|
||||
async function adminRejectWithdrawal(req, res) {
|
||||
const row = await withdrawalService.rejectWithdrawal(String(req.params.id), {
|
||||
actorId: req.user.userId,
|
||||
reason: String(req.body.reason ?? ''),
|
||||
});
|
||||
res.json({ transactionId: row.id, status: row.status });
|
||||
}
|
||||
//# sourceMappingURL=withdrawalController.js.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"withdrawalController.js","sourceRoot":"","sources":["../../src/controllers/withdrawalController.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYH,4BAgBC;AAzBD,iFAAmE;AAGnE;;;;;GAKG;AACI,KAAK,UAAU,QAAQ,CAAC,GAAgB,EAAE,GAAa;IAC5D,MAAM,MAAM,GAAG,GAAG,CAAC,IAAK,CAAC,MAAM,CAAC;IAChC,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC;IACnD,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;QAChD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,2CAA2C,EAAE,CAAC,CAAC;QAC7E,OAAO;IACT,CAAC;IACD,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,MAAM,MAAM,GAAG,MAAM,iBAAiB,CAAC,iBAAiB,CACtD,MAAM,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,GAAG,CAAC,IAAI,CAAC,QAAQ,CAClB,CAAC;IACF,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACnB,CAAC"}
|
||||
{"version":3,"file":"withdrawalController.js","sourceRoot":"","sources":["../../src/controllers/withdrawalController.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYH,4BAkBC;AAGD,kDAKC;AAED,oDAcC;AAED,gDAOC;AAGD,wDAMC;AAED,wDAGC;AAED,sDAMC;AAlFD,iFAAmE;AACnE,uGAAyF;AAGzF;;;;GAIG;AACI,KAAK,UAAU,QAAQ,CAAC,GAAgB,EAAE,GAAa;IAC5D,MAAM,MAAM,GAAG,GAAG,CAAC,IAAK,CAAC,MAAM,CAAC;IAChC,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,GAAG,CAAC,IAAI,CAAC;IACnD,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;QAChD,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,2CAA2C,EAAE,CAAC,CAAC;QAC7E,OAAO;IACT,CAAC;IACD,MAAM,SAAS,GAAG,GAAG,CAAC,MAAM,CAAC,iBAAiB,CAAC,EAAE,IAAI,EAAE,CAAC;IACxD,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,MAAM,MAAM,GAAG,MAAM,iBAAiB,CAAC,iBAAiB,CACtD,MAAM,EACN,UAAU,EACV,SAAS,EACT,SAAS,EACT,GAAG,CAAC,IAAI,CAAC,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,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE;QAC1E,OAAO,EAAE,GAAG,CAAC,IAAK,CAAC,MAAM;QACzB,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,IAAI,EAAE,CAAC;KACtC,CAAC,CAAC;IACH,GAAG,CAAC,IAAI,CAAC,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;AAC1D,CAAC"}
|
||||
7
backend/dist/models/settings.model.d.ts
vendored
7
backend/dist/models/settings.model.d.ts
vendored
@ -45,6 +45,13 @@ export interface SystemSettings {
|
||||
candle_predict_retention_keep_last: number;
|
||||
/** Network fee deducted from user USDT balance per withdrawal (6-decimal micro units). */
|
||||
withdrawal_network_fee_usdt_micro: number;
|
||||
/**
|
||||
* When true, withdrawals pending for hot-wallet USDT / gas / missing hot wallet are retried
|
||||
* automatically once the hot wallet can pay them.
|
||||
*/
|
||||
withdrawal_auto_retry_enabled: boolean;
|
||||
/** Minutes between automatic retry passes (1–1440). */
|
||||
withdrawal_auto_retry_interval_minutes: number;
|
||||
/**
|
||||
* Minimum USDT that must remain on the sender's main balance after a peer transfer
|
||||
* (6-decimal micro units). `0` disables the limit.
|
||||
|
||||
2
backend/dist/models/settings.model.d.ts.map
vendored
2
backend/dist/models/settings.model.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"settings.model.d.ts","sourceRoot":"","sources":["../../src/models/settings.model.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,8FAA8F;AAC9F,MAAM,WAAW,cAAc;IAC7B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,0BAA0B,EAAE,OAAO,CAAC;IACpC,0BAA0B,EAAE,OAAO,CAAC;IACpC,uBAAuB,EAAE,OAAO,CAAC;IACjC,wBAAwB,EAAE,OAAO,CAAC;IAClC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,o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IAC1F,iCAAiC,EAAE,MAAM,CAAC;IAC1C;;;OAGG;IACH,6BAA6B,EAAE,OAAO,CAAC;IACvC,uDAAuD;IACvD,sCAAsC,EAAE,MAAM,CAAC;IAC/C;;;OAGG;IACH,iCAAiC,EAAE,MAAM,CAAC;IAC1C,sEAAsE;IACtE,iBAAiB,EAAE,OAAO,CAAC;IAC3B,uFAAuF;IACvF,sBAAsB,EAAE,OAAO,CAAC;IAChC,kEAAkE;IAClE,uBAAuB,EAAE,MAAM,CAAC;IAChC,6DAA6D;IAC7D,yBAAyB,EAAE,MAAM,CAAC;IAClC,6DAA6D;IAC7D,qBAAqB,EAAE,MAAM,CAAC;IAC9B,yGAAyG;IACzG,4BAA4B,EAAE,MAAM,CAAC;IACrC,2EAA2E;IAC3E,2BAA2B,EAAE,OAAO,CAAC;IACrC,yEAAyE;IACzE,gCAAgC,EAAE,OAAO,CAAC;IAC1C,6EAA6E;IAC7E,iCAAiC,EAAE,MAAM,CAAC;IAC1C,4FAA4F;IAC5F,mCAAmC,EAAE,MAAM,CAAC;IAC5C,8FAA8F;IAC9F,qCAAqC,EAAE,MAAM,CAAC;CAC/C"}
|
||||
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' | 'pending_approval' | 'broadcasting' | 'confirming' | 'completed' | 'failed' | 'ledger_finalize_failed';
|
||||
status: 'pending' | 'processing' | 'completed' | 'failed' | 'rejected' | 'cancelled' | 'failed_refunded' | 'pending_approval' | 'broadcasting' | 'confirming' | '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;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M,GAAG,IAAI,CAAC;IAChC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,sBAAsB,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACzC,UAAU,EAAE,IAAI,CAAC;IACjB,UAAU,EAAE,IAAI,CAAC;CAClB"}
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"settingsRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/settingsRepository.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAmN3C,gEAAgE;AAEhE,wBAAgB,uBAAuB,IAAI,IAAI,CAI9C;AAID;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CA4B3D;AAsFD;;;;;;;;;;GAUG;AAEH,wBAAsB,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBpF"}
|
||||
{"version":3,"file":"settingsRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/settingsRepository.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AA2N3C,gEAAgE;AAEhE,wBAAgB,uBAAuB,IAAI,IAAI,CAI9C;AAID;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CA4B3D;AA0FD;;;;;;;;;;GAUG;AAEH,wBAAsB,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBpF"}
|
||||
@ -42,6 +42,8 @@ function buildDefaults() {
|
||||
candle_predict_retention_days: 30,
|
||||
candle_predict_retention_keep_last: 5000,
|
||||
withdrawal_network_fee_usdt_micro: config_1.config.withdrawal.networkFeeUsdtMicro,
|
||||
withdrawal_auto_retry_enabled: false,
|
||||
withdrawal_auto_retry_interval_minutes: 10,
|
||||
transfer_min_remaining_usdt_micro: 0,
|
||||
require_admin_2fa: true,
|
||||
require_withdrawal_2fa: true,
|
||||
@ -71,6 +73,7 @@ const BOOLEAN_KEYS = new Set([
|
||||
'require_withdrawal_2fa',
|
||||
'sybil_auto_suspend_accounts',
|
||||
'login_risk_auto_suspend_accounts',
|
||||
'withdrawal_auto_retry_enabled',
|
||||
]);
|
||||
const INTEGER_KEYS = new Set([
|
||||
'password_min_length',
|
||||
@ -87,6 +90,7 @@ const INTEGER_KEYS = new Set([
|
||||
'candle_predict_retention_days',
|
||||
'candle_predict_retention_keep_last',
|
||||
'withdrawal_network_fee_usdt_micro',
|
||||
'withdrawal_auto_retry_interval_minutes',
|
||||
'transfer_min_remaining_usdt_micro',
|
||||
'login_max_failed_attempts',
|
||||
'login_lockout_minutes',
|
||||
@ -164,6 +168,8 @@ const UPDATABLE_KEYS = [
|
||||
'candle_predict_retention_days',
|
||||
'candle_predict_retention_keep_last',
|
||||
'withdrawal_network_fee_usdt_micro',
|
||||
'withdrawal_auto_retry_enabled',
|
||||
'withdrawal_auto_retry_interval_minutes',
|
||||
'transfer_min_remaining_usdt_micro',
|
||||
'require_admin_2fa',
|
||||
'login_max_failed_attempts',
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"settingsRepository.js","sourceRoot":"","sources":["../../src/repositories/settingsRepository.ts"],"names":[],"mappings":";;AAyNA,0DAIC;AAYD,kCA4BC;AAkGD,wCAwBC;AA/XD,iDAAyC;AAEzC,sCAAmC;AAMnC;;;;;;GAMG;AAIH,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,IAAI,aAAa,GAAgD,IAAI,CAAC;AAItE,SAAS,aAAa;IAEpB,OAAO;QAEL,mBAAmB,EAAE,CAAC;QAEtB,0BAA0B,E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AC,CAEX,CAAC;IAEJ,CAAC;IAED,uBAAuB,EAAE,CAAC;AAE5B,CAAC"}
|
||||
@ -82,8 +82,11 @@ export declare function listCompletedDepositsToAddress(toAddress: string): Promi
|
||||
* @returns Array of transaction records.
|
||||
*/
|
||||
export declare function listByUserId(userId: string, limit?: number, offset?: number, category?: TransactionActivityCategory): Promise<Transaction[]>;
|
||||
/** Withdrawal rows since a UTC timestamp (for daily limit checks). */
|
||||
export declare function listWithdrawalsSince(userId: string, since: Date): Promise<Array<{
|
||||
/**
|
||||
* Withdrawal rows since a UTC timestamp (for daily limit checks).
|
||||
* Excludes requests whose funds were returned; `failed` still holds a reservation and counts.
|
||||
*/
|
||||
export declare function listWithdrawalsSince(userId: string, since: Date, client?: PoolClient): Promise<Array<{
|
||||
amount: string;
|
||||
fee: string;
|
||||
code: string;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"transactionRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/transactionRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,6CAA6C;AAC7C,MAAM,MAAM,2BAA2B,GAAG,UAAU,GAAG,aAAa,GAAG,WAAW,GAAG,aAAa,CAAC;AAiBnG;;;GAGG;AAEH;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,MAAM,CAAC,IAAI,EAAE;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,YAAY,EAAE,MAAM,CAAC;IACrB,IAAI,EAAE,SAAS,GAAG,YAAY,GAAG,UAAU,GAAG,YAAY,GAAG,aAAa,GAAG,aAAa,GAAG,OAAO,GAAG,kBAAkB,CAAC;IAC1H,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,WA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AAW,EAAE,CAAC,CAS9F;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,MAAM,EACd,KAAK,GAAE,MAAW,EAClB,MAAM,GAAE,MAAU,EAClB,QAAQ,CAAC,EAAE,2BAA2B,GACrC,OAAO,CAAC,WAAW,EAAE,CAAC,CAOxB;AAED,sEAAsE;AACtE,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,IAAI,GACV,OAAO,CAAC,KAAK,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC,CAWjF;AAED,uDAAuD;AACvD,wBAAsB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,2BAA2B,GAAG,OAAO,CAAC,MAAM,CAAC,CAO3G;AAED,gGAAgG;AAChG,wBAAsB,uBAAuB,CAC3C,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,KAAK,GAAG,MAAM,GAAG,UAAU,GACrC,OAAO,CAAC,IAAI,CAAC,CASf;AAED;;;GAGG;AACH,wBAAsB,wBAAwB,CAAC,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAA;CAAE,EACjH,GAAG,EAAE,CAAC,EAAE,GACP,OAAO,CAAC,CAAC,EAAE,CAAC,CA6Bd"}
|
||||
{"version":3,"file":"transactionRepository.d.ts","sourceRoot":"","sources":["../../src/repositories/transactionRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,6CAA6C;AAC7C,MAAM,MAAM,2BAA2B,GAAG,UAAU,GAAG,aAAa,GAAG,WAA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AwB,CAAC,CAAC,SAAS;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAA;CAAE,EACjH,GAAG,EAAE,CAAC,EAAE,GACP,OAAO,CAAC,CAAC,EAAE,CAAC,CA6Bd"}
|
||||
@ -141,15 +141,27 @@ async function listByUserId(userId, limit = 50, offset = 0, category) {
|
||||
return (0, connection_1.query)(`SELECT id, user_id, wallet_type_id, type, amount::text, fee::text, status, blockchain_tx_id, from_address, to_address, confirmations, required_confirmations, metadata, created_at, updated_at
|
||||
FROM transactions WHERE user_id = $1${categorySql} ORDER BY created_at DESC LIMIT $2 OFFSET $3`, [userId, limit, offset]);
|
||||
}
|
||||
/** Withdrawal rows since a UTC timestamp (for daily limit checks). */
|
||||
async function listWithdrawalsSince(userId, since) {
|
||||
return (0, connection_1.query)(`SELECT t.amount::text, COALESCE(t.fee, 0)::text AS fee, wt.code, wt.decimals
|
||||
/**
|
||||
* Withdrawal rows since a UTC timestamp (for daily limit checks).
|
||||
* Excludes requests whose funds were returned; `failed` still holds a reservation and counts.
|
||||
*/
|
||||
async function listWithdrawalsSince(userId, since, client) {
|
||||
const sql = `SELECT t.amount::text, COALESCE(t.fee, 0)::text AS fee, wt.code, wt.decimals
|
||||
FROM transactions t
|
||||
INNER JOIN wallet_types wt ON wt.id = t.wallet_type_id
|
||||
WHERE t.user_id = $1
|
||||
AND t.type = 'withdrawal'
|
||||
AND t.status NOT IN ('failed', 'cancelled')
|
||||
AND t.created_at >= $2`, [userId, since]);
|
||||
AND t.status NOT IN ('rejected', 'cancelled', 'failed_refunded')
|
||||
AND NOT (t.status = 'failed' AND t.withdrawal_flow_version IS NULL)
|
||||
AND t.created_at >= $2`;
|
||||
if (client) {
|
||||
const res = await client.query(sql, [
|
||||
userId,
|
||||
since,
|
||||
]);
|
||||
return res.rows;
|
||||
}
|
||||
return (0, connection_1.query)(sql, [userId, since]);
|
||||
}
|
||||
/** Total transaction count for a user (pagination). */
|
||||
async function countByUserId(userId, category) {
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"transactionRepository.js","sourceRoot":"","sources":["../../src/repositories/transactionRepository.ts"],"names":[],"mappings":";;AA4CA,wBAkCC;AAMD,gDAsCC;AAUD,oCAUC;AAOD,oDAMC;AAOD,4BAMC;AAED,wEASC;AASD,oCAYC;AAGD,oDAcC;AAGD,sCAOC;AAGD,0DAYC;AAMD,4DA+BC;AAvRD,iDAAyC;AAOzC,SAAS,sBAAsB,CAAC,QAAsC;IACpE,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,UAAU;YACb,OAAO,uDAAuD,CAAC;QACjE,KAAK,aAAa;YAChB,OAAO,0BAA0B,CAAC;QACpC,KAAK,WAAW;YACd,OAAO,wBAAwB,CAAC;QAClC,KAAK,aAAa;YAChB,OAAO,2DAA2D,CAAC;QACrE;YACE,OAAO,EAAE,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;GAGG;AAEH;;;;;;;;;;;;;;;;GAgBG;AACI,KAAK,UAAU,MAAM,CAAC,IAa5B;IACC,MAAM,IAAI,GAAG,MAAM,IAAA,kBAAK,EACtB;;uMAEmM,EACnM;QACE,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,YAAY;QACjB,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QACtB,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,EAAE;QAC1B,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,cAAc,IAAI,IAAI;QAC3B,IAAI,CAAC,WAAW,IAAI,IAAI;QACxB,IAAI,CAAC,SAAS,IAAI,IAAI;QACtB,IAAI,CAAC,aAAa,IAAI,IAAI;QAC1B,IAAI,CAAC,qBAAqB,IAAI,IAAI;QAClC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ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E,GAAG,CAAC,EAAE,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE;SACzD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"}
|
||||
{"version":3,"file":"transactionRepository.js","sourceRoot":"","sources":["../../src/repositories/transactionRepository.ts"],"names":[],"mappings":";;AA4CA,wBAkCC;AAMD,gDAsCC;AAUD,oCAUC;AAOD,oDAMC;AAOD,4BAMC;AAED,wEASC;AASD,oCAYC;AAMD,oDAqBC;AAGD,sCAOC;AAGD,0DAYC;AAMD,4DA+BC;AAjSD,iDAAyC;AAOzC,SAAS,sBAAsB,CAAC,QAAsC;IACpE,QAAQ,QAAQ,EAAE,CAAC;QACjB,KAAK,UAAU;YACb,OAAO,uDAAuD,CAAC;QACjE,KAAK,aAAa;YAChB,OAAO,0BAA0B,CAAC;QACpC,KAAK,WAAW;YACd,OAAO,wBAAwB,CAAC;QAClC,KAAK,aAAa;YAChB,OAAO,2DAA2D,CAAC;QACrE;YACE,OAAO,EAAE,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;GAGG;AAEH;;;;;;;;;;;;;;;;GAgBG;AACI,KAAK,UAAU,MAAM,CAAC,IAa5B;IACC,MAAM,IAAI,GAAG,MAAM,IAAA,kBAAK,EACtB;;uMAEmM,EACnM;QACE,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,YAAY;QACjB,IAAI,CAAC,IAAI;QACT,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;QACtB,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,QAAQ,EAAE;QAC1B,IAAI,CAAC,MAAM;QACX,IAAI,CAAC,cAAc,IAAI,IAAI;QAC3B,IAAI,CAAC,WAAW,IAAI,IAAI;QACxB,IAAI,CAAC,SAAS,IAAI,IAAI;QACtB,IAAI,CAAC,aAAa,IAAI,IAAI;QAC1B,IAAI,CAAC,qBAAqB,IAAI,IAAI;QAClC,IAAI,CAAC,QAAQ,CAA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AC,CAAC,EAAE,CAAC;QACpE,IAAI,CAAC,KAAK;YAAE,OAAO,EAAE,CAAC;QACtB,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACrC,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,KAAK,MAAM,IAAI,MAAM,KAAK,UAAU;YAAE,OAAO,EAAE,CAAC;QAC9E,OAAO;YACL,GAAG,EAAE;YACL,QAAQ,EAAE,EAAE,GAAG,CAAC,EAAE,CAAC,QAAQ,IAAI,EAAE,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE;SACzD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"}
|
||||
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;AAwJH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAysBxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2JH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAwvBxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
6
backend/dist/routes/index.js
vendored
6
backend/dist/routes/index.js
vendored
@ -173,6 +173,7 @@ router.post('/2fa/enable', (0, validate_1.validateBody)(schemas_1.totpEnableBody
|
||||
router.post('/2fa/disable', (0, validate_1.validateBody)(schemas_1.totpDisableBodySchema), authController.disable2FA);
|
||||
router.post('/2fa/recovery/regenerate', authController.regenerateRecoveryCodes);
|
||||
router.post('/withdraw', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateBody)(schemas_1.withdrawBodySchema), (0, audit_1.auditAction)('withdrawal_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(withdrawalController.withdraw));
|
||||
router.post('/withdrawals/:id/cancel', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateParams)(querySchemas_1.uuidIdParamSchema), (0, audit_1.auditAction)('withdrawal_cancel_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(withdrawalController.cancelOwnWithdrawal));
|
||||
router.post('/transfer', requireSupportedAppVersion_1.requireSupportedAppVersion, (0, validate_1.validateBody)(schemas_1.transferBodySchema), (0, audit_1.auditAction)('transfer_requested', 'wallet'), (0, errorHandler_1.asyncHandler)(transferController.transfer));
|
||||
router.get('/games/candle-predict/state', candlePredictController.getState);
|
||||
router.get('/games/candle-predict/candles', candlePredictController.getCandles);
|
||||
@ -237,6 +238,11 @@ router.get('/admin/rbac/admin-users/:userId', (0, auth_1.requireRoles)('admin'),
|
||||
router.get('/admin/rbac/me', auth_1.authMiddleware, (0, errorHandler_1.asyncHandler)(rbacController.getMyPermissions));
|
||||
router.delete('/admin/users/:userId', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('users.admin'), (0, validate_1.validateBody)(adminSchemas_1.adminDeleteUserBodySchema), adminController.deleteUser);
|
||||
router.post('/admin/fund-requests', (0, auth_1.requirePermissions)('fund_operation.request'), (0, validate_1.validateBody)(adminSchemas_1.fundRequestCreateBodySchema), fundApprovalController.createFundRequest);
|
||||
router.get('/admin/withdrawals', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.withdrawals.view'), (0, validate_1.validateQuery)(schemas_1.adminWithdrawalsListQuerySchema), (0, errorHandler_1.asyncHandler)(withdrawalController.adminListWithdrawals));
|
||||
router.get('/admin/withdrawals/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.withdrawals.view'), (0, validate_1.validateParams)(querySchemas_1.uuidIdParamSchema), (0, errorHandler_1.asyncHandler)(withdrawalController.adminGetWithdrawal));
|
||||
router.post('/admin/withdrawals/:id/process', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.withdrawals.manage'), (0, validate_1.validateParams)(querySchemas_1.uuidIdParamSchema), (0, audit_1.auditAction)('admin_withdrawal_process', 'withdrawal'), (0, errorHandler_1.asyncHandler)(withdrawalController.adminProcessWithdrawal));
|
||||
router.post('/admin/withdrawals/:id/requeue', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.withdrawals.manage'), (0, validate_1.validateParams)(querySchemas_1.uuidIdParamSchema), (0, audit_1.auditAction)('admin_withdrawal_requeue', 'withdrawal'), (0, errorHandler_1.asyncHandler)(withdrawalController.adminRequeueWithdrawal));
|
||||
router.post('/admin/withdrawals/:id/reject', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('admin.withdrawals.manage'), (0, validate_1.validateParams)(querySchemas_1.uuidIdParamSchema), (0, validate_1.validateBody)(schemas_1.adminWithdrawalRejectBodySchema), (0, audit_1.auditAction)('admin_withdrawal_reject', 'withdrawal'), (0, errorHandler_1.asyncHandler)(withdrawalController.adminRejectWithdrawal));
|
||||
router.get('/admin/fund-requests', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.request'), fundApprovalController.listFundRequests);
|
||||
router.get('/admin/fund-requests/:id', (0, auth_1.requireRoles)('admin'), (0, auth_1.requirePermissions)('fund_operation.request'), fundApprovalController.getFundRequest);
|
||||
router.post('/admin/fund-requests/:id/approve', (0, auth_1.requirePermissions)('fund_operation.approve'), fundApprovalController.approveFundRequest);
|
||||
|
||||
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
@ -71,6 +71,46 @@ export declare function sendTrx(fromPrivateKeyHex: string, toAddress: string, am
|
||||
* @returns Transaction ID from broadcast result
|
||||
*/
|
||||
export declare function sendTrc20(fromPrivateKeyHex: string, contractAddress: string, toAddress: string, amountRaw: bigint): Promise<string>;
|
||||
/** Signed TRC20 payout whose txID is known before it is broadcast. */
|
||||
export type SignedTronTransfer = {
|
||||
txId: string;
|
||||
/** JSON of the signed transaction (re-broadcastable as-is until expiration). */
|
||||
payload: string;
|
||||
expiresAt: Date;
|
||||
fromAddress: string;
|
||||
};
|
||||
/**
|
||||
* Builds and signs a TRC20 `transfer` without broadcasting it.
|
||||
*/
|
||||
export declare function signTrc20Transfer(fromPrivateKeyHex: string, contractAddress: string, toAddress: string, amountRaw: bigint): Promise<SignedTronTransfer>;
|
||||
export type TronBroadcastResult = {
|
||||
kind: 'accepted';
|
||||
} | {
|
||||
kind: 'rejected';
|
||||
code: string;
|
||||
message: string;
|
||||
};
|
||||
/**
|
||||
* Interprets a `sendRawTransaction` response. A response with an error code means the node
|
||||
* refused the transaction (it was not accepted); DUP_TRANSACTION_ERROR means it is already known.
|
||||
*/
|
||||
export declare function classifyTronBroadcastResponse(res: {
|
||||
result?: boolean;
|
||||
code?: string;
|
||||
message?: string;
|
||||
}): TronBroadcastResult;
|
||||
/** Broadcasts a previously signed payload. Throws only on transport errors (outcome unknown). */
|
||||
export declare function broadcastSignedTransaction(payload: string): Promise<TronBroadcastResult>;
|
||||
export type TronTxStatus = {
|
||||
kind: 'not_found';
|
||||
} | {
|
||||
kind: 'mined';
|
||||
success: boolean;
|
||||
confirmations: number;
|
||||
message?: string;
|
||||
};
|
||||
/** Looks a payout up by txID on the full node (includes not-yet-solidified blocks). */
|
||||
export declare function getTransactionStatus(txId: string): Promise<TronTxStatus>;
|
||||
/**
|
||||
* Returns native TRX balance in sun for an address.
|
||||
*/
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"tronService.d.ts","sourceRoot":"","sources":["../../../src/services/blockchain/tronService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,4CAA4C;AAC5C,eAAO,MAAM,aAAa,uBAAuB,CAAC;AAElD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAwBjE;AAiBD;;;GAGG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC,CAIvD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wBAAsB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIvE;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKlG"}
|
||||
{"version":3,"file":"tronService.d.ts","sourceRoot":"","sources":["../../../src/services/blockchain/tronService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAOH,4CAA4C;AAC5C,eAAO,MAAM,aAAa,uBAAuB,CAAC;AAElD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAwBjE;AAiBD;;;GAGG;AACH,wBAAsB,eAAe,IAAI,OAAO,CAAC,MAAM,CAAC,CAIvD;AAED;;GAEG;AACH,wBAAsB,iBAAiB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAanF;AAED,8EAA8E;AAC9E,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;CACvB;AAgCD;;;;;GAKG;AACH,wBAAsB,2BAA2B,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CA8CnH;AAED,kEAAkE;AAClE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,eAAe,EAAE,MAAM,CAAC;IACxB,iEAAiE;IACjE,aAAa,EAAE,MAAM,C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AAED,iGAAiG;AACjG,wBAAsB,0BAA0B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAK9F;AAED,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EAAE,WAAW,CAAA;CAAE,GACrB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,aAAa,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjF,uFAAuF;AACvF,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAe9E;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAIvE;AAED;;GAEG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKlG"}
|
||||
84
backend/dist/services/blockchain/tronService.js
vendored
84
backend/dist/services/blockchain/tronService.js
vendored
@ -12,6 +12,10 @@ exports.getTrxTransactionsToAddress = getTrxTransactionsToAddress;
|
||||
exports.getTrc20TransfersToAddress = getTrc20TransfersToAddress;
|
||||
exports.sendTrx = sendTrx;
|
||||
exports.sendTrc20 = sendTrc20;
|
||||
exports.signTrc20Transfer = signTrc20Transfer;
|
||||
exports.classifyTronBroadcastResponse = classifyTronBroadcastResponse;
|
||||
exports.broadcastSignedTransaction = broadcastSignedTransaction;
|
||||
exports.getTransactionStatus = getTransactionStatus;
|
||||
exports.getTrxBalanceSun = getTrxBalanceSun;
|
||||
exports.getTrc20BalanceRaw = getTrc20BalanceRaw;
|
||||
const hdWallet_1 = require("../hdWallet");
|
||||
@ -238,6 +242,86 @@ async function sendTrc20(fromPrivateKeyHex, contractAddress, toAddress, amountRa
|
||||
const result = await contract.transfer(toAddress, amountRaw.toString()).send({ from: fromPrivateKeyHex, feeLimit: 100000000 });
|
||||
return result?.transaction?.txID || result?.txid || String(result);
|
||||
}
|
||||
/** Lets a signed payout be re-broadcast after a lost response before TRON drops it. */
|
||||
const PAYOUT_EXPIRATION_EXTENSION_SECONDS = 600;
|
||||
/**
|
||||
* Builds and signs a TRC20 `transfer` without broadcasting it.
|
||||
*/
|
||||
async function signTrc20Transfer(fromPrivateKeyHex, contractAddress, toAddress, amountRaw) {
|
||||
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
||||
const builder = tronWeb.transactionBuilder;
|
||||
const trx = tronWeb.trx;
|
||||
const fromRaw = tronWeb.address.fromPrivateKey(fromPrivateKeyHex.replace(/^0x/, ''));
|
||||
const fromAddress = typeof fromRaw === 'string' ? fromRaw : fromRaw.base58 ?? '';
|
||||
if (!fromAddress)
|
||||
throw new Error('Could not derive TRON hot wallet address');
|
||||
const built = await builder.triggerSmartContract(contractAddress, 'transfer(address,uint256)', { feeLimit: 100000000 }, [
|
||||
{ type: 'address', value: toAddress },
|
||||
{ type: 'uint256', value: amountRaw.toString() },
|
||||
], fromAddress);
|
||||
if (!built?.result?.result || !built.transaction) {
|
||||
throw new Error('TRON node refused to build the TRC20 transfer');
|
||||
}
|
||||
const extended = await builder.extendExpiration(built.transaction, PAYOUT_EXPIRATION_EXTENSION_SECONDS);
|
||||
const signed = await trx.sign(extended, fromPrivateKeyHex.replace(/^0x/, ''));
|
||||
const expirationMs = signed.raw_data?.expiration ?? Date.now() + 60000;
|
||||
return {
|
||||
txId: signed.txID,
|
||||
payload: JSON.stringify(signed),
|
||||
expiresAt: new Date(expirationMs),
|
||||
fromAddress,
|
||||
};
|
||||
}
|
||||
function decodeTronMessage(message) {
|
||||
if (!message)
|
||||
return '';
|
||||
if (/^[0-9a-fA-F]+$/.test(message) && message.length % 2 === 0) {
|
||||
try {
|
||||
return Buffer.from(message, 'hex').toString('utf8');
|
||||
}
|
||||
catch {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
/**
|
||||
* Interprets a `sendRawTransaction` response. A response with an error code means the node
|
||||
* refused the transaction (it was not accepted); DUP_TRANSACTION_ERROR means it is already known.
|
||||
*/
|
||||
function classifyTronBroadcastResponse(res) {
|
||||
if (res?.result === true)
|
||||
return { kind: 'accepted' };
|
||||
const code = String(res?.code ?? 'UNKNOWN');
|
||||
if (code === 'DUP_TRANSACTION_ERROR')
|
||||
return { kind: 'accepted' };
|
||||
return { kind: 'rejected', code, message: decodeTronMessage(res?.message) };
|
||||
}
|
||||
/** Broadcasts a previously signed payload. Throws only on transport errors (outcome unknown). */
|
||||
async function broadcastSignedTransaction(payload) {
|
||||
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
||||
const trx = tronWeb.trx;
|
||||
const res = await trx.sendRawTransaction(JSON.parse(payload));
|
||||
return classifyTronBroadcastResponse(res);
|
||||
}
|
||||
/** Looks a payout up by txID on the full node (includes not-yet-solidified blocks). */
|
||||
async function getTransactionStatus(txId) {
|
||||
const tronWeb = (0, hdWallet_1.getTronWeb)();
|
||||
const trx = tronWeb.trx;
|
||||
const info = await trx.getUnconfirmedTransactionInfo(txId);
|
||||
if (!info || typeof info.blockNumber !== 'number')
|
||||
return { kind: 'not_found' };
|
||||
const current = await getCurrentBlock();
|
||||
const confirmations = Math.max(0, current - info.blockNumber + 1);
|
||||
const receiptResult = info.receipt?.result;
|
||||
const success = info.result !== 'FAILED' && (receiptResult === undefined || receiptResult === 'SUCCESS');
|
||||
return {
|
||||
kind: 'mined',
|
||||
success,
|
||||
confirmations,
|
||||
message: success ? undefined : decodeTronMessage(info.resMessage) || receiptResult || info.result,
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Returns native TRX balance in sun for an address.
|
||||
*/
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"dbTamperService.d.ts","sourceRoot":"","sources":["../../src/services/dbTamperService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAgLH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC,CA6C7D;AAED,wBAAsB,kBAAkB,CAAC,IAAI,EAAE;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;;;;;;;;;;;;;;;;GAmBA;AAED,wBAAgB,wBAAwB,IAAI,MAAM,CAGjD;AAgBD,wBAAsB,sBAAsB,CAAC,IAAI,CAAC,EAAE;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,EAAE,CAAC,EAAE,IAAI,CAAC;IACV,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC,MAAM,CAAC,CAsClB"}
|
||||
{"version":3,"file":"dbTamperService.d.ts","sourceRoot":"","sources":["../../src/services/dbTamperService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAiLH,wBAAsB,qBAAqB,IAAI,OAAO,CAAC,MAAM,CAAC,CA6C7D;AAED,wBAAsB,kBAAkB,CAAC,IAAI,EAAE;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;;;;;;;;;;;;;;;;GAmBA;AAED,wBAAgB,wBAAwB,IAAI,MAAM,CAGjD;AAgBD,wBAAsB,sBAAsB,CAAC,IAAI,CAAC,EAAE;IAClD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,EAAE,CAAC,EAAE,IAAI,CAAC;IACV,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC,MAAM,CAAC,CAsClB"}
|
||||
1
backend/dist/services/dbTamperService.js
vendored
1
backend/dist/services/dbTamperService.js
vendored
@ -79,6 +79,7 @@ const TABLE_BASE_SEVERITY = {
|
||||
exchange_funding: 'high',
|
||||
system_settings: 'medium',
|
||||
withdrawal_locks: 'medium',
|
||||
withdrawal_status_history: 'medium',
|
||||
deposit_scanner_state: 'medium',
|
||||
security_alerts: 'high',
|
||||
refresh_tokens: 'medium',
|
||||
|
||||
2
backend/dist/services/dbTamperService.js.map
vendored
2
backend/dist/services/dbTamperService.js.map
vendored
File diff suppressed because one or more lines are too long
7
backend/dist/services/emailService.d.ts
vendored
7
backend/dist/services/emailService.d.ts
vendored
@ -78,8 +78,13 @@ type WalletEmailPayload = {
|
||||
export declare function sendWithdrawalSubmittedEmail(to: string, p: WalletEmailPayload): Promise<void>;
|
||||
/** Withdrawal completed on-chain. */
|
||||
export declare function sendWithdrawalCompletedEmail(to: string, p: WalletEmailPayload): Promise<void>;
|
||||
/** Withdrawal failed or cancelled; funds returned. */
|
||||
/** Technical problem during payout: the request is kept and will be reviewed (no refund). */
|
||||
export declare function sendWithdrawalFailedEmail(to: string, p: WalletEmailPayload): Promise<void>;
|
||||
/** Withdrawal declined by an admin or cancelled by the user: reserved amount credited back. */
|
||||
export declare function sendWithdrawalRefundedEmail(to: string, p: {
|
||||
kind: 'rejected' | 'cancelled';
|
||||
refundedUsdt: string;
|
||||
}): Promise<void>;
|
||||
/** Peer transfer sent confirmation. */
|
||||
export declare function sendTransferSentEmail(to: string, p: WalletEmailPayload): Promise<void>;
|
||||
/** Peer transfer received notification. */
|
||||
|
||||
2
backend/dist/services/emailService.d.ts.map
vendored
2
backend/dist/services/emailService.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"emailService.d.ts","sourceRoot":"","sources":["../../src/services/emailService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AASH,qEAAqE;AACrE,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEtD;AAOD;;GAEG;AACH,wBAAgB,yBAAyB,IAAI,OAAO,CAEnD;AAED;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAG1C;AAmCD,6DAA6D;AAC7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qBAAqB,CACzC,EAAE,EAAE,MAAM,EACV,CAAC,EAAE,kBAAkB,GACpB,OAAO,CAAC,IAAI,CAAC,CAcf;AAED,2CAA2C;AAC3C,wBAAsB,yBAAyB,CAC7C,EAAE,EAAE,MAAM,EACV,CAAC,EAAE,kBAAkB,GACpB,OAAO,CAAC,IAAI,CAAC,CAcf"}
|
||||
29
backend/dist/services/emailService.js
vendored
29
backend/dist/services/emailService.js
vendored
@ -26,6 +26,7 @@ exports.sendPermissionsChangedEmail = sendPermissionsChangedEmail;
|
||||
exports.sendWithdrawalSubmittedEmail = sendWithdrawalSubmittedEmail;
|
||||
exports.sendWithdrawalCompletedEmail = sendWithdrawalCompletedEmail;
|
||||
exports.sendWithdrawalFailedEmail = sendWithdrawalFailedEmail;
|
||||
exports.sendWithdrawalRefundedEmail = sendWithdrawalRefundedEmail;
|
||||
exports.sendTransferSentEmail = sendTransferSentEmail;
|
||||
exports.sendTransferReceivedEmail = sendTransferReceivedEmail;
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
@ -499,29 +500,33 @@ async function sendWithdrawalCompletedEmail(to, p) {
|
||||
], `<p>Your withdrawal was sent successfully.</p>${walletAmountHtml(p)}
|
||||
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
|
||||
}
|
||||
/** Withdrawal failed or cancelled; funds returned. */
|
||||
/** Technical problem during payout: the request is kept and will be reviewed (no refund). */
|
||||
async function sendWithdrawalFailedEmail(to, p) {
|
||||
const reason = p.reason?.trim();
|
||||
const lines = [
|
||||
'Your withdrawal could not be completed. The reserved amount was returned to your available balance.',
|
||||
'',
|
||||
`Amount: ${p.amountUsdt} USDT`,
|
||||
];
|
||||
const message = 'Processing of your withdrawal ran into a technical problem. Your request remains registered and will be reviewed.';
|
||||
const lines = [message, '', `Amount: ${p.amountUsdt} USDT`];
|
||||
if (p.toAddressMasked)
|
||||
lines.push(`Destination: ${p.toAddressMasked}`);
|
||||
if (reason)
|
||||
lines.push(`Reason: ${reason}`);
|
||||
lines.push('', `Time: ${new Date().toISOString()}`);
|
||||
const reasonHtml = reason ? `<p><strong>Reason:</strong> ${reason}</p>` : '';
|
||||
const destHtml = p.toAddressMasked
|
||||
? `<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`
|
||||
: '';
|
||||
await sendUserWalletEmail(to, 'Your Tloto withdrawal could not be completed', 'Withdrawal failed', lines, `<p>Your withdrawal could not be completed. Funds were returned to your available balance.</p>
|
||||
await sendUserWalletEmail(to, 'Your Tloto withdrawal is under review', 'Withdrawal under review', lines, `<p>${message}</p>
|
||||
<ul style="font-size:14px;line-height:1.6;">
|
||||
<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>
|
||||
${destHtml}
|
||||
</ul>
|
||||
${reasonHtml}
|
||||
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
|
||||
}
|
||||
/** Withdrawal declined by an admin or cancelled by the user: reserved amount credited back. */
|
||||
async function sendWithdrawalRefundedEmail(to, p) {
|
||||
const message = p.kind === 'rejected'
|
||||
? 'Your withdrawal request was declined. The corresponding amount has been credited back to your account.'
|
||||
: 'Your withdrawal request was cancelled. The corresponding amount has been credited back to your account.';
|
||||
const title = p.kind === 'rejected' ? 'Withdrawal declined' : 'Withdrawal cancelled';
|
||||
await sendUserWalletEmail(to, p.kind === 'rejected' ? 'Your Tloto withdrawal was declined' : 'Your Tloto withdrawal was cancelled', title, [message, '', `Credited back: ${p.refundedUsdt} USDT`, '', `Time: ${new Date().toISOString()}`], `<p>${message}</p>
|
||||
<ul style="font-size:14px;line-height:1.6;">
|
||||
<li><strong>Credited back:</strong> ${p.refundedUsdt} USDT</li>
|
||||
</ul>
|
||||
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`);
|
||||
}
|
||||
/** Peer transfer sent confirmation. */
|
||||
|
||||
2
backend/dist/services/emailService.js.map
vendored
2
backend/dist/services/emailService.js.map
vendored
File diff suppressed because one or more lines are too long
2
backend/dist/services/faqService.d.ts.map
vendored
2
backend/dist/services/faqService.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"faqService.d.ts","sourceRoot":"","sources":["../../src/services/faqService.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAuBtE,sDAAsD;AACtD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,CAGjE;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAc,GAAG,MAAM,CAIrF;AAED;;;GAGG;AACH,wBAAgB,6BAA6B,CAC3C,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,eAAe,GACpB,MAAM,CAIR;AAgBD,iBAAS,WAAW,CAAC,GAAG,EAAE,cAAc;;;;;;;;;;;;;;;;;EAavC;AA8BD,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAMnE;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE3D;AAYD;;GAEG;AACH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE;IAC7C,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,OAAO,GAAG,cAAc,CAAC;IAC/B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAC3B,GAAG,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,YAA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B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;;;;;;;;;;;;;;;;;;KAGA;AAED,wBAAsB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;GAuBjF;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;GAc7F;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM;;GAI9C;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI3D;AAED;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE;IAClD,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,eAAe,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC,CA6C1C;AAED,wBAAsB,sBAAsB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe;;;;;;;;;;;;;;;;;GAQrF;AAED,iEAAiE;AACjE,wBAAsB,6BAA6B,CACjD,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAY5D"}
|
||||
14
backend/dist/services/faqService.js
vendored
14
backend/dist/services/faqService.js
vendored
@ -357,10 +357,12 @@ async function updateAdminCategory(id, body) {
|
||||
throw new Error('Category not found');
|
||||
return mapCategory(updated);
|
||||
}
|
||||
function unlinkFaqFileQuiet(filename) {
|
||||
/** Removes a FAQ PDF from disk and clears its FIM baseline (intentional delete). */
|
||||
async function unlinkFaqFileQuiet(filename) {
|
||||
if (!filename)
|
||||
return;
|
||||
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(filename));
|
||||
await (0, fileIntegrityService_1.forgetUploadedFile)(fileIntegrityService_1.FILE_INTEGRITY_ROOTS.faq, filename);
|
||||
}
|
||||
async function deleteAdminCategory(id) {
|
||||
const count = await repo.countEntriesInCategory(id);
|
||||
@ -373,8 +375,8 @@ async function deleteAdminCategory(id) {
|
||||
const ok = await repo.deleteCategory(id);
|
||||
if (!ok)
|
||||
throw new Error('Category not found');
|
||||
unlinkFaqFileQuiet(existing.pdf_fr_filename);
|
||||
unlinkFaqFileQuiet(existing.pdf_en_filename);
|
||||
await unlinkFaqFileQuiet(existing.pdf_fr_filename);
|
||||
await unlinkFaqFileQuiet(existing.pdf_en_filename);
|
||||
return { ok: true };
|
||||
}
|
||||
async function listAdminFaqs(filters) {
|
||||
@ -465,12 +467,12 @@ async function uploadCategoryDocument(input) {
|
||||
const originalName = buildFaqCategoryGuideFilename(cat.slug || cat.name, input.lang);
|
||||
const updated = await repo.setCategoryDocument(input.categoryId, input.lang, saved.filename, originalName);
|
||||
if (!updated) {
|
||||
(0, fileMagic_1.removeUploadedFile)(resolveFaqFilePath(saved.filename));
|
||||
await unlinkFaqFileQuiet(saved.filename);
|
||||
await repo.deleteUploadedFile(saved.filename);
|
||||
throw new Error('Category not found');
|
||||
}
|
||||
if (previous && previous !== saved.filename) {
|
||||
unlinkFaqFileQuiet(previous);
|
||||
await unlinkFaqFileQuiet(previous);
|
||||
await repo.deleteUploadedFile(previous).catch(() => undefined);
|
||||
}
|
||||
return mapCategory(updated);
|
||||
@ -480,7 +482,7 @@ async function deleteCategoryDocument(categoryId, lang) {
|
||||
if (!result)
|
||||
throw new Error('Category not found');
|
||||
if (result.removedFilename) {
|
||||
unlinkFaqFileQuiet(result.removedFilename);
|
||||
await unlinkFaqFileQuiet(result.removedFilename);
|
||||
await repo.deleteUploadedFile(result.removedFilename).catch(() => undefined);
|
||||
}
|
||||
return mapCategory(result.row);
|
||||
|
||||
2
backend/dist/services/faqService.js.map
vendored
2
backend/dist/services/faqService.js.map
vendored
File diff suppressed because one or more lines are too long
@ -1 +1 @@
|
||||
{"version":3,"file":"settingsService.d.ts","sourceRoot":"","sources":["../../src/services/settingsService.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AA8O3C;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAI3D;AAID;;;;;;;;;;GAUG;AAEH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CA6M3F;AAID;;;;;;;;GAQG;AAEH,wBAAsB,cAAc,CAClC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,EAChC,KAAK,CAAC,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GACjE,OAAO,CAAC,cAAc,CAAC,CAkCzB"}
|
||||
{"version":3,"file":"settingsService.d.ts","sourceRoot":"","sources":["../../src/services/settingsService.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAwP3C;;;;;;GAMG;AAEH,wBAAsB,WAAW,IAAI,OAAO,CAAC,cAAc,CAAC,CAI3D;AAID;;;;;;;;;;GAUG;AAEH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CAqN3F;AAID;;;;;;;;GAQG;AAEH,wBAAsB,cAAc,CAClC,OAAO,EAAE,OAAO,CAAC,cAAc,CAAC,EAChC,KAAK,CAAC,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GACjE,OAAO,CAAC,cAAc,CAAC,CAkCzB"}
|
||||
9
backend/dist/services/settingsService.js
vendored
9
backend/dist/services/settingsService.js
vendored
@ -94,6 +94,9 @@ function validateUpdates(updates) {
|
||||
if (updates.withdrawal_network_fee_usdt_micro !== undefined) {
|
||||
updates.withdrawal_network_fee_usdt_micro = clampInt(updates.withdrawal_network_fee_usdt_micro, 0, 100000000);
|
||||
}
|
||||
if (updates.withdrawal_auto_retry_interval_minutes !== undefined) {
|
||||
updates.withdrawal_auto_retry_interval_minutes = clampInt(updates.withdrawal_auto_retry_interval_minutes, 1, 1440);
|
||||
}
|
||||
if (updates.transfer_min_remaining_usdt_micro !== undefined) {
|
||||
updates.transfer_min_remaining_usdt_micro = clampInt(updates.transfer_min_remaining_usdt_micro, 0, 1000000000000);
|
||||
}
|
||||
@ -220,6 +223,12 @@ function parseSettingsUpdates(body) {
|
||||
if (typeof body.transfer_min_remaining_usdt_micro === 'number') {
|
||||
updates.transfer_min_remaining_usdt_micro = body.transfer_min_remaining_usdt_micro;
|
||||
}
|
||||
if (typeof body.withdrawal_auto_retry_enabled === 'boolean') {
|
||||
updates.withdrawal_auto_retry_enabled = body.withdrawal_auto_retry_enabled;
|
||||
}
|
||||
if (typeof body.withdrawal_auto_retry_interval_minutes === 'number') {
|
||||
updates.withdrawal_auto_retry_interval_minutes = body.withdrawal_auto_retry_interval_minutes;
|
||||
}
|
||||
if (typeof body.require_admin_2fa === 'boolean') {
|
||||
updates.require_admin_2fa = body.require_admin_2fa;
|
||||
}
|
||||
|
||||
2
backend/dist/services/settingsService.js.map
vendored
2
backend/dist/services/settingsService.js.map
vendored
File diff suppressed because one or more lines are too long
84
backend/dist/services/withdrawalService.d.ts
vendored
84
backend/dist/services/withdrawalService.d.ts
vendored
@ -1,9 +1,14 @@
|
||||
/**
|
||||
* On-chain withdrawal service.
|
||||
* Debits unified USDT ledger (USDT_TRC20, 6 decimals); pays from the chosen
|
||||
* rail hot wallet (TRC20 or BEP20). Network need not match deposit history —
|
||||
* liquidity is gated by hot float (USDT + gas), not user inventory.
|
||||
* On-chain withdrawal service (state machine v2).
|
||||
*
|
||||
* A valid request is always recorded as `pending` with `amount + fee` reserved on the user's
|
||||
* unified USDT ledger (USDT_TRC20, 6 decimals), even when the platform hot wallet cannot pay
|
||||
* right now. Payout runs separately: pending -> processing -> completed once the transaction
|
||||
* is confirmed on-chain. Platform liquidity problems never surface to the user — the request
|
||||
* simply stays pending until an admin (or the automatic attempt) processes it.
|
||||
*/
|
||||
import type { WithdrawalActor, WithdrawalRow } from '../repositories/withdrawalRepository';
|
||||
import { WithdrawalPendingReason } from './withdrawals/withdrawalStateMachine';
|
||||
export type WithdrawalResult = {
|
||||
transactionId: string;
|
||||
status: string;
|
||||
@ -12,15 +17,70 @@ export type WithdrawalResult = {
|
||||
totalDebited: string;
|
||||
fundRequestId?: string;
|
||||
blockchainTxId?: string | null;
|
||||
/** True when the same idempotency key was already used: no new request was created. */
|
||||
duplicate?: boolean;
|
||||
};
|
||||
export type RequestWithdrawalOptions = {
|
||||
/** Client-generated key: repeating a submission returns the original request. */
|
||||
idempotencyKey?: string | null;
|
||||
/** Start payout right after recording (default true). */
|
||||
autoProcess?: boolean;
|
||||
};
|
||||
/**
|
||||
* Submits a withdrawal: locks unified ledger, verifies hot float, pays from rail hot wallet.
|
||||
* `walletTypeCode` selects the payout rail (USDT_TRC20 or USDT_BEP20).
|
||||
* `amountRaw` is always in ledger micro-USDT (6 decimals).
|
||||
* Records a withdrawal request: validates, reserves funds and returns status `pending`.
|
||||
* Never fails because of platform hot-wallet liquidity.
|
||||
*/
|
||||
export declare function requestWithdrawal(userId: string, walletTypeCode: string, toAddress: string, amountRaw: bigint, totpCode?: string): Promise<WithdrawalResult>;
|
||||
/** 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>;
|
||||
export declare function requestWithdrawal(userId: string, walletTypeCode: string, toAddress: string, amountRaw: bigint, totpCode?: string, options?: RequestWithdrawalOptions): Promise<WithdrawalResult>;
|
||||
export type ProcessWithdrawalResult = {
|
||||
transactionId: string;
|
||||
status: string;
|
||||
pendingReason?: WithdrawalPendingReason | null;
|
||||
blockchainTxId?: string | null;
|
||||
message?: string;
|
||||
};
|
||||
/**
|
||||
* Attempts the payout of a pending/failed request: pending|failed -> processing, then either
|
||||
* broadcast (stays processing until confirmed), back to pending (liquidity), or failed.
|
||||
* Throws WithdrawalStateError only when the request cannot be processed from its status.
|
||||
*/
|
||||
export declare function processWithdrawal(transactionId: string, actor: WithdrawalActor, opts?: {
|
||||
approvalGranted?: boolean;
|
||||
}): Promise<ProcessWithdrawalResult>;
|
||||
/** Called by the approval workflow once the large-withdrawal quorum is reached. */
|
||||
export declare function processApprovedWithdrawal(transactionId: string, approvedBy: string): Promise<Record<string, unknown>>;
|
||||
/** @deprecated name kept for the approval workflow; payout is now asynchronous. */
|
||||
export declare const broadcastApprovedWithdrawal: typeof processApprovedWithdrawal;
|
||||
/** Verifies one broadcast payout on-chain and advances its status when the result is known. */
|
||||
export declare function verifyBroadcastWithdrawal(row: WithdrawalRow, nowMs?: number): Promise<string>;
|
||||
/**
|
||||
* Automatic retry pass (only when enabled in settings). A request is claimed only when the
|
||||
* hot wallet can pay it right now (USDT + gas, minus payouts already in flight), so an
|
||||
* unfunded wallet produces no status churn.
|
||||
*/
|
||||
export declare function runWithdrawalAutoRetryCycle(): Promise<{
|
||||
attempted: number;
|
||||
skipped: number;
|
||||
}>;
|
||||
/** One pass of the confirmation monitor (also recovers interrupted claims and auto-retries). */
|
||||
export declare function runWithdrawalMonitorCycle(): Promise<{
|
||||
checked: number;
|
||||
completed: number;
|
||||
}>;
|
||||
/** Admin refusal (pending|failed -> rejected) with a full, single refund. */
|
||||
export declare function rejectWithdrawal(transactionId: string, input: {
|
||||
actorId: string;
|
||||
reason: string;
|
||||
source?: 'admin' | 'approval';
|
||||
}): Promise<WithdrawalRow>;
|
||||
/** User cancellation of a request that is still pending (pending -> cancelled, refunded). */
|
||||
export declare function cancelWithdrawal(transactionId: string, input: {
|
||||
userId: string;
|
||||
actorType?: 'user' | 'admin';
|
||||
actorId?: string;
|
||||
source?: 'user' | 'approval';
|
||||
}): Promise<WithdrawalRow>;
|
||||
/** Approval workflow cancelled by the requester / super admin. */
|
||||
export declare function cancelWithdrawalFromApproval(transactionId: string, actorId: string): Promise<void>;
|
||||
/** Admin: failed -> pending (e.g. before a later retry). */
|
||||
export declare function requeueWithdrawal(transactionId: string, actorId: string): Promise<WithdrawalRow>;
|
||||
//# sourceMappingURL=withdrawalService.d.ts.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"withdrawalService.d.ts","sourceRoot":"","sources":["../../src/services/withdrawalService.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AA2GH,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,EAC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M,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,GAAG,UAAU,CAAA;CAAE,GACxE,OAAO,CAAC,aAAa,CAAC,CAmCxB;AAED,6FAA6F;AAC7F,wBAAsB,gBAAgB,CACpC,aAAa,EAAE,MAAM,EACrB,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAA;CAAE,GACtG,OAAO,CAAC,aAAa,CAAC,CAuCxB;AAED,kEAAkE;AAClE,wBAAsB,4BAA4B,CAChD,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC,CASf;AAED,4DAA4D;AAC5D,wBAAsB,iBAAiB,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC,CAqBtG"}
|
||||
1005
backend/dist/services/withdrawalService.js
vendored
1005
backend/dist/services/withdrawalService.js
vendored
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -32,6 +32,22 @@ import { validateProductionSecretsOrThrow } from '../safety/productionSecretsGua
|
||||
import { connectRedis } from '../realtime/redis/client';
|
||||
|
||||
const DEPOSIT_POLL_INTERVAL_MS = 60 * 1000;
|
||||
const WITHDRAWAL_MONITOR_INTERVAL_MS = 20 * 1000;
|
||||
|
||||
/** Confirms broadcast payouts on-chain (completed only after required confirmations). */
|
||||
function startWithdrawalMonitor(): void {
|
||||
const run = async () => {
|
||||
try {
|
||||
const { runWithdrawalMonitorCycle } = await import('../services/withdrawalService');
|
||||
const r = await runWithdrawalMonitorCycle();
|
||||
if (r.completed > 0) console.log(`[withdrawal] ${r.completed} payout(s) confirmed`);
|
||||
} catch (e) {
|
||||
console.error('Withdrawal monitor error:', e);
|
||||
}
|
||||
setTimeout(run, WITHDRAWAL_MONITOR_INTERVAL_MS);
|
||||
};
|
||||
setTimeout(run, 20 * 1000);
|
||||
}
|
||||
|
||||
async function startDepositMonitor(): Promise<void> {
|
||||
const run = async () => {
|
||||
@ -190,6 +206,7 @@ export async function bootstrapCore(opts: BootstrapOptions = {}): Promise<void>
|
||||
startAdminExportWorker();
|
||||
scheduleAnalyticsMaterializedViewRefresh();
|
||||
startDepositMonitor();
|
||||
startWithdrawalMonitor();
|
||||
startLedgerIntegrityMonitor();
|
||||
startFileIntegrityMonitor();
|
||||
startDbTamperMonitor();
|
||||
|
||||
@ -1,16 +1,16 @@
|
||||
/**
|
||||
* Withdrawal controller — HTTP handler for submitting on-chain withdrawal requests.
|
||||
* Withdrawal controllers — user submission / cancellation and the admin withdrawal queue.
|
||||
*/
|
||||
|
||||
import { Response } from 'express';
|
||||
import * as withdrawalService from '../services/withdrawalService';
|
||||
import * as withdrawalAdminService from '../services/withdrawals/withdrawalAdminService';
|
||||
import { AuthRequest } from '../middleware/auth';
|
||||
|
||||
/**
|
||||
* Submits a withdrawal request to send funds from the user's wallet to an external address.
|
||||
* May require a TOTP code when 2FA is enabled for the user.
|
||||
* @param req - Authenticated request. Body: `walletType`, `toAddress`, `amount`, optional `totpCode`.
|
||||
* @param res - JSON `{ transactionId, status }` on success, 400 on validation or withdrawal failure.
|
||||
* Records a withdrawal request (status `pending`, amount + fee reserved).
|
||||
* Body: `walletType`, `toAddress`, `amount`, optional `totpCode`, optional `idempotencyKey`
|
||||
* (also accepted as the `Idempotency-Key` header).
|
||||
*/
|
||||
export async function withdraw(req: AuthRequest, res: Response): Promise<void> {
|
||||
const userId = req.user!.userId;
|
||||
@ -19,13 +19,70 @@ export async function withdraw(req: AuthRequest, res: Response): Promise<void> {
|
||||
res.status(400).json({ error: 'walletType, toAddress and amount required' });
|
||||
return;
|
||||
}
|
||||
const headerKey = req.header('Idempotency-Key')?.trim();
|
||||
const amountRaw = BigInt(amount);
|
||||
const result = await withdrawalService.requestWithdrawal(
|
||||
userId,
|
||||
walletType,
|
||||
toAddress,
|
||||
amountRaw,
|
||||
req.body.totpCode
|
||||
req.body.totpCode,
|
||||
{ idempotencyKey: req.body.idempotencyKey ?? headerKey ?? null }
|
||||
);
|
||||
res.json(result);
|
||||
}
|
||||
|
||||
/** User cancels their own withdrawal while it is still pending (refund to available balance). */
|
||||
export async function cancelOwnWithdrawal(req: AuthRequest, res: Response): Promise<void> {
|
||||
const row = await withdrawalService.cancelWithdrawal(String(req.params.id), {
|
||||
userId: req.user!.userId,
|
||||
});
|
||||
res.json({ transactionId: row.id, status: row.status });
|
||||
}
|
||||
|
||||
export async function adminListWithdrawals(req: AuthRequest, res: Response): Promise<void> {
|
||||
const q = req.query as Record<string, string | undefined>;
|
||||
const result = await withdrawalAdminService.listWithdrawals({
|
||||
status: q.status,
|
||||
network: q.network,
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
minAmount: q.minAmount,
|
||||
maxAmount: q.maxAmount,
|
||||
search: q.search,
|
||||
limit: q.limit ? Number(q.limit) : undefined,
|
||||
offset: q.offset ? Number(q.offset) : undefined,
|
||||
});
|
||||
res.json(result);
|
||||
}
|
||||
|
||||
export async function adminGetWithdrawal(req: AuthRequest, res: Response): Promise<void> {
|
||||
const detail = await withdrawalAdminService.getWithdrawalDetail(String(req.params.id));
|
||||
if (!detail) {
|
||||
res.status(404).json({ error: 'Withdrawal not found', code: 'WITHDRAWAL_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
res.json(detail);
|
||||
}
|
||||
|
||||
/** Starts (or retries) the payout. Returns the resulting status (processing / pending / failed). */
|
||||
export async function adminProcessWithdrawal(req: AuthRequest, res: Response): Promise<void> {
|
||||
const result = await withdrawalService.processWithdrawal(String(req.params.id), {
|
||||
actorType: 'admin',
|
||||
actorUserId: req.user!.userId,
|
||||
});
|
||||
res.json(result);
|
||||
}
|
||||
|
||||
export async function adminRequeueWithdrawal(req: AuthRequest, res: Response): Promise<void> {
|
||||
const row = await withdrawalService.requeueWithdrawal(String(req.params.id), req.user!.userId);
|
||||
res.json({ transactionId: row.id, status: row.status });
|
||||
}
|
||||
|
||||
export async function adminRejectWithdrawal(req: AuthRequest, res: Response): Promise<void> {
|
||||
const row = await withdrawalService.rejectWithdrawal(String(req.params.id), {
|
||||
actorId: req.user!.userId,
|
||||
reason: String(req.body.reason ?? ''),
|
||||
});
|
||||
res.json({ transactionId: row.id, status: row.status });
|
||||
}
|
||||
|
||||
@ -3909,4 +3909,101 @@ BEGIN
|
||||
|
||||
END IF;
|
||||
|
||||
END $$;
|
||||
END $$;
|
||||
|
||||
-- ---------------------------------------------------------------------------
|
||||
-- Withdrawal state machine v2
|
||||
-- pending -> processing -> completed
|
||||
-- processing -> pending (temporary, nothing broadcast) | failed
|
||||
-- failed -> processing | pending | rejected ; pending -> rejected | cancelled
|
||||
-- Funds stay in ledger locked_balance until completed (debit) or rejected/cancelled (refund).
|
||||
-- Rows with withdrawal_flow_version IS NULL are legacy and are never driven by the v2 machine.
|
||||
-- ---------------------------------------------------------------------------
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS withdrawal_flow_version SMALLINT;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS pending_reason VARCHAR(48);
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS processing_stage VARCHAR(32);
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS processing_attempts INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS processing_started_at TIMESTAMPTZ;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS processing_actor_id UUID;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS last_error TEXT;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS idempotency_key VARCHAR(128);
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS signed_payload TEXT;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS signed_expires_at TIMESTAMPTZ;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS broadcast_at TIMESTAMPTZ;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS abandoned_tx_hashes TEXT[];
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS refunded_at TIMESTAMPTZ;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS rejection_reason TEXT;
|
||||
ALTER TABLE transactions ADD COLUMN IF NOT EXISTS resolved_by UUID;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_transactions_withdrawal_idempotency
|
||||
ON transactions (user_id, idempotency_key)
|
||||
WHERE idempotency_key IS NOT NULL;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_transactions_withdrawal_queue
|
||||
ON transactions (status, created_at DESC)
|
||||
WHERE type = 'withdrawal';
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_withdrawal_locks_transaction
|
||||
ON withdrawal_locks (transaction_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS withdrawal_status_history (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
transaction_id UUID NOT NULL REFERENCES transactions (id) ON DELETE CASCADE,
|
||||
from_status VARCHAR(32),
|
||||
to_status VARCHAR(32) NOT NULL,
|
||||
actor_type VARCHAR(16) NOT NULL DEFAULT 'system'
|
||||
CHECK (actor_type IN ('user', 'admin', 'system')),
|
||||
actor_user_id UUID,
|
||||
reason TEXT,
|
||||
metadata JSONB,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_withdrawal_status_history_tx
|
||||
ON withdrawal_status_history (transaction_id, created_at);
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
EXECUTE format('DROP TRIGGER IF EXISTS trg_db_tamper_%I ON %I', 'withdrawal_status_history', 'withdrawal_status_history');
|
||||
EXECUTE format(
|
||||
'CREATE TRIGGER trg_db_tamper_%I
|
||||
AFTER INSERT OR UPDATE OR DELETE ON %I
|
||||
FOR EACH ROW EXECUTE FUNCTION trg_fn_db_tamper_guard()',
|
||||
'withdrawal_status_history', 'withdrawal_status_history'
|
||||
);
|
||||
END $$;
|
||||
|
||||
-- Legacy rows: old code unlocked funds before writing 'failed', so those are already refunded.
|
||||
UPDATE transactions t
|
||||
SET status = 'failed_refunded',
|
||||
withdrawal_flow_version = 2,
|
||||
refunded_at = COALESCE(t.refunded_at, t.updated_at)
|
||||
WHERE t.type = 'withdrawal'
|
||||
AND t.withdrawal_flow_version IS NULL
|
||||
AND t.status = 'failed'
|
||||
AND NOT EXISTS (SELECT 1 FROM withdrawal_locks l WHERE l.transaction_id = t.id);
|
||||
|
||||
-- Legacy large withdrawals awaiting the approval quorum (funds still locked).
|
||||
UPDATE transactions t
|
||||
SET status = 'pending',
|
||||
pending_reason = 'awaiting_approval',
|
||||
withdrawal_flow_version = 2
|
||||
WHERE t.type = 'withdrawal'
|
||||
AND t.withdrawal_flow_version IS NULL
|
||||
AND t.status = 'pending_approval'
|
||||
AND EXISTS (SELECT 1 FROM withdrawal_locks l WHERE l.transaction_id = t.id);
|
||||
|
||||
UPDATE transactions t
|
||||
SET pending_reason = COALESCE(t.pending_reason, 'queued'),
|
||||
withdrawal_flow_version = 2
|
||||
WHERE t.type = 'withdrawal'
|
||||
AND t.withdrawal_flow_version IS NULL
|
||||
AND t.status = 'pending'
|
||||
AND t.blockchain_tx_id IS NULL
|
||||
AND EXISTS (SELECT 1 FROM withdrawal_locks l WHERE l.transaction_id = t.id);
|
||||
|
||||
UPDATE transactions
|
||||
SET withdrawal_flow_version = 2
|
||||
WHERE type = 'withdrawal'
|
||||
AND withdrawal_flow_version IS NULL
|
||||
AND status = 'completed';
|
||||
@ -46,6 +46,13 @@ export interface SystemSettings {
|
||||
candle_predict_retention_keep_last: number;
|
||||
/** Network fee deducted from user USDT balance per withdrawal (6-decimal micro units). */
|
||||
withdrawal_network_fee_usdt_micro: number;
|
||||
/**
|
||||
* When true, withdrawals pending for hot-wallet USDT / gas / missing hot wallet are retried
|
||||
* automatically once the hot wallet can pay them.
|
||||
*/
|
||||
withdrawal_auto_retry_enabled: boolean;
|
||||
/** Minutes between automatic retry passes (1–1440). */
|
||||
withdrawal_auto_retry_interval_minutes: number;
|
||||
/**
|
||||
* Minimum USDT that must remain on the sender's main balance after a peer transfer
|
||||
* (6-decimal micro units). `0` disables the limit.
|
||||
|
||||
@ -13,11 +13,16 @@ export interface Transaction {
|
||||
fee: string;
|
||||
status:
|
||||
| 'pending'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'rejected'
|
||||
| 'cancelled'
|
||||
| 'failed_refunded'
|
||||
// Legacy withdrawal statuses (pre state machine v2)
|
||||
| 'pending_approval'
|
||||
| 'broadcasting'
|
||||
| 'confirming'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'ledger_finalize_failed';
|
||||
blockchain_tx_id: string | null;
|
||||
from_address: string | null;
|
||||
|
||||
@ -186,6 +186,16 @@ export const PERMISSION_CATALOG: PermissionDef[] = [
|
||||
p('approval_policies', 'view', 'View approval policies', 'fund_operations', ['approval_policy.view']),
|
||||
p('approval_policies', 'manage', 'Manage approval policies', 'fund_operations', ['approval_policy.manage']),
|
||||
|
||||
// Granular — withdrawal queue
|
||||
p('withdrawals', 'view', 'View the withdrawal request queue and history', 'withdrawals', ['treasury.view']),
|
||||
p(
|
||||
'withdrawals',
|
||||
'manage',
|
||||
'Process, retry, requeue or reject withdrawal requests',
|
||||
'withdrawals',
|
||||
['fund_operation.approve']
|
||||
),
|
||||
|
||||
// Granular — ledger
|
||||
p('ledger_credit', 'manage', 'Grant ledger credits to users', 'users', ['ledger.credit']),
|
||||
|
||||
@ -242,6 +252,7 @@ export const DEFAULT_ADMIN_PERMISSION_KEYS = [
|
||||
'admin.games.view',
|
||||
'admin.games.edit',
|
||||
'admin.treasury.view',
|
||||
'admin.withdrawals.view',
|
||||
'admin.security.view',
|
||||
'admin.security.manage',
|
||||
'admin.referral.view',
|
||||
|
||||
@ -75,6 +75,10 @@ function buildDefaults(): SystemSettings {
|
||||
|
||||
withdrawal_network_fee_usdt_micro: config.withdrawal.networkFeeUsdtMicro,
|
||||
|
||||
withdrawal_auto_retry_enabled: false,
|
||||
|
||||
withdrawal_auto_retry_interval_minutes: 10,
|
||||
|
||||
transfer_min_remaining_usdt_micro: 0,
|
||||
|
||||
require_admin_2fa: true,
|
||||
@ -135,6 +139,8 @@ const BOOLEAN_KEYS = new Set([
|
||||
|
||||
'login_risk_auto_suspend_accounts',
|
||||
|
||||
'withdrawal_auto_retry_enabled',
|
||||
|
||||
]);
|
||||
|
||||
|
||||
@ -169,6 +175,8 @@ const INTEGER_KEYS = new Set([
|
||||
|
||||
'withdrawal_network_fee_usdt_micro',
|
||||
|
||||
'withdrawal_auto_retry_interval_minutes',
|
||||
|
||||
'transfer_min_remaining_usdt_micro',
|
||||
|
||||
'login_max_failed_attempts',
|
||||
@ -317,6 +325,10 @@ const UPDATABLE_KEYS = [
|
||||
|
||||
'withdrawal_network_fee_usdt_micro',
|
||||
|
||||
'withdrawal_auto_retry_enabled',
|
||||
|
||||
'withdrawal_auto_retry_interval_minutes',
|
||||
|
||||
'transfer_min_remaining_usdt_micro',
|
||||
|
||||
'require_admin_2fa',
|
||||
|
||||
@ -200,21 +200,31 @@ export async function listByUserId(
|
||||
);
|
||||
}
|
||||
|
||||
/** Withdrawal rows since a UTC timestamp (for daily limit checks). */
|
||||
/**
|
||||
* Withdrawal rows since a UTC timestamp (for daily limit checks).
|
||||
* Excludes requests whose funds were returned; `failed` still holds a reservation and counts.
|
||||
*/
|
||||
export async function listWithdrawalsSince(
|
||||
userId: string,
|
||||
since: Date
|
||||
since: Date,
|
||||
client?: PoolClient
|
||||
): Promise<Array<{ amount: string; fee: string; code: string; decimals: number }>> {
|
||||
return query<Array<{ amount: string; fee: string; code: string; decimals: number }>>(
|
||||
`SELECT t.amount::text, COALESCE(t.fee, 0)::text AS fee, wt.code, wt.decimals
|
||||
const sql = `SELECT t.amount::text, COALESCE(t.fee, 0)::text AS fee, wt.code, wt.decimals
|
||||
FROM transactions t
|
||||
INNER JOIN wallet_types wt ON wt.id = t.wallet_type_id
|
||||
WHERE t.user_id = $1
|
||||
AND t.type = 'withdrawal'
|
||||
AND t.status NOT IN ('failed', 'cancelled')
|
||||
AND t.created_at >= $2`,
|
||||
[userId, since]
|
||||
);
|
||||
AND t.status NOT IN ('rejected', 'cancelled', 'failed_refunded')
|
||||
AND NOT (t.status = 'failed' AND t.withdrawal_flow_version IS NULL)
|
||||
AND t.created_at >= $2`;
|
||||
if (client) {
|
||||
const res = await client.query<{ amount: string; fee: string; code: string; decimals: number }>(sql, [
|
||||
userId,
|
||||
since,
|
||||
]);
|
||||
return res.rows;
|
||||
}
|
||||
return query<Array<{ amount: string; fee: string; code: string; decimals: number }>>(sql, [userId, since]);
|
||||
}
|
||||
|
||||
/** Total transaction count for a user (pagination). */
|
||||
|
||||
821
backend/src/repositories/withdrawalRepository.ts
Normal file
821
backend/src/repositories/withdrawalRepository.ts
Normal file
@ -0,0 +1,821 @@
|
||||
/**
|
||||
* Withdrawal request persistence for the v2 state machine.
|
||||
* Every status change runs in one authorized DB transaction with the row locked
|
||||
* (SELECT ... FOR UPDATE), so concurrent admins / workers cannot both act on a request
|
||||
* and a reservation can never be released or debited twice.
|
||||
*/
|
||||
|
||||
import { PoolClient } from 'pg';
|
||||
import { query, getClient, beginAuthorizedTransaction } from '../db/connection';
|
||||
import {
|
||||
WITHDRAWAL_FLOW_VERSION,
|
||||
WithdrawalActorType,
|
||||
WithdrawalErrorCode,
|
||||
WithdrawalPendingReason,
|
||||
WithdrawalStatus,
|
||||
canTransition,
|
||||
} from '../services/withdrawals/withdrawalStateMachine';
|
||||
|
||||
export type WithdrawalRow = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
wallet_type_id: number;
|
||||
type: string;
|
||||
amount: string;
|
||||
fee: string;
|
||||
status: string;
|
||||
blockchain_tx_id: string | null;
|
||||
from_address: string | null;
|
||||
to_address: string | null;
|
||||
confirmations: number | null;
|
||||
required_confirmations: number | null;
|
||||
metadata: Record<string, unknown> | null;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
withdrawal_flow_version: number | null;
|
||||
pending_reason: string | null;
|
||||
processing_stage: string | null;
|
||||
processing_attempts: number;
|
||||
processing_started_at: Date | null;
|
||||
processing_actor_id: string | null;
|
||||
last_error: string | null;
|
||||
idempotency_key: string | null;
|
||||
signed_payload: string | null;
|
||||
signed_expires_at: Date | null;
|
||||
broadcast_at: Date | null;
|
||||
abandoned_tx_hashes: string[] | null;
|
||||
refunded_at: Date | null;
|
||||
rejection_reason: string | null;
|
||||
resolved_by: string | null;
|
||||
};
|
||||
|
||||
export type WithdrawalActor = {
|
||||
actorType: WithdrawalActorType;
|
||||
actorUserId?: string | null;
|
||||
};
|
||||
|
||||
export type WithdrawalOpResult =
|
||||
| { ok: true; row: WithdrawalRow; fromStatus: string }
|
||||
| { ok: false; code: WithdrawalErrorCode; status?: string };
|
||||
|
||||
const PLAIN_COLS = [
|
||||
'id',
|
||||
'user_id',
|
||||
'wallet_type_id',
|
||||
'type',
|
||||
'status',
|
||||
'blockchain_tx_id',
|
||||
'from_address',
|
||||
'to_address',
|
||||
'confirmations',
|
||||
'required_confirmations',
|
||||
'metadata',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'withdrawal_flow_version',
|
||||
'pending_reason',
|
||||
'processing_stage',
|
||||
'processing_attempts',
|
||||
'processing_started_at',
|
||||
'processing_actor_id',
|
||||
'last_error',
|
||||
'idempotency_key',
|
||||
'signed_payload',
|
||||
'signed_expires_at',
|
||||
'broadcast_at',
|
||||
'abandoned_tx_hashes',
|
||||
'refunded_at',
|
||||
'rejection_reason',
|
||||
'resolved_by',
|
||||
];
|
||||
|
||||
function selectCols(alias = ''): string {
|
||||
const p = alias ? `${alias}.` : '';
|
||||
return [
|
||||
...PLAIN_COLS.map((c) => `${p}${c}`),
|
||||
`${p}amount::text AS amount`,
|
||||
`COALESCE(${p}fee, 0)::text AS fee`,
|
||||
].join(', ');
|
||||
}
|
||||
|
||||
const COLS = selectCols();
|
||||
|
||||
/** Advisory lock namespace for per-user withdrawal creation. */
|
||||
const USER_CREATE_LOCK_NS = 872_364_301;
|
||||
|
||||
async function withTx<T>(fn: (client: PoolClient) => Promise<T>): Promise<T> {
|
||||
const client = await getClient();
|
||||
try {
|
||||
await beginAuthorizedTransaction(client);
|
||||
const result = await fn(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => undefined);
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function lockRow(client: PoolClient, id: string): Promise<WithdrawalRow | null> {
|
||||
const res = await client.query<WithdrawalRow>(
|
||||
`SELECT ${COLS} FROM transactions WHERE id = $1 AND type = 'withdrawal' FOR UPDATE`,
|
||||
[id]
|
||||
);
|
||||
return res.rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function insertHistory(
|
||||
client: PoolClient,
|
||||
entry: {
|
||||
transactionId: string;
|
||||
fromStatus: string | null;
|
||||
toStatus: string;
|
||||
actor: WithdrawalActor;
|
||||
reason?: string | null;
|
||||
metadata?: Record<string, unknown> | null;
|
||||
}
|
||||
): Promise<void> {
|
||||
await client.query(
|
||||
`INSERT INTO withdrawal_status_history
|
||||
(transaction_id, from_status, to_status, actor_type, actor_user_id, reason, metadata)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
[
|
||||
entry.transactionId,
|
||||
entry.fromStatus,
|
||||
entry.toStatus,
|
||||
entry.actor.actorType,
|
||||
entry.actor.actorUserId ?? null,
|
||||
entry.reason ?? null,
|
||||
entry.metadata ? JSON.stringify(entry.metadata) : null,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
export class WithdrawalBalanceError extends Error {
|
||||
readonly code = 'INSUFFICIENT_BALANCE';
|
||||
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'WithdrawalBalanceError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a pending withdrawal and reserves `amount + fee` on the user's main ledger account
|
||||
* in one transaction. Serialized per user; a repeated idempotency key returns the original row.
|
||||
*/
|
||||
export async function createWithdrawalRequest(input: {
|
||||
userId: string;
|
||||
walletTypeId: number;
|
||||
amountRaw: bigint;
|
||||
feeRaw: bigint;
|
||||
toAddress: string;
|
||||
requiredConfirmations: number;
|
||||
metadata: Record<string, unknown>;
|
||||
pendingReason: WithdrawalPendingReason;
|
||||
idempotencyKey?: string | null;
|
||||
insufficientMessage: string;
|
||||
/** Runs inside the transaction after the per-user lock (e.g. daily limit check). */
|
||||
beforeReserve?: (client: PoolClient) => Promise<void>;
|
||||
}): Promise<{ row: WithdrawalRow; duplicate: boolean }> {
|
||||
return withTx(async (client) => {
|
||||
await client.query('SELECT pg_advisory_xact_lock($1, hashtext($2))', [
|
||||
USER_CREATE_LOCK_NS,
|
||||
input.userId,
|
||||
]);
|
||||
|
||||
if (input.idempotencyKey) {
|
||||
const existing = await client.query<WithdrawalRow>(
|
||||
`SELECT ${COLS} FROM transactions
|
||||
WHERE user_id = $1 AND idempotency_key = $2 AND type = 'withdrawal'`,
|
||||
[input.userId, input.idempotencyKey]
|
||||
);
|
||||
if (existing.rows[0]) return { row: existing.rows[0], duplicate: true };
|
||||
}
|
||||
|
||||
if (input.beforeReserve) await input.beforeReserve(client);
|
||||
|
||||
const totalDebit = input.amountRaw + input.feeRaw;
|
||||
await client.query(
|
||||
`INSERT INTO ledger_accounts (user_id, wallet_type_id, account_kind)
|
||||
VALUES ($1, $2, 'main')
|
||||
ON CONFLICT (user_id, wallet_type_id, account_kind) DO NOTHING`,
|
||||
[input.userId, input.walletTypeId]
|
||||
);
|
||||
const acc = await client.query<{ id: string; available_balance: string; locked_balance: string }>(
|
||||
`SELECT id, available_balance::text, locked_balance::text FROM ledger_accounts
|
||||
WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = 'main'
|
||||
FOR UPDATE`,
|
||||
[input.userId, input.walletTypeId]
|
||||
);
|
||||
const account = acc.rows[0];
|
||||
if (!account) throw new Error('Account not found');
|
||||
const available = BigInt(account.available_balance);
|
||||
const locked = BigInt(account.locked_balance);
|
||||
if (available < totalDebit) throw new WithdrawalBalanceError(input.insufficientMessage);
|
||||
|
||||
await client.query(
|
||||
`UPDATE ledger_accounts SET available_balance = $1, locked_balance = $2, updated_at = NOW()
|
||||
WHERE id = $3`,
|
||||
[(available - totalDebit).toString(), (locked + totalDebit).toString(), account.id]
|
||||
);
|
||||
|
||||
const inserted = await client.query<WithdrawalRow>(
|
||||
`INSERT INTO transactions (
|
||||
user_id, wallet_type_id, type, amount, fee, status, to_address,
|
||||
confirmations, required_confirmations, metadata,
|
||||
withdrawal_flow_version, pending_reason, idempotency_key
|
||||
) VALUES ($1, $2, 'withdrawal', $3, $4, 'pending', $5, 0, $6, $7, $8, $9, $10)
|
||||
RETURNING ${COLS}`,
|
||||
[
|
||||
input.userId,
|
||||
input.walletTypeId,
|
||||
input.amountRaw.toString(),
|
||||
input.feeRaw.toString(),
|
||||
input.toAddress,
|
||||
input.requiredConfirmations,
|
||||
JSON.stringify(input.metadata),
|
||||
WITHDRAWAL_FLOW_VERSION,
|
||||
input.pendingReason,
|
||||
input.idempotencyKey ?? null,
|
||||
]
|
||||
);
|
||||
const row = inserted.rows[0]!;
|
||||
|
||||
await client.query(
|
||||
`INSERT INTO withdrawal_locks (user_id, wallet_type_id, transaction_id, amount)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[input.userId, input.walletTypeId, row.id, totalDebit.toString()]
|
||||
);
|
||||
|
||||
await insertHistory(client, {
|
||||
transactionId: row.id,
|
||||
fromStatus: null,
|
||||
toStatus: 'pending',
|
||||
actor: { actorType: 'user', actorUserId: input.userId },
|
||||
reason: input.pendingReason,
|
||||
});
|
||||
|
||||
return { row, duplicate: false };
|
||||
});
|
||||
}
|
||||
|
||||
/** Merges keys into metadata and optionally updates the pending reason (no status change). */
|
||||
export async function patchPendingDetails(
|
||||
id: string,
|
||||
patch: { metadata?: Record<string, unknown>; pendingReason?: WithdrawalPendingReason }
|
||||
): Promise<void> {
|
||||
await query(
|
||||
`UPDATE transactions
|
||||
SET metadata = COALESCE(metadata, '{}'::jsonb) || $2::jsonb,
|
||||
pending_reason = COALESCE($3, pending_reason),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND type = 'withdrawal'`,
|
||||
[id, JSON.stringify(patch.metadata ?? {}), patch.pendingReason ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* pending|failed -> processing. Refuses rows that already carry a broadcast hash,
|
||||
* legacy rows, and large withdrawals still waiting for the approval quorum.
|
||||
*/
|
||||
export async function claimForProcessing(
|
||||
id: string,
|
||||
actor: WithdrawalActor,
|
||||
opts: { approvalGranted?: boolean } = {}
|
||||
): Promise<WithdrawalOpResult> {
|
||||
return withTx(async (client) => {
|
||||
const current = await lockRow(client, id);
|
||||
if (!current) return { ok: false, code: 'WITHDRAWAL_NOT_FOUND' };
|
||||
if (current.withdrawal_flow_version !== WITHDRAWAL_FLOW_VERSION) {
|
||||
return { ok: false, code: 'WITHDRAWAL_LEGACY_READ_ONLY', status: current.status };
|
||||
}
|
||||
if (!canTransition(current.status, 'processing')) {
|
||||
return { ok: false, code: 'WITHDRAWAL_INVALID_TRANSITION', status: current.status };
|
||||
}
|
||||
if (current.blockchain_tx_id) {
|
||||
return { ok: false, code: 'WITHDRAWAL_ALREADY_BROADCAST', status: current.status };
|
||||
}
|
||||
if (current.pending_reason === 'awaiting_approval' && !opts.approvalGranted) {
|
||||
return { ok: false, code: 'WITHDRAWAL_AWAITING_APPROVAL', status: current.status };
|
||||
}
|
||||
|
||||
const updated = await client.query<WithdrawalRow>(
|
||||
`UPDATE transactions
|
||||
SET status = 'processing',
|
||||
processing_stage = 'claimed',
|
||||
processing_attempts = processing_attempts + 1,
|
||||
processing_started_at = NOW(),
|
||||
processing_actor_id = $2,
|
||||
pending_reason = NULL,
|
||||
last_error = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING ${COLS}`,
|
||||
[id, actor.actorUserId ?? null]
|
||||
);
|
||||
const row = updated.rows[0]!;
|
||||
await insertHistory(client, {
|
||||
transactionId: id,
|
||||
fromStatus: current.status,
|
||||
toStatus: 'processing',
|
||||
actor,
|
||||
metadata: { attempt: row.processing_attempts },
|
||||
});
|
||||
return { ok: true, row, fromStatus: current.status };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* processing|failed -> pending for a temporary problem detected before anything was sent.
|
||||
* `discardUnsentHash` is only for a signed payout the node explicitly refused.
|
||||
*/
|
||||
export async function releaseToPending(
|
||||
id: string,
|
||||
input: {
|
||||
reason: WithdrawalPendingReason;
|
||||
lastError?: string | null;
|
||||
actor: WithdrawalActor;
|
||||
discardUnsentHash?: boolean;
|
||||
}
|
||||
): Promise<WithdrawalOpResult> {
|
||||
return withTx(async (client) => {
|
||||
const current = await lockRow(client, id);
|
||||
if (!current) return { ok: false, code: 'WITHDRAWAL_NOT_FOUND' };
|
||||
if (current.withdrawal_flow_version !== WITHDRAWAL_FLOW_VERSION) {
|
||||
return { ok: false, code: 'WITHDRAWAL_LEGACY_READ_ONLY', status: current.status };
|
||||
}
|
||||
if (!canTransition(current.status, 'pending')) {
|
||||
return { ok: false, code: 'WITHDRAWAL_INVALID_TRANSITION', status: current.status };
|
||||
}
|
||||
if (current.blockchain_tx_id && !input.discardUnsentHash) {
|
||||
return { ok: false, code: 'WITHDRAWAL_ALREADY_BROADCAST', status: current.status };
|
||||
}
|
||||
const updated = await client.query<WithdrawalRow>(
|
||||
`UPDATE transactions
|
||||
SET status = 'pending',
|
||||
pending_reason = $2,
|
||||
processing_stage = NULL,
|
||||
last_error = $3,
|
||||
abandoned_tx_hashes = CASE
|
||||
WHEN blockchain_tx_id IS NULL THEN abandoned_tx_hashes
|
||||
ELSE array_append(COALESCE(abandoned_tx_hashes, ARRAY[]::TEXT[]), blockchain_tx_id)
|
||||
END,
|
||||
blockchain_tx_id = NULL,
|
||||
signed_payload = NULL,
|
||||
signed_expires_at = NULL,
|
||||
broadcast_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING ${COLS}`,
|
||||
[id, input.reason, input.lastError?.slice(0, 2000) ?? null]
|
||||
);
|
||||
await insertHistory(client, {
|
||||
transactionId: id,
|
||||
fromStatus: current.status,
|
||||
toStatus: 'pending',
|
||||
actor: input.actor,
|
||||
reason: input.reason,
|
||||
metadata: input.lastError ? { error: input.lastError } : null,
|
||||
});
|
||||
return { ok: true, row: updated.rows[0]!, fromStatus: current.status };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* processing -> failed once the current attempt is known not to have paid out.
|
||||
* Any attempt hash is archived so a retry signs a fresh transaction.
|
||||
*/
|
||||
export async function failProcessing(
|
||||
id: string,
|
||||
input: { error: string; actor: WithdrawalActor }
|
||||
): Promise<WithdrawalOpResult> {
|
||||
return withTx(async (client) => {
|
||||
const current = await lockRow(client, id);
|
||||
if (!current) return { ok: false, code: 'WITHDRAWAL_NOT_FOUND' };
|
||||
if (!canTransition(current.status, 'failed')) {
|
||||
return { ok: false, code: 'WITHDRAWAL_INVALID_TRANSITION', status: current.status };
|
||||
}
|
||||
const updated = await client.query<WithdrawalRow>(
|
||||
`UPDATE transactions
|
||||
SET status = 'failed',
|
||||
last_error = $2,
|
||||
processing_stage = NULL,
|
||||
abandoned_tx_hashes = CASE
|
||||
WHEN blockchain_tx_id IS NULL THEN abandoned_tx_hashes
|
||||
ELSE array_append(COALESCE(abandoned_tx_hashes, ARRAY[]::TEXT[]), blockchain_tx_id)
|
||||
END,
|
||||
blockchain_tx_id = NULL,
|
||||
signed_payload = NULL,
|
||||
signed_expires_at = NULL,
|
||||
broadcast_at = NULL,
|
||||
confirmations = 0,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING ${COLS}`,
|
||||
[id, input.error.slice(0, 2000)]
|
||||
);
|
||||
await insertHistory(client, {
|
||||
transactionId: id,
|
||||
fromStatus: current.status,
|
||||
toStatus: 'failed',
|
||||
actor: input.actor,
|
||||
reason: input.error.slice(0, 500),
|
||||
metadata: current.blockchain_tx_id ? { abandonedTxHash: current.blockchain_tx_id } : null,
|
||||
});
|
||||
return { ok: true, row: updated.rows[0]!, fromStatus: current.status };
|
||||
});
|
||||
}
|
||||
|
||||
/** Persists the signed payout before broadcast so a lost response can be verified by hash. */
|
||||
export async function recordSignedPayout(
|
||||
id: string,
|
||||
input: { txHash: string; signedPayload: string; expiresAt: Date | null; fromAddress: string }
|
||||
): Promise<boolean> {
|
||||
const rows = await query<{ id: string }[]>(
|
||||
`UPDATE transactions
|
||||
SET blockchain_tx_id = $2,
|
||||
signed_payload = $3,
|
||||
signed_expires_at = $4,
|
||||
from_address = $5,
|
||||
processing_stage = 'signed',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND status = 'processing' AND blockchain_tx_id IS NULL
|
||||
RETURNING id`,
|
||||
[id, input.txHash, input.signedPayload, input.expiresAt, input.fromAddress]
|
||||
);
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
export async function markBroadcast(
|
||||
id: string,
|
||||
input: { stage: 'broadcast' | 'broadcast_uncertain'; lastError?: string | null }
|
||||
): Promise<void> {
|
||||
await query(
|
||||
`UPDATE transactions
|
||||
SET processing_stage = $2,
|
||||
broadcast_at = COALESCE(broadcast_at, NOW()),
|
||||
last_error = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND status = 'processing'`,
|
||||
[id, input.stage, input.lastError ?? null]
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateConfirmations(id: string, confirmations: number): Promise<void> {
|
||||
await query(
|
||||
`UPDATE transactions
|
||||
SET confirmations = $2, processing_stage = 'confirming', updated_at = NOW()
|
||||
WHERE id = $1 AND status = 'processing'`,
|
||||
[id, confirmations]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* processing -> completed after on-chain confirmation: debits the reserved funds
|
||||
* (locked -> gone) with a single ledger entry and releases the reservation row.
|
||||
*/
|
||||
export async function finalizeCompleted(
|
||||
id: string,
|
||||
input: { confirmations: number }
|
||||
): Promise<WithdrawalOpResult> {
|
||||
return withTx(async (client) => {
|
||||
const current = await lockRow(client, id);
|
||||
if (!current) return { ok: false, code: 'WITHDRAWAL_NOT_FOUND' };
|
||||
if (!canTransition(current.status, 'completed') || !current.blockchain_tx_id) {
|
||||
return { ok: false, code: 'WITHDRAWAL_INVALID_TRANSITION', status: current.status };
|
||||
}
|
||||
const totalDebit = BigInt(current.amount) + BigInt(current.fee || '0');
|
||||
|
||||
const acc = await client.query<{ id: string; available_balance: string; locked_balance: string }>(
|
||||
`SELECT id, available_balance::text, locked_balance::text FROM ledger_accounts
|
||||
WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = 'main'
|
||||
FOR UPDATE`,
|
||||
[current.user_id, current.wallet_type_id]
|
||||
);
|
||||
const account = acc.rows[0];
|
||||
if (!account) throw new Error('Ledger account not found for withdrawal');
|
||||
const locked = BigInt(account.locked_balance);
|
||||
if (locked < totalDebit) throw new Error('Locked balance too low to finalize withdrawal');
|
||||
|
||||
await client.query(
|
||||
`UPDATE ledger_accounts SET locked_balance = $1, updated_at = NOW() WHERE id = $2`,
|
||||
[(locked - totalDebit).toString(), account.id]
|
||||
);
|
||||
await client.query(
|
||||
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
||||
VALUES ($1, 'withdrawal', $2, $3, 'transaction', $4)`,
|
||||
[account.id, (-totalDebit).toString(), account.available_balance, id]
|
||||
);
|
||||
await client.query('DELETE FROM withdrawal_locks WHERE transaction_id = $1', [id]);
|
||||
|
||||
const updated = await client.query<WithdrawalRow>(
|
||||
`UPDATE transactions
|
||||
SET status = 'completed',
|
||||
processing_stage = 'confirmed',
|
||||
confirmations = $2,
|
||||
signed_payload = NULL,
|
||||
last_error = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING ${COLS}`,
|
||||
[id, input.confirmations]
|
||||
);
|
||||
await insertHistory(client, {
|
||||
transactionId: id,
|
||||
fromStatus: current.status,
|
||||
toStatus: 'completed',
|
||||
actor: { actorType: 'system' },
|
||||
metadata: { txHash: current.blockchain_tx_id, confirmations: input.confirmations },
|
||||
});
|
||||
return { ok: true, row: updated.rows[0]!, fromStatus: current.status };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* pending|failed -> rejected (admin) or pending -> cancelled (user): returns the full
|
||||
* reservation to available balance exactly once.
|
||||
*/
|
||||
export async function refundWithdrawal(
|
||||
id: string,
|
||||
input: {
|
||||
toStatus: Extract<WithdrawalStatus, 'rejected' | 'cancelled'>;
|
||||
actor: WithdrawalActor;
|
||||
reason?: string | null;
|
||||
/** When set, the row must belong to this user (user-initiated cancel). */
|
||||
ownerUserId?: string;
|
||||
}
|
||||
): Promise<WithdrawalOpResult> {
|
||||
return withTx(async (client) => {
|
||||
const current = await lockRow(client, id);
|
||||
if (!current || (input.ownerUserId && current.user_id !== input.ownerUserId)) {
|
||||
return { ok: false, code: 'WITHDRAWAL_NOT_FOUND' };
|
||||
}
|
||||
if (current.withdrawal_flow_version !== WITHDRAWAL_FLOW_VERSION) {
|
||||
return { ok: false, code: 'WITHDRAWAL_LEGACY_READ_ONLY', status: current.status };
|
||||
}
|
||||
if (!canTransition(current.status, input.toStatus) || current.refunded_at) {
|
||||
return { ok: false, code: 'WITHDRAWAL_INVALID_TRANSITION', status: current.status };
|
||||
}
|
||||
if (current.blockchain_tx_id) {
|
||||
return { ok: false, code: 'WITHDRAWAL_ALREADY_BROADCAST', status: current.status };
|
||||
}
|
||||
|
||||
const totalDebit = BigInt(current.amount) + BigInt(current.fee || '0');
|
||||
const lockRes = await client.query<{ sum: string; n: string }>(
|
||||
`SELECT COALESCE(SUM(amount), 0)::text AS sum, COUNT(*)::text AS n
|
||||
FROM withdrawal_locks WHERE transaction_id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (BigInt(lockRes.rows[0]?.sum ?? '0') !== totalDebit) {
|
||||
throw new Error('Withdrawal reservation mismatch; refusing automatic refund');
|
||||
}
|
||||
|
||||
const acc = await client.query<{ id: string; available_balance: string; locked_balance: string }>(
|
||||
`SELECT id, available_balance::text, locked_balance::text FROM ledger_accounts
|
||||
WHERE user_id = $1 AND wallet_type_id = $2 AND account_kind = 'main'
|
||||
FOR UPDATE`,
|
||||
[current.user_id, current.wallet_type_id]
|
||||
);
|
||||
const account = acc.rows[0];
|
||||
if (!account) throw new Error('Ledger account not found for withdrawal');
|
||||
const locked = BigInt(account.locked_balance);
|
||||
if (locked < totalDebit) throw new Error('Locked balance too low to refund withdrawal');
|
||||
|
||||
await client.query(
|
||||
`UPDATE ledger_accounts SET available_balance = $1, locked_balance = $2, updated_at = NOW()
|
||||
WHERE id = $3`,
|
||||
[
|
||||
(BigInt(account.available_balance) + totalDebit).toString(),
|
||||
(locked - totalDebit).toString(),
|
||||
account.id,
|
||||
]
|
||||
);
|
||||
await client.query('DELETE FROM withdrawal_locks WHERE transaction_id = $1', [id]);
|
||||
|
||||
const refundMeta = {
|
||||
refund: { amount: totalDebit.toString(), refunded_at: new Date().toISOString() },
|
||||
};
|
||||
const updated = await client.query<WithdrawalRow>(
|
||||
`UPDATE transactions
|
||||
SET status = $2,
|
||||
refunded_at = NOW(),
|
||||
rejection_reason = $3,
|
||||
resolved_by = $4,
|
||||
pending_reason = NULL,
|
||||
processing_stage = NULL,
|
||||
metadata = COALESCE(metadata, '{}'::jsonb) || $5::jsonb,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING ${COLS}`,
|
||||
[
|
||||
id,
|
||||
input.toStatus,
|
||||
input.reason?.slice(0, 1000) ?? null,
|
||||
input.actor.actorUserId ?? null,
|
||||
JSON.stringify(refundMeta),
|
||||
]
|
||||
);
|
||||
await insertHistory(client, {
|
||||
transactionId: id,
|
||||
fromStatus: current.status,
|
||||
toStatus: input.toStatus,
|
||||
actor: input.actor,
|
||||
reason: input.reason ?? null,
|
||||
metadata: { refundedAmount: totalDebit.toString() },
|
||||
});
|
||||
return { ok: true, row: updated.rows[0]!, fromStatus: current.status };
|
||||
});
|
||||
}
|
||||
|
||||
export async function findWithdrawal(id: string): Promise<WithdrawalRow | null> {
|
||||
const rows = await query<WithdrawalRow[]>(
|
||||
`SELECT ${COLS} FROM transactions WHERE id = $1 AND type = 'withdrawal'`,
|
||||
[id]
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export type WithdrawalHistoryRow = {
|
||||
id: string;
|
||||
from_status: string | null;
|
||||
to_status: string;
|
||||
actor_type: WithdrawalActorType;
|
||||
actor_user_id: string | null;
|
||||
reason: string | null;
|
||||
metadata: Record<string, unknown> | null;
|
||||
created_at: Date;
|
||||
};
|
||||
|
||||
export async function listHistory(transactionId: string): Promise<WithdrawalHistoryRow[]> {
|
||||
return query<WithdrawalHistoryRow[]>(
|
||||
`SELECT id::text, from_status, to_status, actor_type, actor_user_id, reason, metadata, created_at
|
||||
FROM withdrawal_status_history
|
||||
WHERE transaction_id = $1
|
||||
ORDER BY created_at ASC, id ASC`,
|
||||
[transactionId]
|
||||
);
|
||||
}
|
||||
|
||||
/** Processing rows that already carry a hash and need on-chain verification. */
|
||||
export async function listAwaitingChainResult(limit = 50): Promise<WithdrawalRow[]> {
|
||||
return query<WithdrawalRow[]>(
|
||||
`SELECT ${COLS} FROM transactions
|
||||
WHERE type = 'withdrawal' AND status = 'processing'
|
||||
AND withdrawal_flow_version = $1 AND blockchain_tx_id IS NOT NULL
|
||||
ORDER BY updated_at ASC
|
||||
LIMIT $2`,
|
||||
[WITHDRAWAL_FLOW_VERSION, limit]
|
||||
);
|
||||
}
|
||||
|
||||
/** Processing rows claimed long ago without a signed payout (worker crashed before signing). */
|
||||
export async function listStaleClaims(olderThanMinutes: number): Promise<WithdrawalRow[]> {
|
||||
return query<WithdrawalRow[]>(
|
||||
`SELECT ${COLS} FROM transactions
|
||||
WHERE type = 'withdrawal' AND status = 'processing'
|
||||
AND withdrawal_flow_version = $1 AND blockchain_tx_id IS NULL
|
||||
AND processing_started_at < NOW() - ($2::int * INTERVAL '1 minute')`,
|
||||
[WITHDRAWAL_FLOW_VERSION, olderThanMinutes]
|
||||
);
|
||||
}
|
||||
|
||||
/** Pending rows blocked only by platform liquidity, oldest first (automatic retry). */
|
||||
export async function listAutoRetryCandidates(
|
||||
reasons: WithdrawalPendingReason[],
|
||||
limit: number
|
||||
): Promise<WithdrawalRow[]> {
|
||||
return query<WithdrawalRow[]>(
|
||||
`SELECT ${COLS} FROM transactions
|
||||
WHERE type = 'withdrawal' AND status = 'pending'
|
||||
AND withdrawal_flow_version = $1
|
||||
AND pending_reason = ANY($2::text[])
|
||||
AND blockchain_tx_id IS NULL
|
||||
ORDER BY created_at ASC
|
||||
LIMIT $3`,
|
||||
[WITHDRAWAL_FLOW_VERSION, reasons, limit]
|
||||
);
|
||||
}
|
||||
|
||||
/** Ledger amount of other payouts already broadcast on a network but not yet confirmed. */
|
||||
export async function sumInFlightPayouts(network: string, excludeId: string): Promise<bigint> {
|
||||
const rows = await query<{ sum: string }[]>(
|
||||
`SELECT COALESCE(SUM(amount), 0)::text AS sum FROM transactions
|
||||
WHERE type = 'withdrawal' AND status = 'processing'
|
||||
AND blockchain_tx_id IS NOT NULL
|
||||
AND metadata->>'network' = $1
|
||||
AND id <> $2`,
|
||||
[network, excludeId]
|
||||
);
|
||||
return BigInt(rows[0]?.sum ?? '0');
|
||||
}
|
||||
|
||||
export type AdminWithdrawalFilters = {
|
||||
status?: string;
|
||||
network?: string;
|
||||
from?: Date;
|
||||
to?: Date;
|
||||
minAmountRaw?: bigint;
|
||||
maxAmountRaw?: bigint;
|
||||
emailHash?: string;
|
||||
search?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
export type AdminWithdrawalListRow = WithdrawalRow & {
|
||||
user_email_encrypted: string | null;
|
||||
user_first_name: string | null;
|
||||
user_last_name: string | null;
|
||||
};
|
||||
|
||||
export async function listForAdmin(
|
||||
filters: AdminWithdrawalFilters
|
||||
): Promise<{ items: AdminWithdrawalListRow[]; total: number }> {
|
||||
const where: string[] = [`t.type = 'withdrawal'`];
|
||||
const values: unknown[] = [];
|
||||
const add = (sql: string, value: unknown) => {
|
||||
values.push(value);
|
||||
where.push(sql.replace('?', `$${values.length}`));
|
||||
};
|
||||
|
||||
if (filters.status === 'open') {
|
||||
where.push(`t.status IN ('pending', 'processing', 'failed')`);
|
||||
} else if (filters.status && filters.status !== 'all') {
|
||||
add('t.status = ?', filters.status);
|
||||
}
|
||||
if (filters.network) add(`t.metadata->>'network' = ?`, filters.network);
|
||||
if (filters.from) add('t.created_at >= ?', filters.from);
|
||||
if (filters.to) add('t.created_at <= ?', filters.to);
|
||||
if (filters.minAmountRaw != null) add('t.amount >= ?', filters.minAmountRaw.toString());
|
||||
if (filters.maxAmountRaw != null) add('t.amount <= ?', filters.maxAmountRaw.toString());
|
||||
if (filters.emailHash) add('u.email_hash = ?', filters.emailHash);
|
||||
if (filters.search) {
|
||||
values.push(filters.search);
|
||||
const p = `$${values.length}`;
|
||||
where.push(
|
||||
`(t.id::text = ${p} OR t.user_id::text = ${p} OR lower(t.to_address) = lower(${p}) OR t.blockchain_tx_id = ${p})`
|
||||
);
|
||||
}
|
||||
|
||||
const whereSql = `WHERE ${where.join(' AND ')}`;
|
||||
const limit = Math.min(Math.max(filters.limit ?? 25, 1), 200);
|
||||
const offset = Math.max(filters.offset ?? 0, 0);
|
||||
|
||||
const countRows = await query<{ count: string }[]>(
|
||||
`SELECT COUNT(*)::text AS count FROM transactions t LEFT JOIN users u ON u.id = t.user_id ${whereSql}`,
|
||||
values
|
||||
);
|
||||
const items = await query<AdminWithdrawalListRow[]>(
|
||||
`SELECT ${selectCols('t')},
|
||||
u.email_encrypted AS user_email_encrypted,
|
||||
u.first_name AS user_first_name,
|
||||
u.last_name AS user_last_name
|
||||
FROM transactions t
|
||||
LEFT JOIN users u ON u.id = t.user_id
|
||||
${whereSql}
|
||||
ORDER BY t.created_at DESC
|
||||
LIMIT $${values.length + 1} OFFSET $${values.length + 2}`,
|
||||
[...values, limit, offset]
|
||||
);
|
||||
return { items, total: parseInt(countRows[0]?.count ?? '0', 10) };
|
||||
}
|
||||
|
||||
export async function countOpenByStatus(): Promise<Record<'pending' | 'processing' | 'failed', number>> {
|
||||
const rows = await query<{ status: string; count: string }[]>(
|
||||
`SELECT status, COUNT(*)::text AS count FROM transactions
|
||||
WHERE type = 'withdrawal' AND status IN ('pending', 'processing', 'failed')
|
||||
GROUP BY status`
|
||||
);
|
||||
const out = { pending: 0, processing: 0, failed: 0 };
|
||||
for (const r of rows) {
|
||||
if (r.status === 'pending' || r.status === 'processing' || r.status === 'failed') {
|
||||
out[r.status] = parseInt(r.count, 10);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function countPendingByReason(): Promise<Record<string, number>> {
|
||||
const rows = await query<{ reason: string | null; count: string }[]>(
|
||||
`SELECT pending_reason AS reason, COUNT(*)::text AS count FROM transactions
|
||||
WHERE type = 'withdrawal' AND status = 'pending'
|
||||
GROUP BY pending_reason`
|
||||
);
|
||||
const out: Record<string, number> = {};
|
||||
for (const r of rows) out[r.reason ?? 'queued'] = parseInt(r.count, 10);
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function findFundRequestIdForWithdrawal(transactionId: string): Promise<string | null> {
|
||||
const rows = await query<{ id: string }[]>(
|
||||
`SELECT id FROM fund_operation_requests
|
||||
WHERE operation_type = 'user_withdrawal' AND payload->>'transactionId' = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1`,
|
||||
[transactionId]
|
||||
);
|
||||
return rows[0]?.id ?? null;
|
||||
}
|
||||
@ -13,6 +13,8 @@ import {
|
||||
registerBodySchema,
|
||||
changePasswordBodySchema,
|
||||
withdrawBodySchema,
|
||||
adminWithdrawalRejectBodySchema,
|
||||
adminWithdrawalsListQuerySchema,
|
||||
transferBodySchema,
|
||||
totpEnableBodySchema,
|
||||
totpDisableBodySchema,
|
||||
@ -95,6 +97,7 @@ import {
|
||||
walletTransactionsQuerySchema,
|
||||
uuidParamSchema,
|
||||
alertIdParamSchema,
|
||||
uuidIdParamSchema,
|
||||
} from '../validation/querySchemas';
|
||||
import {
|
||||
apiLimiter,
|
||||
@ -315,6 +318,13 @@ router.post(
|
||||
auditAction('withdrawal_requested', 'wallet'),
|
||||
asyncHandler(withdrawalController.withdraw)
|
||||
);
|
||||
router.post(
|
||||
'/withdrawals/:id/cancel',
|
||||
requireSupportedAppVersion,
|
||||
validateParams(uuidIdParamSchema),
|
||||
auditAction('withdrawal_cancel_requested', 'wallet'),
|
||||
asyncHandler(withdrawalController.cancelOwnWithdrawal)
|
||||
);
|
||||
router.post(
|
||||
'/transfer',
|
||||
requireSupportedAppVersion,
|
||||
@ -447,6 +457,46 @@ router.post(
|
||||
validateBody(fundRequestCreateBodySchema),
|
||||
fundApprovalController.createFundRequest
|
||||
);
|
||||
router.get(
|
||||
'/admin/withdrawals',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.withdrawals.view'),
|
||||
validateQuery(adminWithdrawalsListQuerySchema),
|
||||
asyncHandler(withdrawalController.adminListWithdrawals)
|
||||
);
|
||||
router.get(
|
||||
'/admin/withdrawals/:id',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.withdrawals.view'),
|
||||
validateParams(uuidIdParamSchema),
|
||||
asyncHandler(withdrawalController.adminGetWithdrawal)
|
||||
);
|
||||
router.post(
|
||||
'/admin/withdrawals/:id/process',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.withdrawals.manage'),
|
||||
validateParams(uuidIdParamSchema),
|
||||
auditAction('admin_withdrawal_process', 'withdrawal'),
|
||||
asyncHandler(withdrawalController.adminProcessWithdrawal)
|
||||
);
|
||||
router.post(
|
||||
'/admin/withdrawals/:id/requeue',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.withdrawals.manage'),
|
||||
validateParams(uuidIdParamSchema),
|
||||
auditAction('admin_withdrawal_requeue', 'withdrawal'),
|
||||
asyncHandler(withdrawalController.adminRequeueWithdrawal)
|
||||
);
|
||||
router.post(
|
||||
'/admin/withdrawals/:id/reject',
|
||||
requireRoles('admin'),
|
||||
requirePermissions('admin.withdrawals.manage'),
|
||||
validateParams(uuidIdParamSchema),
|
||||
validateBody(adminWithdrawalRejectBodySchema),
|
||||
auditAction('admin_withdrawal_reject', 'withdrawal'),
|
||||
asyncHandler(withdrawalController.adminRejectWithdrawal)
|
||||
);
|
||||
|
||||
router.get('/admin/fund-requests', requireRoles('admin'), requirePermissions('fund_operation.request'), fundApprovalController.listFundRequests);
|
||||
router.get('/admin/fund-requests/:id', requireRoles('admin'), requirePermissions('fund_operation.request'), fundApprovalController.getFundRequest);
|
||||
router.post(
|
||||
|
||||
@ -378,6 +378,109 @@ export async function sendUsdt(
|
||||
return receipt.hash;
|
||||
}
|
||||
|
||||
/** Signed BEP20 payout whose hash is known before it is broadcast. */
|
||||
export type SignedBscTransfer = {
|
||||
txHash: string;
|
||||
/** Serialized signed transaction (re-broadcastable as-is). */
|
||||
payload: string;
|
||||
fromAddress: string;
|
||||
nonce: number;
|
||||
};
|
||||
|
||||
function walletFor(fromPrivateKeyHex: string): ethers.Wallet {
|
||||
return new ethers.Wallet(
|
||||
fromPrivateKeyHex.startsWith('0x') ? fromPrivateKeyHex : '0x' + fromPrivateKeyHex,
|
||||
getProvider()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds (nonce, gas) and signs a USDT BEP20 `transfer` without broadcasting it.
|
||||
* Gas estimation reverts when the hot wallet lacks USDT and fails with INSUFFICIENT_FUNDS
|
||||
* when it lacks BNB — both before anything is sent.
|
||||
*/
|
||||
export async function signUsdtTransfer(
|
||||
fromPrivateKeyHex: string,
|
||||
contractAddress: string,
|
||||
toAddress: string,
|
||||
amountRaw: bigint
|
||||
): Promise<SignedBscTransfer> {
|
||||
const wallet = walletFor(fromPrivateKeyHex);
|
||||
const iface = new ethers.Interface(ERC20_ABI);
|
||||
const populated = await wallet.populateTransaction({
|
||||
to: resolveUsdtContract(contractAddress),
|
||||
data: iface.encodeFunctionData('transfer', [ethers.getAddress(toAddress), amountRaw]),
|
||||
});
|
||||
const payload = await wallet.signTransaction(populated);
|
||||
const parsed = ethers.Transaction.from(payload);
|
||||
if (!parsed.hash) throw new Error('Could not compute BSC transaction hash');
|
||||
return { txHash: parsed.hash, payload, fromAddress: wallet.address, nonce: parsed.nonce };
|
||||
}
|
||||
|
||||
export type BscFailureClass = 'gas' | 'usdt' | 'rejected' | 'uncertain';
|
||||
|
||||
/**
|
||||
* Classifies an ethers error raised while estimating or broadcasting a payout.
|
||||
* `uncertain` = transport problem: the transaction may or may not have reached the network.
|
||||
*/
|
||||
export function classifyBscError(err: unknown): BscFailureClass {
|
||||
const code = String((err as { code?: string })?.code ?? '');
|
||||
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
||||
if (code === 'INSUFFICIENT_FUNDS' || /insufficient funds/.test(msg)) return 'gas';
|
||||
if (code === 'CALL_EXCEPTION' || /execution reverted|transfer amount exceeds balance/.test(msg)) {
|
||||
return 'usdt';
|
||||
}
|
||||
if (
|
||||
code === 'NONCE_EXPIRED' ||
|
||||
code === 'REPLACEMENT_UNDERPRICED' ||
|
||||
code === 'INVALID_ARGUMENT' ||
|
||||
code === 'TRANSACTION_REPLACED' ||
|
||||
/nonce too low|replacement transaction underpriced|invalid sender/.test(msg)
|
||||
) {
|
||||
return 'rejected';
|
||||
}
|
||||
return 'uncertain';
|
||||
}
|
||||
|
||||
export function isAlreadyKnownBroadcastError(err: unknown): boolean {
|
||||
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
||||
return /already known|known transaction/.test(msg);
|
||||
}
|
||||
|
||||
/** Broadcasts a previously signed transaction. Throws on any RPC error (caller classifies). */
|
||||
export async function broadcastSignedTransaction(payload: string): Promise<void> {
|
||||
await getProvider().broadcastTransaction(payload);
|
||||
}
|
||||
|
||||
export type BscTxStatus =
|
||||
| { kind: 'not_found' }
|
||||
| { kind: 'pending' }
|
||||
| { kind: 'mined'; success: boolean; confirmations: number };
|
||||
|
||||
export async function getPayoutTxStatus(txHash: string): Promise<BscTxStatus> {
|
||||
const p = getProvider();
|
||||
const receipt = await p.getTransactionReceipt(txHash);
|
||||
if (receipt) {
|
||||
const current = await p.getBlockNumber();
|
||||
return {
|
||||
kind: 'mined',
|
||||
success: receipt.status === 1,
|
||||
confirmations: Math.max(0, current - receipt.blockNumber + 1),
|
||||
};
|
||||
}
|
||||
const tx = await p.getTransaction(txHash);
|
||||
return tx ? { kind: 'pending' } : { kind: 'not_found' };
|
||||
}
|
||||
|
||||
/** Next nonce already consumed on-chain by `address` (mined transactions only). */
|
||||
export async function getConfirmedNonce(address: string): Promise<number> {
|
||||
return getProvider().getTransactionCount(address, 'latest');
|
||||
}
|
||||
|
||||
export function nonceOfSignedPayload(payload: string): number {
|
||||
return ethers.Transaction.from(payload).nonce;
|
||||
}
|
||||
|
||||
export async function getNativeBalanceWei(address: string): Promise<bigint> {
|
||||
return getProvider().getBalance(address);
|
||||
}
|
||||
|
||||
@ -275,6 +275,150 @@ export async function sendTrc20(fromPrivateKeyHex: string, contractAddress: stri
|
||||
return result?.transaction?.txID || result?.txid || String(result);
|
||||
}
|
||||
|
||||
/** Signed TRC20 payout whose txID is known before it is broadcast. */
|
||||
export type SignedTronTransfer = {
|
||||
txId: string;
|
||||
/** JSON of the signed transaction (re-broadcastable as-is until expiration). */
|
||||
payload: string;
|
||||
expiresAt: Date;
|
||||
fromAddress: string;
|
||||
};
|
||||
|
||||
type TronTxBuilderExt = {
|
||||
triggerSmartContract(
|
||||
contractAddress: string,
|
||||
functionSelector: string,
|
||||
options: { feeLimit: number },
|
||||
parameters: Array<{ type: string; value: string }>,
|
||||
issuerAddress: string
|
||||
): Promise<{ result?: { result?: boolean }; transaction?: { txID: string } }>;
|
||||
extendExpiration(tx: unknown, extensionSeconds: number): Promise<{ txID: string }>;
|
||||
};
|
||||
|
||||
type TronTrxExt = {
|
||||
sign(tx: unknown, privateKey: string): Promise<{ txID: string; raw_data?: { expiration?: number } }>;
|
||||
sendRawTransaction(signed: unknown): Promise<{
|
||||
result?: boolean;
|
||||
txid?: string;
|
||||
code?: string;
|
||||
message?: string;
|
||||
}>;
|
||||
getUnconfirmedTransactionInfo(txId: string): Promise<{
|
||||
id?: string;
|
||||
blockNumber?: number;
|
||||
result?: string;
|
||||
receipt?: { result?: string };
|
||||
resMessage?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
/** Lets a signed payout be re-broadcast after a lost response before TRON drops it. */
|
||||
const PAYOUT_EXPIRATION_EXTENSION_SECONDS = 600;
|
||||
|
||||
/**
|
||||
* Builds and signs a TRC20 `transfer` without broadcasting it.
|
||||
*/
|
||||
export async function signTrc20Transfer(
|
||||
fromPrivateKeyHex: string,
|
||||
contractAddress: string,
|
||||
toAddress: string,
|
||||
amountRaw: bigint
|
||||
): Promise<SignedTronTransfer> {
|
||||
const tronWeb = getTronWeb();
|
||||
const builder = tronWeb.transactionBuilder as unknown as TronTxBuilderExt;
|
||||
const trx = tronWeb.trx as unknown as TronTrxExt;
|
||||
const fromRaw = tronWeb.address.fromPrivateKey(fromPrivateKeyHex.replace(/^0x/, ''));
|
||||
const fromAddress = typeof fromRaw === 'string' ? fromRaw : fromRaw.base58 ?? '';
|
||||
if (!fromAddress) throw new Error('Could not derive TRON hot wallet address');
|
||||
|
||||
const built = await builder.triggerSmartContract(
|
||||
contractAddress,
|
||||
'transfer(address,uint256)',
|
||||
{ feeLimit: 100_000_000 },
|
||||
[
|
||||
{ type: 'address', value: toAddress },
|
||||
{ type: 'uint256', value: amountRaw.toString() },
|
||||
],
|
||||
fromAddress
|
||||
);
|
||||
if (!built?.result?.result || !built.transaction) {
|
||||
throw new Error('TRON node refused to build the TRC20 transfer');
|
||||
}
|
||||
const extended = await builder.extendExpiration(
|
||||
built.transaction,
|
||||
PAYOUT_EXPIRATION_EXTENSION_SECONDS
|
||||
);
|
||||
const signed = await trx.sign(extended, fromPrivateKeyHex.replace(/^0x/, ''));
|
||||
const expirationMs = signed.raw_data?.expiration ?? Date.now() + 60_000;
|
||||
return {
|
||||
txId: signed.txID,
|
||||
payload: JSON.stringify(signed),
|
||||
expiresAt: new Date(expirationMs),
|
||||
fromAddress,
|
||||
};
|
||||
}
|
||||
|
||||
export type TronBroadcastResult =
|
||||
| { kind: 'accepted' }
|
||||
| { kind: 'rejected'; code: string; message: string };
|
||||
|
||||
function decodeTronMessage(message: string | undefined): string {
|
||||
if (!message) return '';
|
||||
if (/^[0-9a-fA-F]+$/.test(message) && message.length % 2 === 0) {
|
||||
try {
|
||||
return Buffer.from(message, 'hex').toString('utf8');
|
||||
} catch {
|
||||
return message;
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interprets a `sendRawTransaction` response. A response with an error code means the node
|
||||
* refused the transaction (it was not accepted); DUP_TRANSACTION_ERROR means it is already known.
|
||||
*/
|
||||
export function classifyTronBroadcastResponse(res: {
|
||||
result?: boolean;
|
||||
code?: string;
|
||||
message?: string;
|
||||
}): TronBroadcastResult {
|
||||
if (res?.result === true) return { kind: 'accepted' };
|
||||
const code = String(res?.code ?? 'UNKNOWN');
|
||||
if (code === 'DUP_TRANSACTION_ERROR') return { kind: 'accepted' };
|
||||
return { kind: 'rejected', code, message: decodeTronMessage(res?.message) };
|
||||
}
|
||||
|
||||
/** Broadcasts a previously signed payload. Throws only on transport errors (outcome unknown). */
|
||||
export async function broadcastSignedTransaction(payload: string): Promise<TronBroadcastResult> {
|
||||
const tronWeb = getTronWeb();
|
||||
const trx = tronWeb.trx as unknown as TronTrxExt;
|
||||
const res = await trx.sendRawTransaction(JSON.parse(payload));
|
||||
return classifyTronBroadcastResponse(res);
|
||||
}
|
||||
|
||||
export type TronTxStatus =
|
||||
| { kind: 'not_found' }
|
||||
| { kind: 'mined'; success: boolean; confirmations: number; message?: string };
|
||||
|
||||
/** Looks a payout up by txID on the full node (includes not-yet-solidified blocks). */
|
||||
export async function getTransactionStatus(txId: string): Promise<TronTxStatus> {
|
||||
const tronWeb = getTronWeb();
|
||||
const trx = tronWeb.trx as unknown as TronTrxExt;
|
||||
const info = await trx.getUnconfirmedTransactionInfo(txId);
|
||||
if (!info || typeof info.blockNumber !== 'number') return { kind: 'not_found' };
|
||||
const current = await getCurrentBlock();
|
||||
const confirmations = Math.max(0, current - info.blockNumber + 1);
|
||||
const receiptResult = info.receipt?.result;
|
||||
const success = info.result !== 'FAILED' && (receiptResult === undefined || receiptResult === 'SUCCESS');
|
||||
return {
|
||||
kind: 'mined',
|
||||
success,
|
||||
confirmations,
|
||||
message: success ? undefined : decodeTronMessage(info.resMessage) || receiptResult || info.result,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns native TRX balance in sun for an address.
|
||||
*/
|
||||
|
||||
@ -44,6 +44,7 @@ const TABLE_BASE_SEVERITY: Record<string, SecurityAlertSeverity> = {
|
||||
exchange_funding: 'high',
|
||||
system_settings: 'medium',
|
||||
withdrawal_locks: 'medium',
|
||||
withdrawal_status_history: 'medium',
|
||||
deposit_scanner_state: 'medium',
|
||||
security_alerts: 'high',
|
||||
refresh_tokens: 'medium',
|
||||
|
||||
@ -629,37 +629,54 @@ export async function sendWithdrawalCompletedEmail(
|
||||
);
|
||||
}
|
||||
|
||||
/** Withdrawal failed or cancelled; funds returned. */
|
||||
/** Technical problem during payout: the request is kept and will be reviewed (no refund). */
|
||||
export async function sendWithdrawalFailedEmail(
|
||||
to: string,
|
||||
p: WalletEmailPayload
|
||||
): Promise<void> {
|
||||
const reason = p.reason?.trim();
|
||||
const lines = [
|
||||
'Your withdrawal could not be completed. The reserved amount was returned to your available balance.',
|
||||
'',
|
||||
`Amount: ${p.amountUsdt} USDT`,
|
||||
];
|
||||
const message =
|
||||
'Processing of your withdrawal ran into a technical problem. Your request remains registered and will be reviewed.';
|
||||
const lines = [message, '', `Amount: ${p.amountUsdt} USDT`];
|
||||
if (p.toAddressMasked) lines.push(`Destination: ${p.toAddressMasked}`);
|
||||
if (reason) lines.push(`Reason: ${reason}`);
|
||||
lines.push('', `Time: ${new Date().toISOString()}`);
|
||||
|
||||
const reasonHtml = reason ? `<p><strong>Reason:</strong> ${reason}</p>` : '';
|
||||
const destHtml = p.toAddressMasked
|
||||
? `<li><strong>Destination:</strong> ${p.toAddressMasked}</li>`
|
||||
: '';
|
||||
|
||||
await sendUserWalletEmail(
|
||||
to,
|
||||
'Your Tloto withdrawal could not be completed',
|
||||
'Withdrawal failed',
|
||||
'Your Tloto withdrawal is under review',
|
||||
'Withdrawal under review',
|
||||
lines,
|
||||
`<p>Your withdrawal could not be completed. Funds were returned to your available balance.</p>
|
||||
`<p>${message}</p>
|
||||
<ul style="font-size:14px;line-height:1.6;">
|
||||
<li><strong>Amount:</strong> ${p.amountUsdt} USDT</li>
|
||||
${destHtml}
|
||||
</ul>
|
||||
${reasonHtml}
|
||||
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
|
||||
);
|
||||
}
|
||||
|
||||
/** Withdrawal declined by an admin or cancelled by the user: reserved amount credited back. */
|
||||
export async function sendWithdrawalRefundedEmail(
|
||||
to: string,
|
||||
p: { kind: 'rejected' | 'cancelled'; refundedUsdt: string }
|
||||
): Promise<void> {
|
||||
const message =
|
||||
p.kind === 'rejected'
|
||||
? 'Your withdrawal request was declined. The corresponding amount has been credited back to your account.'
|
||||
: 'Your withdrawal request was cancelled. The corresponding amount has been credited back to your account.';
|
||||
const title = p.kind === 'rejected' ? 'Withdrawal declined' : 'Withdrawal cancelled';
|
||||
await sendUserWalletEmail(
|
||||
to,
|
||||
p.kind === 'rejected' ? 'Your Tloto withdrawal was declined' : 'Your Tloto withdrawal was cancelled',
|
||||
title,
|
||||
[message, '', `Credited back: ${p.refundedUsdt} USDT`, '', `Time: ${new Date().toISOString()}`],
|
||||
`<p>${message}</p>
|
||||
<ul style="font-size:14px;line-height:1.6;">
|
||||
<li><strong>Credited back:</strong> ${p.refundedUsdt} USDT</li>
|
||||
</ul>
|
||||
<p style="font-size:13px;color:#666;">Time: ${new Date().toISOString()}</p>`
|
||||
);
|
||||
}
|
||||
|
||||
@ -274,9 +274,9 @@ export async function executeApprovedRequest(
|
||||
});
|
||||
}
|
||||
case 'user_withdrawal': {
|
||||
const { broadcastApprovedWithdrawal } = await import('./withdrawalService');
|
||||
const { processApprovedWithdrawal } = await import('./withdrawalService');
|
||||
const { transactionId } = request.payload as { transactionId: string };
|
||||
return broadcastApprovedWithdrawal(transactionId, approvedBy);
|
||||
return processApprovedWithdrawal(transactionId, approvedBy);
|
||||
}
|
||||
case 'approval_policy_change': {
|
||||
return applyPolicyChangeFromRequest(request, approvedBy);
|
||||
@ -515,8 +515,12 @@ export async function castVote(
|
||||
if (existing.operation_type === 'user_withdrawal') {
|
||||
const { transactionId } = existing.payload as { transactionId?: string };
|
||||
if (transactionId) {
|
||||
const { abandonPendingWithdrawal } = await import('./withdrawalService');
|
||||
await abandonPendingWithdrawal(transactionId, trimmed);
|
||||
const { rejectWithdrawal } = await import('./withdrawalService');
|
||||
await rejectWithdrawal(transactionId, {
|
||||
actorId: voterId,
|
||||
reason: trimmed,
|
||||
source: 'approval',
|
||||
}).catch((e) => console.error('[fund-approval] withdrawal rejection/refund failed:', e));
|
||||
}
|
||||
}
|
||||
await auditLogRepository.create({
|
||||
@ -650,8 +654,8 @@ export async function cancelFundRequest(
|
||||
if (existing.operation_type === 'user_withdrawal') {
|
||||
const { transactionId } = existing.payload as { transactionId?: string };
|
||||
if (transactionId) {
|
||||
const { abandonPendingWithdrawal } = await import('./withdrawalService');
|
||||
await abandonPendingWithdrawal(transactionId, 'cancelled');
|
||||
const { cancelWithdrawalFromApproval } = await import('./withdrawalService');
|
||||
await cancelWithdrawalFromApproval(transactionId, actorId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -74,6 +74,32 @@ export function evaluateHotLiquidity(input: {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
export type HotBalances = { usdtBalanceRaw: bigint; nativeBalanceRaw: bigint };
|
||||
|
||||
/** Reads on-chain USDT (chain units) and native gas balances of a hot wallet. */
|
||||
export async function readHotBalances(params: {
|
||||
network: 'TRON' | 'BSC';
|
||||
hotAddress: string;
|
||||
usdtContract: string;
|
||||
}): Promise<HotBalances> {
|
||||
const { network, hotAddress, usdtContract } = params;
|
||||
if (network === 'TRON') {
|
||||
const contract = config.blockchain.tron.usdtTrc20Contract || usdtContract;
|
||||
if (!contract) throw new Error('USDT TRC20 contract not configured');
|
||||
const [usdtBalanceRaw, nativeBalanceRaw] = await Promise.all([
|
||||
tronService.getTrc20BalanceRaw(hotAddress, contract),
|
||||
tronService.getTrxBalanceSun(hotAddress),
|
||||
]);
|
||||
return { usdtBalanceRaw, nativeBalanceRaw };
|
||||
}
|
||||
const contract = bscService.resolveUsdtContract(usdtContract);
|
||||
const [usdtBalanceRaw, nativeBalanceRaw] = await Promise.all([
|
||||
bscService.getUsdtBalanceRaw(hotAddress, contract),
|
||||
bscService.getNativeBalanceWei(hotAddress),
|
||||
]);
|
||||
return { usdtBalanceRaw, nativeBalanceRaw };
|
||||
}
|
||||
|
||||
function liquidityError(message: string): Error & { code: string } {
|
||||
const err = new Error(message) as Error & { code: string };
|
||||
err.code = 'HOT_WALLET_INSUFFICIENT_LIQUIDITY';
|
||||
|
||||
@ -178,6 +178,16 @@ function validateUpdates(updates: Partial<SystemSettings>): void {
|
||||
|
||||
}
|
||||
|
||||
if (updates.withdrawal_auto_retry_interval_minutes !== undefined) {
|
||||
|
||||
updates.withdrawal_auto_retry_interval_minutes = clampInt(
|
||||
updates.withdrawal_auto_retry_interval_minutes,
|
||||
1,
|
||||
1440
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
if (updates.transfer_min_remaining_usdt_micro !== undefined) {
|
||||
|
||||
updates.transfer_min_remaining_usdt_micro = clampInt(
|
||||
@ -431,6 +441,14 @@ export function parseSettingsUpdates(body: Record<string, unknown>): Partial<Sys
|
||||
|
||||
}
|
||||
|
||||
if (typeof body.withdrawal_auto_retry_enabled === 'boolean') {
|
||||
updates.withdrawal_auto_retry_enabled = body.withdrawal_auto_retry_enabled;
|
||||
}
|
||||
|
||||
if (typeof body.withdrawal_auto_retry_interval_minutes === 'number') {
|
||||
updates.withdrawal_auto_retry_interval_minutes = body.withdrawal_auto_retry_interval_minutes;
|
||||
}
|
||||
|
||||
if (typeof body.require_admin_2fa === 'boolean') {
|
||||
|
||||
updates.require_admin_2fa = body.require_admin_2fa;
|
||||
|
||||
@ -66,7 +66,21 @@ function amountLabel(amountRaw: bigint | string, feeRaw?: bigint | string): {
|
||||
return { amount, fee, total };
|
||||
}
|
||||
|
||||
/** Withdrawal submitted (awaiting approval / processing). */
|
||||
/** User-facing withdrawal copy. Never mentions platform liquidity, hot wallets or gas. */
|
||||
export const WITHDRAWAL_MESSAGES = {
|
||||
pending:
|
||||
'Your withdrawal request has been registered. It will be processed as soon as possible.',
|
||||
processing: 'Your withdrawal request is currently being processed.',
|
||||
completed: 'Your withdrawal was completed successfully.',
|
||||
failed:
|
||||
'Processing of your withdrawal ran into a technical problem. Your request remains registered and will be reviewed.',
|
||||
rejected:
|
||||
'Your withdrawal request was declined. The corresponding amount has been credited back to your account.',
|
||||
cancelled:
|
||||
'Your withdrawal request was cancelled. The corresponding amount has been credited back to your account.',
|
||||
} as const;
|
||||
|
||||
/** Withdrawal request recorded (status Pending). */
|
||||
export async function notifyWithdrawalSubmitted(
|
||||
userId: string,
|
||||
data: {
|
||||
@ -80,14 +94,12 @@ export async function notifyWithdrawalSubmitted(
|
||||
): Promise<void> {
|
||||
const { amount, fee, total } = amountLabel(data.amountRaw, data.feeRaw);
|
||||
const dest = maskAddress(data.toAddress);
|
||||
const statusNote = data.pendingApproval
|
||||
? 'Your withdrawal is pending review before it is sent on-chain.'
|
||||
: 'Your withdrawal request was received and is being processed.';
|
||||
const statusNote = WITHDRAWAL_MESSAGES.pending;
|
||||
void recordInAppNotification({
|
||||
userId,
|
||||
eventType: 'withdrawal_submitted',
|
||||
title: 'Withdrawal submitted',
|
||||
body: `${amount} USDT to ${dest}${data.pendingApproval ? ' (pending review)' : ''}.`,
|
||||
title: 'Withdrawal request registered',
|
||||
body: `${WITHDRAWAL_MESSAGES.pending} (${amount} USDT to ${dest})`,
|
||||
metadata: {
|
||||
transactionId: data.transactionId,
|
||||
amount,
|
||||
@ -132,7 +144,7 @@ export async function notifyWithdrawalCompleted(
|
||||
userId,
|
||||
eventType: 'withdrawal_completed',
|
||||
title: 'Withdrawal completed',
|
||||
body: `${amount} USDT was sent to ${dest}.`,
|
||||
body: `${WITHDRAWAL_MESSAGES.completed} (${amount} USDT to ${dest})`,
|
||||
metadata: {
|
||||
transactionId: data.transactionId,
|
||||
amount,
|
||||
@ -158,7 +170,21 @@ export async function notifyWithdrawalCompleted(
|
||||
}
|
||||
}
|
||||
|
||||
/** Withdrawal failed / cancelled (funds unlocked). */
|
||||
/** Payout attempt started (in-app only, to avoid email noise right before completion). */
|
||||
export async function notifyWithdrawalProcessing(
|
||||
userId: string,
|
||||
data: { transactionId: string }
|
||||
): Promise<void> {
|
||||
await recordInAppNotification({
|
||||
userId,
|
||||
eventType: 'withdrawal_processing',
|
||||
title: 'Withdrawal in progress',
|
||||
body: WITHDRAWAL_MESSAGES.processing,
|
||||
metadata: { transactionId: data.transactionId },
|
||||
});
|
||||
}
|
||||
|
||||
/** Technical failure: the request is kept (funds stay reserved) and will be reviewed. */
|
||||
export async function notifyWithdrawalFailed(
|
||||
userId: string,
|
||||
data: {
|
||||
@ -166,7 +192,6 @@ export async function notifyWithdrawalFailed(
|
||||
feeRaw?: bigint | string;
|
||||
toAddress?: string;
|
||||
transactionId: string;
|
||||
reason?: string;
|
||||
}
|
||||
): Promise<void> {
|
||||
const { amount } = amountLabel(data.amountRaw, data.feeRaw);
|
||||
@ -174,15 +199,9 @@ export async function notifyWithdrawalFailed(
|
||||
void recordInAppNotification({
|
||||
userId,
|
||||
eventType: 'withdrawal_failed',
|
||||
title: 'Withdrawal failed',
|
||||
body: dest
|
||||
? `Your withdrawal of ${amount} USDT to ${dest} could not be completed. Funds were returned to your balance.`
|
||||
: `Your withdrawal of ${amount} USDT could not be completed. Funds were returned to your balance.`,
|
||||
metadata: {
|
||||
transactionId: data.transactionId,
|
||||
amount,
|
||||
reason: data.reason ?? null,
|
||||
},
|
||||
title: 'Withdrawal under review',
|
||||
body: `${WITHDRAWAL_MESSAGES.failed} (${amount} USDT${dest ? ` to ${dest}` : ''})`,
|
||||
metadata: { transactionId: data.transactionId, amount },
|
||||
});
|
||||
const email = await resolveUserEmail(userId);
|
||||
if (!email) return;
|
||||
@ -190,13 +209,50 @@ export async function notifyWithdrawalFailed(
|
||||
await emailService.sendWithdrawalFailedEmail(email, {
|
||||
amountUsdt: amount,
|
||||
toAddressMasked: dest,
|
||||
reason: data.reason,
|
||||
});
|
||||
} catch (e) {
|
||||
logNotifyError('withdrawal failed email', e);
|
||||
}
|
||||
}
|
||||
|
||||
async function notifyWithdrawalRefunded(
|
||||
userId: string,
|
||||
kind: 'rejected' | 'cancelled',
|
||||
data: { amountRaw: bigint | string; feeRaw: bigint | string; transactionId: string }
|
||||
): Promise<void> {
|
||||
const { total } = amountLabel(data.amountRaw, data.feeRaw);
|
||||
void recordInAppNotification({
|
||||
userId,
|
||||
eventType: kind === 'rejected' ? 'withdrawal_rejected' : 'withdrawal_cancelled',
|
||||
title: kind === 'rejected' ? 'Withdrawal declined — refunded' : 'Withdrawal cancelled — refunded',
|
||||
body: `${WITHDRAWAL_MESSAGES[kind]} (${total} USDT)`,
|
||||
metadata: { transactionId: data.transactionId, refunded: total },
|
||||
});
|
||||
const email = await resolveUserEmail(userId);
|
||||
if (!email) return;
|
||||
try {
|
||||
await emailService.sendWithdrawalRefundedEmail(email, { kind, refundedUsdt: total! });
|
||||
} catch (e) {
|
||||
logNotifyError(`withdrawal ${kind} email`, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Admin refusal: full reservation credited back. */
|
||||
export async function notifyWithdrawalRejected(
|
||||
userId: string,
|
||||
data: { amountRaw: bigint | string; feeRaw: bigint | string; transactionId: string }
|
||||
): Promise<void> {
|
||||
await notifyWithdrawalRefunded(userId, 'rejected', data);
|
||||
}
|
||||
|
||||
/** User cancellation of a pending request: full reservation credited back. */
|
||||
export async function notifyWithdrawalCancelled(
|
||||
userId: string,
|
||||
data: { amountRaw: bigint | string; feeRaw: bigint | string; transactionId: string }
|
||||
): Promise<void> {
|
||||
await notifyWithdrawalRefunded(userId, 'cancelled', data);
|
||||
}
|
||||
|
||||
/** Peer transfer sent (sender). */
|
||||
export async function notifyTransferSent(
|
||||
userId: string,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
234
backend/src/services/withdrawals/withdrawalAdminService.ts
Normal file
234
backend/src/services/withdrawals/withdrawalAdminService.ts
Normal file
@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Admin view of withdrawal requests: list, counters, detail with status history and a
|
||||
* live hot-wallet liquidity check for the request's network.
|
||||
*/
|
||||
|
||||
import { decrypt, hashForIndex } from '../../utils/crypto';
|
||||
import * as withdrawalRepository from '../../repositories/withdrawalRepository';
|
||||
import type { AdminWithdrawalFilters, WithdrawalRow } from '../../repositories/withdrawalRepository';
|
||||
import * as walletRepository from '../../repositories/walletRepository';
|
||||
import * as hotWalletRepository from '../../repositories/hotWalletRepository';
|
||||
import * as settingsRepository from '../../repositories/settingsRepository';
|
||||
import { evaluateHotLiquidity, readHotBalances } from '../hotLiquidityService';
|
||||
import { WITHDRAWAL_FLOW_VERSION, canTransition } from './withdrawalStateMachine';
|
||||
|
||||
function safeDecrypt(value: string | null): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
return decrypt(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type AdminWithdrawalDto = {
|
||||
id: string;
|
||||
userId: string;
|
||||
userEmail: string | null;
|
||||
userName: string | null;
|
||||
amount: string;
|
||||
fee: string;
|
||||
totalDebited: string;
|
||||
currency: 'USDT';
|
||||
network: string | null;
|
||||
railWalletType: string | null;
|
||||
toAddress: string | null;
|
||||
status: string;
|
||||
pendingReason: string | null;
|
||||
processingStage: string | null;
|
||||
attempts: number;
|
||||
lastError: string | null;
|
||||
blockchainTxId: string | null;
|
||||
abandonedTxHashes: string[];
|
||||
confirmations: number;
|
||||
requiredConfirmations: number | null;
|
||||
rejectionReason: string | null;
|
||||
refundedAt: string | null;
|
||||
fundRequestId: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
legacy: boolean;
|
||||
actions: { canProcess: boolean; canRequeue: boolean; canReject: boolean };
|
||||
};
|
||||
|
||||
function toDto(
|
||||
row: WithdrawalRow & {
|
||||
user_email_encrypted?: string | null;
|
||||
user_first_name?: string | null;
|
||||
user_last_name?: string | null;
|
||||
}
|
||||
): AdminWithdrawalDto {
|
||||
const legacy = row.withdrawal_flow_version !== WITHDRAWAL_FLOW_VERSION;
|
||||
const awaitingApproval = row.pending_reason === 'awaiting_approval';
|
||||
const name = [row.user_first_name, row.user_last_name].filter(Boolean).join(' ').trim();
|
||||
return {
|
||||
id: row.id,
|
||||
userId: row.user_id,
|
||||
userEmail: safeDecrypt(row.user_email_encrypted ?? null),
|
||||
userName: name || null,
|
||||
amount: row.amount,
|
||||
fee: row.fee,
|
||||
totalDebited: (BigInt(row.amount) + BigInt(row.fee || '0')).toString(),
|
||||
currency: 'USDT',
|
||||
network: (row.metadata?.network as string | undefined) ?? null,
|
||||
railWalletType: (row.metadata?.rail_wallet_type as string | undefined) ?? null,
|
||||
toAddress: row.to_address,
|
||||
status: row.status,
|
||||
pendingReason: row.status === 'pending' ? row.pending_reason ?? 'queued' : null,
|
||||
processingStage: row.status === 'processing' ? row.processing_stage : null,
|
||||
attempts: row.processing_attempts ?? 0,
|
||||
lastError: row.last_error,
|
||||
blockchainTxId: row.blockchain_tx_id,
|
||||
abandonedTxHashes: row.abandoned_tx_hashes ?? [],
|
||||
confirmations: row.confirmations ?? 0,
|
||||
requiredConfirmations: row.required_confirmations,
|
||||
rejectionReason: row.rejection_reason,
|
||||
refundedAt: row.refunded_at ? new Date(row.refunded_at).toISOString() : null,
|
||||
fundRequestId: (row.metadata?.fund_request_id as string | undefined) ?? null,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
updatedAt: new Date(row.updated_at).toISOString(),
|
||||
legacy,
|
||||
actions: {
|
||||
canProcess:
|
||||
!legacy && canTransition(row.status, 'processing') && !row.blockchain_tx_id && !awaitingApproval,
|
||||
canRequeue: !legacy && row.status === 'failed',
|
||||
canReject: !legacy && canTransition(row.status, 'rejected') && !row.blockchain_tx_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type AdminWithdrawalQuery = {
|
||||
status?: string;
|
||||
network?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
minAmount?: string;
|
||||
maxAmount?: string;
|
||||
search?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
};
|
||||
|
||||
function parseRawAmount(value: string | undefined): bigint | undefined {
|
||||
if (!value || !/^\d+$/.test(value.trim())) return undefined;
|
||||
return BigInt(value.trim());
|
||||
}
|
||||
|
||||
function parseDate(value: string | undefined): Date | undefined {
|
||||
if (!value) return undefined;
|
||||
const d = new Date(value);
|
||||
return Number.isNaN(d.getTime()) ? undefined : d;
|
||||
}
|
||||
|
||||
export async function listWithdrawals(q: AdminWithdrawalQuery) {
|
||||
const search = q.search?.trim();
|
||||
const filters: AdminWithdrawalFilters = {
|
||||
status: q.status || 'open',
|
||||
network: q.network || undefined,
|
||||
from: parseDate(q.from),
|
||||
to: parseDate(q.to),
|
||||
minAmountRaw: parseRawAmount(q.minAmount),
|
||||
maxAmountRaw: parseRawAmount(q.maxAmount),
|
||||
limit: q.limit,
|
||||
offset: q.offset,
|
||||
};
|
||||
if (search) {
|
||||
if (search.includes('@')) filters.emailHash = hashForIndex(search.toLowerCase());
|
||||
else filters.search = search;
|
||||
}
|
||||
const [{ items, total }, counts, pendingReasons, settings] = await Promise.all([
|
||||
withdrawalRepository.listForAdmin(filters),
|
||||
withdrawalRepository.countOpenByStatus(),
|
||||
withdrawalRepository.countPendingByReason(),
|
||||
settingsRepository.getSettings(),
|
||||
]);
|
||||
return {
|
||||
items: items.map(toDto),
|
||||
total,
|
||||
counts,
|
||||
pendingReasons,
|
||||
autoRetry: {
|
||||
enabled: settings.withdrawal_auto_retry_enabled,
|
||||
intervalMinutes: settings.withdrawal_auto_retry_interval_minutes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type LiquiditySnapshot = {
|
||||
network: string;
|
||||
hotAddress: string | null;
|
||||
usdtBalanceRaw: string | null;
|
||||
nativeBalanceRaw: string | null;
|
||||
inFlightLedgerRaw: string;
|
||||
canPay: boolean;
|
||||
shortfall: 'usdt' | 'gas' | 'no_hot_wallet' | null;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
async function liquidityFor(row: WithdrawalRow): Promise<LiquiditySnapshot | null> {
|
||||
const network = row.metadata?.network;
|
||||
const rail = row.metadata?.rail_wallet_type;
|
||||
if ((network !== 'TRON' && network !== 'BSC') || typeof rail !== 'string') return null;
|
||||
const inFlight = await withdrawalRepository.sumInFlightPayouts(network, row.id);
|
||||
const base: LiquiditySnapshot = {
|
||||
network,
|
||||
hotAddress: null,
|
||||
usdtBalanceRaw: null,
|
||||
nativeBalanceRaw: null,
|
||||
inFlightLedgerRaw: inFlight.toString(),
|
||||
canPay: false,
|
||||
shortfall: null,
|
||||
};
|
||||
const walletType = await walletRepository.getWalletTypeByCode(rail);
|
||||
const hot = walletType ? await hotWalletRepository.getActiveHotWallet(walletType.id) : null;
|
||||
if (!walletType || !hot) return { ...base, shortfall: 'no_hot_wallet' };
|
||||
try {
|
||||
const balances = await readHotBalances({
|
||||
network,
|
||||
hotAddress: hot.address,
|
||||
usdtContract: walletType.contract_address || '',
|
||||
});
|
||||
const verdict = evaluateHotLiquidity({
|
||||
network,
|
||||
usdtBalanceRaw: balances.usdtBalanceRaw,
|
||||
nativeBalanceRaw: balances.nativeBalanceRaw,
|
||||
ledgerAmountRaw: BigInt(row.amount) + inFlight,
|
||||
});
|
||||
return {
|
||||
...base,
|
||||
hotAddress: hot.address,
|
||||
usdtBalanceRaw: balances.usdtBalanceRaw.toString(),
|
||||
nativeBalanceRaw: balances.nativeBalanceRaw.toString(),
|
||||
canPay: verdict.ok,
|
||||
shortfall: verdict.ok ? null : verdict.reason,
|
||||
};
|
||||
} catch (e) {
|
||||
return { ...base, hotAddress: hot.address, error: e instanceof Error ? e.message : String(e) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function getWithdrawalDetail(id: string) {
|
||||
const rows = await withdrawalRepository.listForAdmin({ search: id, status: 'all', limit: 1 });
|
||||
const row = rows.items.find((r) => r.id === id);
|
||||
if (!row) return null;
|
||||
const [history, liquidity] = await Promise.all([
|
||||
withdrawalRepository.listHistory(id),
|
||||
row.status === 'pending' || row.status === 'failed' ? liquidityFor(row) : Promise.resolve(null),
|
||||
]);
|
||||
return {
|
||||
withdrawal: toDto(row),
|
||||
history: history.map((h) => ({
|
||||
id: h.id,
|
||||
fromStatus: h.from_status,
|
||||
toStatus: h.to_status,
|
||||
actorType: h.actor_type,
|
||||
actorUserId: h.actor_user_id,
|
||||
reason: h.reason,
|
||||
metadata: h.metadata,
|
||||
createdAt: new Date(h.created_at).toISOString(),
|
||||
})),
|
||||
liquidity,
|
||||
};
|
||||
}
|
||||
|
||||
export { toDto as toAdminWithdrawalDto };
|
||||
193
backend/src/services/withdrawals/withdrawalPayoutService.ts
Normal file
193
backend/src/services/withdrawals/withdrawalPayoutService.ts
Normal file
@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Network adapter for withdrawal payouts: sign (hash known up front), broadcast,
|
||||
* and look the payout up by hash. All decisions about statuses live in withdrawalService.
|
||||
*/
|
||||
|
||||
import { config } from '../../config';
|
||||
import * as tronService from '../blockchain/tronService';
|
||||
import * as bscService from '../blockchain/bscService';
|
||||
import { BEP20_USDT_DECIMALS, scaleLedgerToChain } from '../../utils/usdtUnits';
|
||||
|
||||
export type PayoutNetwork = 'TRON' | 'BSC';
|
||||
|
||||
export type SignedPayout = {
|
||||
network: PayoutNetwork;
|
||||
txHash: string;
|
||||
payload: string;
|
||||
expiresAt: Date | null;
|
||||
fromAddress: string;
|
||||
};
|
||||
|
||||
/** `liquidity` failures happen before anything is sent and keep the request pending. */
|
||||
export type PayoutFailureKind = 'liquidity_usdt' | 'liquidity_gas' | 'rejected' | 'uncertain' | 'technical';
|
||||
|
||||
export class PayoutError extends Error {
|
||||
readonly kind: PayoutFailureKind;
|
||||
|
||||
constructor(kind: PayoutFailureKind, message: string) {
|
||||
super(message);
|
||||
this.name = 'PayoutError';
|
||||
this.kind = kind;
|
||||
}
|
||||
}
|
||||
|
||||
export async function signPayout(input: {
|
||||
network: PayoutNetwork;
|
||||
privateKey: string;
|
||||
usdtContract: string;
|
||||
toAddress: string;
|
||||
ledgerAmountRaw: bigint;
|
||||
}): Promise<SignedPayout> {
|
||||
if (input.network === 'TRON') {
|
||||
const contract = config.blockchain.tron.usdtTrc20Contract || input.usdtContract;
|
||||
if (!contract) throw new PayoutError('technical', 'USDT TRC20 contract not configured');
|
||||
const signed = await tronService.signTrc20Transfer(
|
||||
input.privateKey,
|
||||
contract,
|
||||
input.toAddress,
|
||||
input.ledgerAmountRaw
|
||||
);
|
||||
return {
|
||||
network: 'TRON',
|
||||
txHash: signed.txId,
|
||||
payload: signed.payload,
|
||||
expiresAt: signed.expiresAt,
|
||||
fromAddress: signed.fromAddress,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const signed = await bscService.signUsdtTransfer(
|
||||
input.privateKey,
|
||||
bscService.resolveUsdtContract(input.usdtContract),
|
||||
input.toAddress,
|
||||
scaleLedgerToChain(input.ledgerAmountRaw, BEP20_USDT_DECIMALS)
|
||||
);
|
||||
return {
|
||||
network: 'BSC',
|
||||
txHash: signed.txHash,
|
||||
payload: signed.payload,
|
||||
expiresAt: null,
|
||||
fromAddress: signed.fromAddress,
|
||||
};
|
||||
} catch (e) {
|
||||
const cls = bscService.classifyBscError(e);
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (cls === 'gas') throw new PayoutError('liquidity_gas', msg);
|
||||
if (cls === 'usdt') throw new PayoutError('liquidity_usdt', msg);
|
||||
throw new PayoutError('technical', msg);
|
||||
}
|
||||
}
|
||||
|
||||
export type BroadcastOutcome =
|
||||
| { kind: 'accepted' }
|
||||
| { kind: 'not_sent'; failure: Exclude<PayoutFailureKind, 'uncertain' | 'technical'>; message: string }
|
||||
| { kind: 'uncertain'; message: string };
|
||||
|
||||
const TRON_GAS_REJECTION = /balance is not sufficient|account resource insufficient|not enough energy|bandwidth/i;
|
||||
|
||||
/** Maps a TRON node refusal to a failure kind (nothing reached the chain). */
|
||||
export function classifyTronRejection(code: string, message: string): 'liquidity_gas' | 'rejected' {
|
||||
if (code === 'BANDWITH_ERROR' || TRON_GAS_REJECTION.test(message)) return 'liquidity_gas';
|
||||
return 'rejected';
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcasts a signed payout. A transport error never counts as failure: we first check
|
||||
* whether the hash reached the network, otherwise the outcome stays `uncertain`.
|
||||
*/
|
||||
export async function broadcastPayout(signed: SignedPayout): Promise<BroadcastOutcome> {
|
||||
if (signed.network === 'TRON') {
|
||||
try {
|
||||
const res = await tronService.broadcastSignedTransaction(signed.payload);
|
||||
if (res.kind === 'accepted') return { kind: 'accepted' };
|
||||
return {
|
||||
kind: 'not_sent',
|
||||
failure: classifyTronRejection(res.code, res.message),
|
||||
message: `${res.code}: ${res.message}`.slice(0, 500),
|
||||
};
|
||||
} catch (e) {
|
||||
return resolveTransportError(signed, e);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await bscService.broadcastSignedTransaction(signed.payload);
|
||||
return { kind: 'accepted' };
|
||||
} catch (e) {
|
||||
if (bscService.isAlreadyKnownBroadcastError(e)) return { kind: 'accepted' };
|
||||
const cls = bscService.classifyBscError(e);
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (cls === 'uncertain') return resolveTransportError(signed, e);
|
||||
// Refused by the node, but double-check it is not already on-chain (e.g. nonce too low).
|
||||
const status = await getPayoutStatus(signed.network, signed.txHash).catch(() => null);
|
||||
if (status && status.kind !== 'not_found') return { kind: 'accepted' };
|
||||
const failure = cls === 'gas' ? 'liquidity_gas' : cls === 'usdt' ? 'liquidity_usdt' : 'rejected';
|
||||
return { kind: 'not_sent', failure, message: msg.slice(0, 500) };
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveTransportError(signed: SignedPayout, err: unknown): Promise<BroadcastOutcome> {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const status = await getPayoutStatus(signed.network, signed.txHash).catch(() => null);
|
||||
if (status && status.kind !== 'not_found') return { kind: 'accepted' };
|
||||
return { kind: 'uncertain', message: msg.slice(0, 500) };
|
||||
}
|
||||
|
||||
export type PayoutChainStatus =
|
||||
| { kind: 'not_found' }
|
||||
| { kind: 'pending' }
|
||||
| { kind: 'mined'; success: boolean; confirmations: number; message?: string };
|
||||
|
||||
export async function getPayoutStatus(network: PayoutNetwork, txHash: string): Promise<PayoutChainStatus> {
|
||||
if (network === 'TRON') return tronService.getTransactionStatus(txHash);
|
||||
return bscService.getPayoutTxStatus(txHash);
|
||||
}
|
||||
|
||||
/** Re-sends the exact same signed payload (same hash): safe, cannot pay twice. */
|
||||
export async function rebroadcastPayout(network: PayoutNetwork, payload: string): Promise<void> {
|
||||
if (network === 'TRON') {
|
||||
await tronService.broadcastSignedTransaction(payload);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await bscService.broadcastSignedTransaction(payload);
|
||||
} catch (e) {
|
||||
if (!bscService.isAlreadyKnownBroadcastError(e)) throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export type MissingTxDecision = 'wait' | 'rebroadcast' | 'dropped';
|
||||
|
||||
/** Grace period before a missing BSC payout whose nonce was consumed is declared dropped. */
|
||||
export const BSC_DROP_GRACE_MS = 10 * 60_000;
|
||||
/** Margin after TRON expiration before declaring the payout dropped. */
|
||||
export const TRON_EXPIRY_MARGIN_MS = 2 * 60_000;
|
||||
|
||||
/**
|
||||
* What to do when a broadcast payout is not visible on-chain.
|
||||
* TRON: a signed tx is void after its expiration. BSC: void once its nonce is used by another tx.
|
||||
*/
|
||||
export function decideMissingPayout(input: {
|
||||
network: PayoutNetwork;
|
||||
nowMs: number;
|
||||
broadcastAtMs: number | null;
|
||||
expiresAtMs: number | null;
|
||||
nonceConsumed?: boolean;
|
||||
}): MissingTxDecision {
|
||||
if (input.network === 'TRON') {
|
||||
if (input.expiresAtMs != null && input.nowMs > input.expiresAtMs + TRON_EXPIRY_MARGIN_MS) {
|
||||
return 'dropped';
|
||||
}
|
||||
return 'rebroadcast';
|
||||
}
|
||||
const since = input.broadcastAtMs != null ? input.nowMs - input.broadcastAtMs : 0;
|
||||
if (input.nonceConsumed && since > BSC_DROP_GRACE_MS) return 'dropped';
|
||||
if (input.nonceConsumed) return 'wait';
|
||||
return 'rebroadcast';
|
||||
}
|
||||
|
||||
export async function isBscNonceConsumed(fromAddress: string, payload: string): Promise<boolean> {
|
||||
const confirmedNonce = await bscService.getConfirmedNonce(fromAddress);
|
||||
return confirmedNonce > bscService.nonceOfSignedPayload(payload);
|
||||
}
|
||||
95
backend/src/services/withdrawals/withdrawalStateMachine.ts
Normal file
95
backend/src/services/withdrawals/withdrawalStateMachine.ts
Normal file
@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Withdrawal lifecycle rules (single source of truth for web, mobile and admin).
|
||||
*
|
||||
* Funds are reserved (ledger available -> locked) when the request is created and stay
|
||||
* locked until the payout is confirmed on-chain (completed) or the request is rejected /
|
||||
* cancelled (refund). `failed` keeps the reservation so the request can be retried.
|
||||
*/
|
||||
|
||||
export const WITHDRAWAL_STATUSES = [
|
||||
'pending',
|
||||
'processing',
|
||||
'completed',
|
||||
'failed',
|
||||
'rejected',
|
||||
'cancelled',
|
||||
] as const;
|
||||
|
||||
export type WithdrawalStatus = (typeof WITHDRAWAL_STATUSES)[number];
|
||||
|
||||
/** Terminal status for legacy rows whose funds were already returned by the old flow. */
|
||||
export const LEGACY_REFUNDED_STATUS = 'failed_refunded';
|
||||
|
||||
export const WITHDRAWAL_FLOW_VERSION = 2;
|
||||
|
||||
/** Allowed `from -> to` transitions. Anything not listed is refused by the backend. */
|
||||
export const WITHDRAWAL_TRANSITIONS: Readonly<Record<WithdrawalStatus, readonly WithdrawalStatus[]>> = {
|
||||
pending: ['processing', 'rejected', 'cancelled'],
|
||||
processing: ['completed', 'pending', 'failed'],
|
||||
failed: ['processing', 'pending', 'rejected'],
|
||||
completed: [],
|
||||
rejected: [],
|
||||
cancelled: [],
|
||||
};
|
||||
|
||||
/** Why a request is still pending. Internal only — never shown to end users. */
|
||||
export type WithdrawalPendingReason =
|
||||
| 'queued'
|
||||
| 'awaiting_approval'
|
||||
| 'awaiting_liquidity'
|
||||
| 'awaiting_gas'
|
||||
| 'hot_wallet_unavailable'
|
||||
| 'processing_interrupted'
|
||||
| 'requeued_by_admin'
|
||||
| 'account_on_hold';
|
||||
|
||||
export type WithdrawalActorType = 'user' | 'admin' | 'system';
|
||||
|
||||
export function isWithdrawalStatus(value: string): value is WithdrawalStatus {
|
||||
return (WITHDRAWAL_STATUSES as readonly string[]).includes(value);
|
||||
}
|
||||
|
||||
export function canTransition(from: string, to: WithdrawalStatus): boolean {
|
||||
if (!isWithdrawalStatus(from)) return false;
|
||||
return WITHDRAWAL_TRANSITIONS[from].includes(to);
|
||||
}
|
||||
|
||||
/** Statuses a row may currently have for `to` to be a legal next status. */
|
||||
export function allowedFromStatuses(to: WithdrawalStatus): WithdrawalStatus[] {
|
||||
return WITHDRAWAL_STATUSES.filter((from) => WITHDRAWAL_TRANSITIONS[from].includes(to));
|
||||
}
|
||||
|
||||
export function isTerminalWithdrawalStatus(status: string): boolean {
|
||||
return (
|
||||
status === 'completed' ||
|
||||
status === 'rejected' ||
|
||||
status === 'cancelled' ||
|
||||
status === LEGACY_REFUNDED_STATUS
|
||||
);
|
||||
}
|
||||
|
||||
export type WithdrawalErrorCode =
|
||||
| 'WITHDRAWAL_NOT_FOUND'
|
||||
| 'WITHDRAWAL_INVALID_TRANSITION'
|
||||
| 'WITHDRAWAL_LEGACY_READ_ONLY'
|
||||
| 'WITHDRAWAL_AWAITING_APPROVAL'
|
||||
| 'WITHDRAWAL_ALREADY_BROADCAST';
|
||||
|
||||
export class WithdrawalStateError extends Error {
|
||||
readonly code: WithdrawalErrorCode;
|
||||
|
||||
constructor(code: WithdrawalErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = 'WithdrawalStateError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function assertTransition(from: string, to: WithdrawalStatus): void {
|
||||
if (!canTransition(from, to)) {
|
||||
throw new WithdrawalStateError(
|
||||
'WITHDRAWAL_INVALID_TRANSITION',
|
||||
`Withdrawal cannot move from ${from} to ${to}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -40,6 +40,7 @@ describe('walletNotificationService', () => {
|
||||
'sendWithdrawalSubmittedEmail',
|
||||
'sendWithdrawalCompletedEmail',
|
||||
'sendWithdrawalFailedEmail',
|
||||
'sendWithdrawalRefundedEmail',
|
||||
'sendTransferSentEmail',
|
||||
'sendTransferReceivedEmail',
|
||||
] as const;
|
||||
@ -120,7 +121,8 @@ describe('walletNotificationService', () => {
|
||||
|
||||
assert.equal(inAppCalls.length, 1);
|
||||
assert.equal(inAppCalls[0].eventType, 'withdrawal_submitted');
|
||||
assert.match(inAppCalls[0].body || '', /pending review/i);
|
||||
assert.match(inAppCalls[0].body || '', /has been registered/i);
|
||||
assert.doesNotMatch(inAppCalls[0].body || '', /hot wallet|liquidit|gas/i);
|
||||
assert.match(inAppCalls[0].body || '', /TXYZab…ABCD|TXYZab…/);
|
||||
assert.equal(inAppCalls[0].metadata?.amount, '5');
|
||||
assert.equal(inAppCalls[0].metadata?.fee, '0.5');
|
||||
@ -158,13 +160,52 @@ describe('walletNotificationService', () => {
|
||||
feeRaw: 500_000n,
|
||||
toAddress: 'TShortAddrOnly',
|
||||
transactionId: 'tx-fail-1',
|
||||
reason: 'hot wallet empty',
|
||||
})
|
||||
);
|
||||
assert.equal(inAppCalls.length, 0);
|
||||
assert.equal(emailCalls.length, 1);
|
||||
assert.equal(emailCalls[0].fn, 'sendWithdrawalFailedEmail');
|
||||
assert.equal(emailCalls[0].payload.reason, 'hot wallet empty');
|
||||
assert.equal(emailCalls[0].payload.reason, undefined);
|
||||
});
|
||||
|
||||
test('withdrawal messages never expose platform liquidity internals', () => {
|
||||
for (const text of Object.values(walletNotify.WITHDRAWAL_MESSAGES)) {
|
||||
assert.doesNotMatch(text, /hot wallet|liquidit|gas|insufficient/i);
|
||||
}
|
||||
});
|
||||
|
||||
test('withdrawal rejected / cancelled: in-app + refund email', async () => {
|
||||
installStubs();
|
||||
await walletNotify.notifyWithdrawalRejected('user-1', {
|
||||
amountRaw: 10_000_000n,
|
||||
feeRaw: 1_000_000n,
|
||||
transactionId: 'tx-rej-1',
|
||||
});
|
||||
await walletNotify.notifyWithdrawalCancelled('user-1', {
|
||||
amountRaw: 3_000_000n,
|
||||
feeRaw: 1_000_000n,
|
||||
transactionId: 'tx-can-1',
|
||||
});
|
||||
assert.deepEqual(
|
||||
inAppCalls.map((c) => c.eventType),
|
||||
['withdrawal_rejected', 'withdrawal_cancelled']
|
||||
);
|
||||
assert.match(inAppCalls[0].body || '', /credited back/);
|
||||
assert.equal(inAppCalls[0].metadata?.refunded, '11');
|
||||
assert.deepEqual(
|
||||
emailCalls.map((c) => [c.fn, c.payload.kind, c.payload.refundedUsdt]),
|
||||
[
|
||||
['sendWithdrawalRefundedEmail', 'rejected', '11'],
|
||||
['sendWithdrawalRefundedEmail', 'cancelled', '4'],
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('withdrawal processing: in-app only', async () => {
|
||||
installStubs();
|
||||
await walletNotify.notifyWithdrawalProcessing('user-1', { transactionId: 'tx-p-1' });
|
||||
assert.equal(inAppCalls[0].eventType, 'withdrawal_processing');
|
||||
assert.equal(emailCalls.length, 0);
|
||||
});
|
||||
|
||||
test('transfer sent + received: masks emails and notifies both sides', async () => {
|
||||
@ -235,7 +276,12 @@ describe('walletNotificationService', () => {
|
||||
emailService.sendWithdrawalFailedEmail('test@example.com', {
|
||||
amountUsdt: '1',
|
||||
toAddressMasked: 'TXYZab…ABCD',
|
||||
reason: 'rejected',
|
||||
})
|
||||
);
|
||||
await assert.doesNotReject(() =>
|
||||
emailService.sendWithdrawalRefundedEmail('test@example.com', {
|
||||
kind: 'rejected',
|
||||
refundedUsdt: '1.5',
|
||||
})
|
||||
);
|
||||
await assert.doesNotReject(() =>
|
||||
@ -256,13 +302,19 @@ describe('walletNotificationService', () => {
|
||||
describe('wallet notify wiring', () => {
|
||||
const servicesDir = path.join(__dirname, '../services');
|
||||
|
||||
test('withdrawalService hooks submitted / completed / failed', () => {
|
||||
test('withdrawalService hooks every status notification', () => {
|
||||
const src = fs.readFileSync(path.join(servicesDir, 'withdrawalService.js'), 'utf8');
|
||||
assert.match(src, /walletNotificationService/);
|
||||
assert.match(src, /notifyWithdrawalSubmitted/);
|
||||
assert.match(src, /notifyWithdrawalCompleted/);
|
||||
assert.match(src, /notifyWithdrawalFailed/);
|
||||
assert.match(src, /pendingApproval:\s*true/);
|
||||
for (const fn of [
|
||||
'notifyWithdrawalSubmitted',
|
||||
'notifyWithdrawalProcessing',
|
||||
'notifyWithdrawalCompleted',
|
||||
'notifyWithdrawalFailed',
|
||||
'notifyWithdrawalRejected',
|
||||
'notifyWithdrawalCancelled',
|
||||
]) {
|
||||
assert.match(src, new RegExp(fn));
|
||||
}
|
||||
});
|
||||
|
||||
test('transferService hooks sent + received for both users', () => {
|
||||
|
||||
668
backend/src/tests/withdrawalLifecycle.db.test.ts
Normal file
668
backend/src/tests/withdrawalLifecycle.db.test.ts
Normal file
@ -0,0 +1,668 @@
|
||||
/**
|
||||
* Withdrawal state machine v2 against a real PostgreSQL database.
|
||||
* Blockchain + hot-wallet balances are stubbed; ledger, locks and row-level concurrency are real.
|
||||
* Run with RUN_DB_TESTS=1 and DATABASE_URL pointing to a disposable database.
|
||||
*/
|
||||
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
import { query, runMigrations } from '../db/connection';
|
||||
import { ensureTestMigrations, isDbTestEnabled } from './helpers/testDb';
|
||||
import { encrypt } from '../utils/crypto';
|
||||
import * as settingsRepository from '../repositories/settingsRepository';
|
||||
import * as hotWalletRepository from '../repositories/hotWalletRepository';
|
||||
import * as withdrawalRepository from '../repositories/withdrawalRepository';
|
||||
import * as authService from '../services/authService';
|
||||
import * as hotLiquidityService from '../services/hotLiquidityService';
|
||||
import * as payout from '../services/withdrawals/withdrawalPayoutService';
|
||||
import type {
|
||||
BroadcastOutcome,
|
||||
PayoutChainStatus,
|
||||
SignedPayout,
|
||||
} from '../services/withdrawals/withdrawalPayoutService';
|
||||
import * as walletNotificationService from '../services/walletNotificationService';
|
||||
import * as referralService from '../services/referralService';
|
||||
import * as userAdminStatsService from '../services/userAdminStatsService';
|
||||
import * as securityService from '../services/securityService';
|
||||
import * as withdrawalService from '../services/withdrawalService';
|
||||
|
||||
const dbDescribe = isDbTestEnabled() ? describe : describe.skip;
|
||||
|
||||
const USDT = 1_000_000n;
|
||||
const FEE = 1n * USDT;
|
||||
const TRON_DEST = `T${'A'.repeat(33)}`;
|
||||
|
||||
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
|
||||
const patch = <T extends object>(mod: T) => mod as Mutable<T> & Record<string, unknown>;
|
||||
|
||||
const chain = {
|
||||
usdt: 0n,
|
||||
native: 0n,
|
||||
signCalls: 0,
|
||||
broadcastCalls: 0,
|
||||
rebroadcastCalls: 0,
|
||||
signError: null as Error | null,
|
||||
broadcastOutcome: { kind: 'accepted' } as BroadcastOutcome,
|
||||
statuses: new Map<string, PayoutChainStatus>(),
|
||||
expiresInMs: 60_000,
|
||||
lastHash: '',
|
||||
autoRetryEnabled: false,
|
||||
};
|
||||
const notifications: Array<{ fn: string; userId: string }> = [];
|
||||
let referralCalls = 0;
|
||||
let walletTypeId = 0;
|
||||
|
||||
function resetChain() {
|
||||
chain.usdt = 1_000_000n * USDT;
|
||||
chain.native = 10n ** 20n;
|
||||
chain.signCalls = 0;
|
||||
chain.broadcastCalls = 0;
|
||||
chain.rebroadcastCalls = 0;
|
||||
chain.signError = null;
|
||||
chain.broadcastOutcome = { kind: 'accepted' };
|
||||
chain.expiresInMs = 60_000;
|
||||
chain.autoRetryEnabled = false;
|
||||
notifications.length = 0;
|
||||
referralCalls = 0;
|
||||
}
|
||||
|
||||
async function createFundedUser(availableUsdt: bigint): Promise<string> {
|
||||
const id = crypto.randomUUID();
|
||||
await query(
|
||||
`INSERT INTO users (id, email_hash, password_hash, role_id) VALUES ($1, $2, 'test-hash', 1)`,
|
||||
[id, crypto.createHash('sha256').update(id).digest('hex')]
|
||||
);
|
||||
const acc = await query<{ id: string }[]>(
|
||||
`INSERT INTO ledger_accounts (user_id, wallet_type_id, account_kind, available_balance, locked_balance)
|
||||
VALUES ($1, $2, 'main', $3, 0) RETURNING id`,
|
||||
[id, walletTypeId, (availableUsdt * USDT).toString()]
|
||||
);
|
||||
await query(
|
||||
`INSERT INTO ledger_entries (account_id, type, amount, balance_after, reference_type, reference_id)
|
||||
VALUES ($1, 'deposit', $2, $2, 'test', $3)`,
|
||||
[acc[0]!.id, (availableUsdt * USDT).toString(), id]
|
||||
);
|
||||
return id;
|
||||
}
|
||||
|
||||
async function balances(userId: string) {
|
||||
const rows = await query<{ available: string; locked: string; entries: string }[]>(
|
||||
`SELECT a.available_balance::text AS available, a.locked_balance::text AS locked,
|
||||
COALESCE((SELECT SUM(e.amount) FROM ledger_entries e WHERE e.account_id = a.id), 0)::text AS entries
|
||||
FROM ledger_accounts a
|
||||
WHERE a.user_id = $1 AND a.wallet_type_id = $2 AND a.account_kind = 'main'`,
|
||||
[userId, walletTypeId]
|
||||
);
|
||||
const r = rows[0]!;
|
||||
const available = BigInt(r.available);
|
||||
const locked = BigInt(r.locked);
|
||||
// Ledger integrity invariant used by the platform monitor.
|
||||
assert.equal(available + locked, BigInt(r.entries), 'available + locked must equal ledger entries');
|
||||
return { available, locked };
|
||||
}
|
||||
|
||||
async function locksFor(txId: string): Promise<bigint> {
|
||||
const rows = await query<{ s: string }[]>(
|
||||
`SELECT COALESCE(SUM(amount), 0)::text AS s FROM withdrawal_locks WHERE transaction_id = $1`,
|
||||
[txId]
|
||||
);
|
||||
return BigInt(rows[0]!.s);
|
||||
}
|
||||
|
||||
async function historyOf(txId: string): Promise<string[]> {
|
||||
const rows = await withdrawalRepository.listHistory(txId);
|
||||
return rows.map((h) => `${h.from_status ?? '∅'}>${h.to_status}`);
|
||||
}
|
||||
|
||||
async function submit(userId: string, amountUsdt: bigint, key?: string) {
|
||||
return withdrawalService.requestWithdrawal(userId, 'USDT_TRC20', TRON_DEST, amountUsdt * USDT, undefined, {
|
||||
autoProcess: false,
|
||||
idempotencyKey: key,
|
||||
});
|
||||
}
|
||||
|
||||
const ADMIN = { actorType: 'admin' as const, actorUserId: null };
|
||||
|
||||
async function expectCode(p: Promise<unknown>, code: string) {
|
||||
await assert.rejects(p, (e: unknown) => {
|
||||
assert.equal((e as { code?: string }).code, code);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
dbDescribe('withdrawal lifecycle v2 (database)', () => {
|
||||
before(async () => {
|
||||
await ensureTestMigrations();
|
||||
const wt = await query<{ id: number }[]>(`SELECT id FROM wallet_types WHERE code = 'USDT_TRC20'`);
|
||||
walletTypeId = wt[0]!.id;
|
||||
|
||||
const realGetSettings = settingsRepository.getSettings;
|
||||
patch(settingsRepository).getSettings = async () => ({
|
||||
...(await realGetSettings()),
|
||||
allow_withdrawals: true,
|
||||
network_usdt_trc20_withdraw_enabled: true,
|
||||
network_usdt_bep20_withdraw_enabled: true,
|
||||
daily_withdrawal_limit_usd: 1_000_000,
|
||||
large_withdrawal_threshold_usd: 1_000_000,
|
||||
withdrawal_network_fee_usdt_micro: Number(FEE),
|
||||
withdrawal_auto_retry_enabled: chain.autoRetryEnabled,
|
||||
withdrawal_auto_retry_interval_minutes: 1,
|
||||
});
|
||||
patch(authService).assertWithdrawalSecondFactor = async () => undefined;
|
||||
patch(hotWalletRepository).getActiveHotWallet = async (id: number) =>
|
||||
({
|
||||
id: '00000000-0000-4000-8000-00000000h0t1',
|
||||
wallet_type_id: id,
|
||||
address: `T${'H'.repeat(33)}`,
|
||||
encrypted_private_key: encrypt('11'.repeat(32)),
|
||||
is_active: true,
|
||||
}) as unknown as Awaited<ReturnType<typeof hotWalletRepository.getActiveHotWallet>>;
|
||||
patch(hotLiquidityService).readHotBalances = async () => ({
|
||||
usdtBalanceRaw: chain.usdt,
|
||||
nativeBalanceRaw: chain.native,
|
||||
});
|
||||
patch(payout).signPayout = async (input: { network: 'TRON' | 'BSC' }): Promise<SignedPayout> => {
|
||||
chain.signCalls++;
|
||||
if (chain.signError) throw chain.signError;
|
||||
const hash = `hash_${crypto.randomUUID()}`;
|
||||
chain.lastHash = hash;
|
||||
return {
|
||||
network: input.network,
|
||||
txHash: hash,
|
||||
payload: `signed:${hash}`,
|
||||
expiresAt: new Date(Date.now() + chain.expiresInMs),
|
||||
fromAddress: `T${'H'.repeat(33)}`,
|
||||
};
|
||||
};
|
||||
patch(payout).broadcastPayout = async () => {
|
||||
chain.broadcastCalls++;
|
||||
return chain.broadcastOutcome;
|
||||
};
|
||||
patch(payout).rebroadcastPayout = async () => {
|
||||
chain.rebroadcastCalls++;
|
||||
};
|
||||
patch(payout).getPayoutStatus = async (_n: string, hash: string) =>
|
||||
chain.statuses.get(hash) ?? { kind: 'pending' };
|
||||
patch(payout).isBscNonceConsumed = async () => false;
|
||||
|
||||
for (const fn of [
|
||||
'notifyWithdrawalSubmitted',
|
||||
'notifyWithdrawalProcessing',
|
||||
'notifyWithdrawalCompleted',
|
||||
'notifyWithdrawalFailed',
|
||||
'notifyWithdrawalRejected',
|
||||
'notifyWithdrawalCancelled',
|
||||
]) {
|
||||
patch(walletNotificationService)[fn] = async (userId: string) => {
|
||||
notifications.push({ fn, userId });
|
||||
};
|
||||
}
|
||||
patch(referralService).processWithdrawalReferralCommissions = async () => {
|
||||
referralCalls++;
|
||||
return undefined as never;
|
||||
};
|
||||
patch(userAdminStatsService).queueUserAdminStatsRefresh = () => undefined;
|
||||
patch(securityService).raiseAlert = async () => ({}) as never;
|
||||
});
|
||||
|
||||
beforeEach(() => resetChain());
|
||||
|
||||
after(async () => {
|
||||
// Dedicated test database: rows are left for inspection.
|
||||
});
|
||||
|
||||
test('12.1 request is recorded as pending and reserves amount + fee immediately', async () => {
|
||||
const userId = await createFundedUser(100n);
|
||||
const res = await submit(userId, 10n);
|
||||
assert.equal(res.status, 'pending');
|
||||
assert.equal(res.totalDebited, (11n * USDT).toString());
|
||||
assert.deepEqual(await balances(userId), { available: 89n * USDT, locked: 11n * USDT });
|
||||
assert.equal(await locksFor(res.transactionId), 11n * USDT);
|
||||
assert.deepEqual(await historyOf(res.transactionId), ['∅>pending']);
|
||||
assert.ok(notifications.some((n) => n.fn === 'notifyWithdrawalSubmitted'));
|
||||
});
|
||||
|
||||
test('12.1 reserved amount cannot be reused (no double spend)', async () => {
|
||||
const userId = await createFundedUser(15n);
|
||||
await submit(userId, 10n); // 11 reserved
|
||||
await expectCode(submit(userId, 4n), 'INSUFFICIENT_BALANCE'); // 4 + 1 > 4 left
|
||||
assert.deepEqual(await balances(userId), { available: 4n * USDT, locked: 11n * USDT });
|
||||
});
|
||||
|
||||
test('12.1 / 4.2 hot wallet short of USDT: no user error, stays pending (pending>processing>pending)', async () => {
|
||||
chain.usdt = 0n;
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
const out = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(out.status, 'pending');
|
||||
assert.equal(out.pendingReason, 'awaiting_liquidity');
|
||||
assert.equal(chain.signCalls, 0);
|
||||
const row = await withdrawalRepository.findWithdrawal(res.transactionId);
|
||||
assert.equal(row!.status, 'pending');
|
||||
assert.equal(row!.pending_reason, 'awaiting_liquidity');
|
||||
assert.deepEqual(await historyOf(res.transactionId), ['∅>pending', 'pending>processing', 'processing>pending']);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
assert.ok(!notifications.some((n) => n.fn === 'notifyWithdrawalFailed' || n.fn === 'notifyWithdrawalRejected'));
|
||||
});
|
||||
|
||||
test('12.1 hot wallet short of gas: stays pending (awaiting_gas)', async () => {
|
||||
chain.native = 0n;
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
const out = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(out.pendingReason, 'awaiting_gas');
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(res.transactionId))!.status, 'pending');
|
||||
});
|
||||
|
||||
test('7 / 12.3 after replenishment the admin processes it; completed only after confirmations', async () => {
|
||||
chain.usdt = 0n;
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN); // pending (no liquidity)
|
||||
|
||||
chain.usdt = 1_000n * USDT; // replenished
|
||||
const out = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(out.status, 'processing');
|
||||
assert.equal(chain.signCalls, 1);
|
||||
assert.equal(chain.broadcastCalls, 1);
|
||||
const hash = out.blockchainTxId!;
|
||||
await query(`UPDATE transactions SET required_confirmations = 20 WHERE id = $1`, [res.transactionId]);
|
||||
|
||||
// Broadcast but not yet confirmed: still processing, nothing debited yet.
|
||||
chain.statuses.set(hash, { kind: 'mined', success: true, confirmations: 3 });
|
||||
let row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'confirming');
|
||||
row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.status, 'processing');
|
||||
assert.equal(row.confirmations, 3);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
|
||||
chain.statuses.set(hash, { kind: 'mined', success: true, confirmations: 20 });
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'completed');
|
||||
row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.status, 'completed');
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 0n });
|
||||
assert.equal(await locksFor(res.transactionId), 0n);
|
||||
assert.equal(referralCalls, 1);
|
||||
assert.ok(notifications.some((n) => n.fn === 'notifyWithdrawalCompleted'));
|
||||
assert.deepEqual(await historyOf(res.transactionId), [
|
||||
'∅>pending',
|
||||
'pending>processing',
|
||||
'processing>pending',
|
||||
'pending>processing',
|
||||
'processing>completed',
|
||||
]);
|
||||
|
||||
// Re-verifying a completed payout never debits twice.
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'skipped');
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 0n });
|
||||
|
||||
// 12.2 completed is final.
|
||||
await expectCode(withdrawalService.processWithdrawal(res.transactionId, ADMIN), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
await expectCode(
|
||||
withdrawalService.rejectWithdrawal(res.transactionId, { actorId: userId, reason: 'too late' }),
|
||||
'WITHDRAWAL_INVALID_TRANSITION'
|
||||
);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 0n });
|
||||
});
|
||||
|
||||
test('4.3 technical failure -> failed (funds stay reserved), then retried and requeued', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
chain.signError = new Error('RPC 500 while building transaction');
|
||||
const out = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(out.status, 'failed');
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
assert.ok(notifications.some((n) => n.fn === 'notifyWithdrawalFailed'));
|
||||
|
||||
// Failed -> Pending (admin requeue) -> Processing (retry) without a second debit.
|
||||
await withdrawalService.requeueWithdrawal(res.transactionId, userId);
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(res.transactionId))!.status, 'pending');
|
||||
chain.signError = null;
|
||||
const retry = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(retry.status, 'processing');
|
||||
const row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.processing_attempts, 2);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
await expectCode(withdrawalService.requeueWithdrawal(res.transactionId, userId), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
});
|
||||
|
||||
test('4.3 failed -> processing directly (admin retry)', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 5n);
|
||||
chain.signError = new Error('boom');
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
chain.signError = null;
|
||||
const retry = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(retry.status, 'processing');
|
||||
});
|
||||
|
||||
test('8 / 12.4 reject pending: full refund exactly once, history + notification', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
const row = await withdrawalService.rejectWithdrawal(res.transactionId, {
|
||||
actorId: userId,
|
||||
reason: 'Destination flagged by compliance',
|
||||
});
|
||||
assert.equal(row.status, 'rejected');
|
||||
assert.equal(row.rejection_reason, 'Destination flagged by compliance');
|
||||
assert.ok(row.refunded_at);
|
||||
assert.equal((row.metadata as { refund?: { amount?: string } }).refund?.amount, (11n * USDT).toString());
|
||||
assert.deepEqual(await balances(userId), { available: 50n * USDT, locked: 0n });
|
||||
assert.ok(notifications.some((n) => n.fn === 'notifyWithdrawalRejected'));
|
||||
|
||||
await expectCode(
|
||||
withdrawalService.rejectWithdrawal(res.transactionId, { actorId: userId, reason: 'again' }),
|
||||
'WITHDRAWAL_INVALID_TRANSITION'
|
||||
);
|
||||
await expectCode(withdrawalService.processWithdrawal(res.transactionId, ADMIN), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
assert.deepEqual(await balances(userId), { available: 50n * USDT, locked: 0n });
|
||||
});
|
||||
|
||||
test('4.4 reject failed request after verification', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
chain.signError = new Error('boom');
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
const row = await withdrawalService.rejectWithdrawal(res.transactionId, { actorId: userId, reason: 'Not retried' });
|
||||
assert.equal(row.status, 'rejected');
|
||||
assert.deepEqual(await balances(userId), { available: 50n * USDT, locked: 0n });
|
||||
});
|
||||
|
||||
test('4.4 a processing request (payout broadcast) cannot be rejected or cancelled', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
await expectCode(
|
||||
withdrawalService.rejectWithdrawal(res.transactionId, { actorId: userId, reason: 'stop' }),
|
||||
'WITHDRAWAL_INVALID_TRANSITION'
|
||||
);
|
||||
await expectCode(withdrawalService.cancelWithdrawal(res.transactionId, { userId }), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
});
|
||||
|
||||
test('3 user cancels own pending request: refunded; other users cannot cancel it', async () => {
|
||||
const userId = await createFundedUser(30n);
|
||||
const other = await createFundedUser(1n);
|
||||
const res = await submit(userId, 10n);
|
||||
await expectCode(withdrawalService.cancelWithdrawal(res.transactionId, { userId: other }), 'WITHDRAWAL_NOT_FOUND');
|
||||
const row = await withdrawalService.cancelWithdrawal(res.transactionId, { userId });
|
||||
assert.equal(row.status, 'cancelled');
|
||||
assert.deepEqual(await balances(userId), { available: 30n * USDT, locked: 0n });
|
||||
await expectCode(withdrawalService.cancelWithdrawal(res.transactionId, { userId }), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
assert.ok(notifications.some((n) => n.fn === 'notifyWithdrawalCancelled'));
|
||||
});
|
||||
|
||||
test('10 / 12.5 two admins process simultaneously: one payout only', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
const results = await Promise.allSettled([
|
||||
withdrawalService.processWithdrawal(res.transactionId, ADMIN),
|
||||
withdrawalService.processWithdrawal(res.transactionId, ADMIN),
|
||||
withdrawalService.processWithdrawal(res.transactionId, ADMIN),
|
||||
]);
|
||||
assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1);
|
||||
assert.equal(chain.signCalls, 1);
|
||||
assert.equal(chain.broadcastCalls, 1);
|
||||
});
|
||||
|
||||
test('10 / 12.5 concurrent rejects refund exactly once', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
const results = await Promise.allSettled(
|
||||
[1, 2, 3, 4].map(() =>
|
||||
withdrawalService.rejectWithdrawal(res.transactionId, { actorId: userId, reason: 'dup click' })
|
||||
)
|
||||
);
|
||||
assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1);
|
||||
assert.deepEqual(await balances(userId), { available: 50n * USDT, locked: 0n });
|
||||
});
|
||||
|
||||
test('10 validate vs reject at the same time: exactly one wins', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
const [processed, rejected] = await Promise.allSettled([
|
||||
withdrawalService.processWithdrawal(res.transactionId, ADMIN),
|
||||
withdrawalService.rejectWithdrawal(res.transactionId, { actorId: userId, reason: 'race' }),
|
||||
]);
|
||||
const wins = [processed, rejected].filter((r) => r.status === 'fulfilled').length;
|
||||
assert.equal(wins, 1);
|
||||
const row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
const b = await balances(userId);
|
||||
if (row.status === 'rejected') {
|
||||
assert.deepEqual(b, { available: 50n * USDT, locked: 0n });
|
||||
assert.equal(chain.broadcastCalls, 0);
|
||||
} else {
|
||||
assert.equal(row.status, 'processing');
|
||||
assert.deepEqual(b, { available: 39n * USDT, locked: 11n * USDT });
|
||||
}
|
||||
});
|
||||
|
||||
test('10 double click / repeated request with the same idempotency key creates one request', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const key = `test-${crypto.randomUUID()}`;
|
||||
const results = await Promise.all([submit(userId, 10n, key), submit(userId, 10n, key), submit(userId, 10n, key)]);
|
||||
assert.equal(new Set(results.map((r) => r.transactionId)).size, 1);
|
||||
assert.equal(results.filter((r) => r.duplicate).length, 2);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
});
|
||||
|
||||
test('5 lost broadcast response: stays processing, verified by hash, same tx re-sent, never re-signed', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
chain.broadcastOutcome = { kind: 'uncertain', message: 'ECONNRESET' };
|
||||
const out = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(out.status, 'processing');
|
||||
let row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.processing_stage, 'broadcast_uncertain');
|
||||
const hash = row.blockchain_tx_id!;
|
||||
|
||||
// Retry by an admin is refused while the hash is being verified.
|
||||
await expectCode(withdrawalService.processWithdrawal(res.transactionId, ADMIN), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
|
||||
chain.statuses.set(hash, { kind: 'not_found' });
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'rebroadcast');
|
||||
assert.equal(chain.rebroadcastCalls, 1);
|
||||
assert.equal(chain.signCalls, 1);
|
||||
|
||||
chain.statuses.set(hash, { kind: 'mined', success: true, confirmations: 999 });
|
||||
row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'completed');
|
||||
assert.equal(chain.signCalls, 1);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 0n });
|
||||
});
|
||||
|
||||
test('5 payout never included and expired: failed, hash archived, retry signs a new tx', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
chain.expiresInMs = -10 * 60_000;
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
let row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
const firstHash = row.blockchain_tx_id!;
|
||||
chain.statuses.set(firstHash, { kind: 'not_found' });
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'failed');
|
||||
row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.status, 'failed');
|
||||
assert.equal(row.blockchain_tx_id, null);
|
||||
assert.deepEqual(row.abandoned_tx_hashes, [firstHash]);
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
|
||||
chain.expiresInMs = 60_000;
|
||||
const retry = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(retry.status, 'processing');
|
||||
assert.notEqual(retry.blockchainTxId, firstHash);
|
||||
});
|
||||
|
||||
test('5 payout reverted on-chain: failed, funds still reserved for retry', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
const row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
chain.statuses.set(row.blockchain_tx_id!, { kind: 'mined', success: false, confirmations: 30, message: 'REVERT' });
|
||||
assert.equal(await withdrawalService.verifyBroadcastWithdrawal(row), 'failed');
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
});
|
||||
|
||||
test('4.2 node refuses the signed payout for lack of gas: back to pending, nothing sent', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
chain.broadcastOutcome = { kind: 'not_sent', failure: 'liquidity_gas', message: 'BANDWITH_ERROR' };
|
||||
const out = await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
assert.equal(out.status, 'pending');
|
||||
const row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.pending_reason, 'awaiting_gas');
|
||||
assert.equal(row.blockchain_tx_id, null);
|
||||
assert.equal(row.abandoned_tx_hashes?.length, 1);
|
||||
});
|
||||
|
||||
test('interrupted processing (no signed tx) is recovered to pending by the monitor', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalRepository.claimForProcessing(res.transactionId, ADMIN);
|
||||
await query(
|
||||
`UPDATE transactions SET processing_started_at = NOW() - INTERVAL '30 minutes' WHERE id = $1`,
|
||||
[res.transactionId]
|
||||
);
|
||||
await withdrawalService.runWithdrawalMonitorCycle();
|
||||
const row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.status, 'pending');
|
||||
assert.equal(row.pending_reason, 'processing_interrupted');
|
||||
});
|
||||
|
||||
test('large withdrawal awaiting approval cannot be processed from the queue', async () => {
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalRepository.patchPendingDetails(res.transactionId, { pendingReason: 'awaiting_approval' });
|
||||
await expectCode(withdrawalService.processWithdrawal(res.transactionId, ADMIN), 'WITHDRAWAL_AWAITING_APPROVAL');
|
||||
const approved = await withdrawalService.processApprovedWithdrawal(res.transactionId, userId);
|
||||
assert.equal(approved.status, 'processing');
|
||||
});
|
||||
|
||||
test('daily limit counts failed (still reserved) but not rejected/cancelled requests', async () => {
|
||||
const userId = await createFundedUser(500n);
|
||||
const realGet = settingsRepository.getSettings;
|
||||
patch(settingsRepository).getSettings = async () => ({ ...(await realGet()), daily_withdrawal_limit_usd: 25 });
|
||||
try {
|
||||
const a = await submit(userId, 10n); // 11 used
|
||||
chain.signError = new Error('boom');
|
||||
await withdrawalService.processWithdrawal(a.transactionId, ADMIN); // failed, still counts
|
||||
const b = await submit(userId, 10n); // 22 used
|
||||
await expectCode(submit(userId, 5n), 'DAILY_WITHDRAWAL_LIMIT_EXCEEDED');
|
||||
await withdrawalService.cancelWithdrawal(b.transactionId, { userId }); // frees 11
|
||||
const c = await submit(userId, 5n);
|
||||
assert.equal(c.status, 'pending');
|
||||
} finally {
|
||||
patch(settingsRepository).getSettings = realGet;
|
||||
}
|
||||
});
|
||||
|
||||
/** Isolates auto-retry tests from liquidity-pending rows left by earlier tests. */
|
||||
async function parkOtherAutoRetryRows() {
|
||||
await query(
|
||||
`UPDATE transactions SET pending_reason = 'queued'
|
||||
WHERE type = 'withdrawal' AND status = 'pending'
|
||||
AND pending_reason IN ('awaiting_liquidity', 'awaiting_gas', 'hot_wallet_unavailable')`
|
||||
);
|
||||
}
|
||||
|
||||
test('auto-retry disabled: liquidity-pending requests are left for the admin', async () => {
|
||||
await parkOtherAutoRetryRows();
|
||||
chain.usdt = 0n;
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN); // -> awaiting_liquidity
|
||||
chain.usdt = 1_000n * USDT; // replenished, but the option is off
|
||||
const before = await historyOf(res.transactionId);
|
||||
const r = await withdrawalService.runWithdrawalAutoRetryCycle();
|
||||
assert.deepEqual(r, { attempted: 0, skipped: 0 });
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(res.transactionId))!.status, 'pending');
|
||||
assert.deepEqual(await historyOf(res.transactionId), before);
|
||||
});
|
||||
|
||||
test('auto-retry enabled but hot wallet still empty: no claim, no history churn', async () => {
|
||||
await parkOtherAutoRetryRows();
|
||||
chain.usdt = 0n;
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN);
|
||||
chain.autoRetryEnabled = true;
|
||||
const before = await historyOf(res.transactionId);
|
||||
const r = await withdrawalService.runWithdrawalAutoRetryCycle();
|
||||
assert.equal(r.attempted, 0);
|
||||
assert.equal(chain.signCalls, 0);
|
||||
assert.deepEqual(await historyOf(res.transactionId), before);
|
||||
});
|
||||
|
||||
test('auto-retry enabled after replenishment: processed automatically (system actor)', async () => {
|
||||
await parkOtherAutoRetryRows();
|
||||
chain.native = 0n;
|
||||
const userId = await createFundedUser(50n);
|
||||
const res = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(res.transactionId, ADMIN); // -> awaiting_gas
|
||||
chain.native = 10n ** 20n;
|
||||
chain.autoRetryEnabled = true;
|
||||
const r = await withdrawalService.runWithdrawalAutoRetryCycle();
|
||||
assert.equal(r.attempted, 1);
|
||||
const row = (await withdrawalRepository.findWithdrawal(res.transactionId))!;
|
||||
assert.equal(row.status, 'processing');
|
||||
assert.ok(row.blockchain_tx_id);
|
||||
const history = await withdrawalRepository.listHistory(res.transactionId);
|
||||
assert.equal(history[history.length - 1]!.actor_type, 'system');
|
||||
assert.deepEqual(await balances(userId), { available: 39n * USDT, locked: 11n * USDT });
|
||||
});
|
||||
|
||||
test('auto-retry is FIFO and never exceeds what the hot wallet can pay', async () => {
|
||||
await parkOtherAutoRetryRows();
|
||||
chain.usdt = 0n;
|
||||
const userId = await createFundedUser(100n);
|
||||
const first = await submit(userId, 10n);
|
||||
const second = await submit(userId, 10n);
|
||||
await withdrawalService.processWithdrawal(first.transactionId, ADMIN);
|
||||
await withdrawalService.processWithdrawal(second.transactionId, ADMIN);
|
||||
// Payouts still in flight from earlier tests are reserved against the hot wallet too.
|
||||
const inFlight = await withdrawalRepository.sumInFlightPayouts('TRON', first.transactionId);
|
||||
chain.usdt = inFlight + 15n * USDT; // enough for one 10 USDT payout, not two
|
||||
chain.autoRetryEnabled = true;
|
||||
const r = await withdrawalService.runWithdrawalAutoRetryCycle();
|
||||
assert.equal(r.attempted, 1);
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(first.transactionId))!.status, 'processing');
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(second.transactionId))!.status, 'pending');
|
||||
});
|
||||
|
||||
test('auto-retry never touches requests awaiting approval or set aside by an admin', async () => {
|
||||
await parkOtherAutoRetryRows();
|
||||
const userId = await createFundedUser(50n);
|
||||
const a = await submit(userId, 5n);
|
||||
const b = await submit(userId, 5n);
|
||||
await withdrawalRepository.patchPendingDetails(a.transactionId, { pendingReason: 'awaiting_approval' });
|
||||
chain.signError = new Error('boom');
|
||||
await withdrawalService.processWithdrawal(b.transactionId, ADMIN); // failed
|
||||
chain.signError = null;
|
||||
await withdrawalService.requeueWithdrawal(b.transactionId, userId); // requeued_by_admin
|
||||
chain.autoRetryEnabled = true;
|
||||
const r = await withdrawalService.runWithdrawalAutoRetryCycle();
|
||||
assert.equal(r.attempted, 0);
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(a.transactionId))!.status, 'pending');
|
||||
assert.equal((await withdrawalRepository.findWithdrawal(b.transactionId))!.status, 'pending');
|
||||
});
|
||||
|
||||
test('legacy refunded failures become read-only failed_refunded and are never retried', async () => {
|
||||
const userId = await createFundedUser(5n);
|
||||
const legacy = await query<{ id: string }[]>(
|
||||
`INSERT INTO transactions (user_id, wallet_type_id, type, amount, fee, status, to_address)
|
||||
VALUES ($1, $2, 'withdrawal', $3, 0, 'failed', $4) RETURNING id`,
|
||||
[userId, walletTypeId, (3n * USDT).toString(), TRON_DEST]
|
||||
);
|
||||
await runMigrations();
|
||||
const row = (await withdrawalRepository.findWithdrawal(legacy[0]!.id))!;
|
||||
assert.equal(row.status, 'failed_refunded');
|
||||
await expectCode(withdrawalService.processWithdrawal(row.id, ADMIN), 'WITHDRAWAL_INVALID_TRANSITION');
|
||||
await expectCode(
|
||||
withdrawalService.rejectWithdrawal(row.id, { actorId: userId, reason: 'x' }),
|
||||
'WITHDRAWAL_INVALID_TRANSITION'
|
||||
);
|
||||
assert.deepEqual(await balances(userId), { available: 5n * USDT, locked: 0n });
|
||||
});
|
||||
});
|
||||
155
backend/src/tests/withdrawalStateMachine.test.ts
Normal file
155
backend/src/tests/withdrawalStateMachine.test.ts
Normal file
@ -0,0 +1,155 @@
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
WITHDRAWAL_STATUSES,
|
||||
WITHDRAWAL_TRANSITIONS,
|
||||
allowedFromStatuses,
|
||||
assertTransition,
|
||||
canTransition,
|
||||
isTerminalWithdrawalStatus,
|
||||
type WithdrawalStatus,
|
||||
} from '../services/withdrawals/withdrawalStateMachine';
|
||||
import {
|
||||
classifyTronRejection,
|
||||
decideMissingPayout,
|
||||
BSC_DROP_GRACE_MS,
|
||||
TRON_EXPIRY_MARGIN_MS,
|
||||
} from '../services/withdrawals/withdrawalPayoutService';
|
||||
import { classifyTronBroadcastResponse } from '../services/blockchain/tronService';
|
||||
import { classifyBscError, isAlreadyKnownBroadcastError } from '../services/blockchain/bscService';
|
||||
|
||||
describe('withdrawal state machine — allowed transitions (spec 4.5)', () => {
|
||||
const expected: Array<[WithdrawalStatus, WithdrawalStatus]> = [
|
||||
['pending', 'processing'],
|
||||
['pending', 'rejected'],
|
||||
['pending', 'cancelled'],
|
||||
['processing', 'completed'],
|
||||
['processing', 'pending'],
|
||||
['processing', 'failed'],
|
||||
['failed', 'processing'],
|
||||
['failed', 'pending'],
|
||||
['failed', 'rejected'],
|
||||
];
|
||||
|
||||
test('exactly the specified transitions are allowed', () => {
|
||||
const allowed: Array<[string, string]> = [];
|
||||
for (const from of WITHDRAWAL_STATUSES) {
|
||||
for (const to of WITHDRAWAL_STATUSES) {
|
||||
if (canTransition(from, to)) allowed.push([from, to]);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(allowed.sort(), [...expected].sort());
|
||||
});
|
||||
|
||||
test('completed / rejected / cancelled are terminal', () => {
|
||||
for (const s of ['completed', 'rejected', 'cancelled'] as const) {
|
||||
assert.deepEqual(WITHDRAWAL_TRANSITIONS[s], []);
|
||||
assert.equal(isTerminalWithdrawalStatus(s), true);
|
||||
}
|
||||
assert.equal(isTerminalWithdrawalStatus('failed_refunded'), true);
|
||||
assert.equal(isTerminalWithdrawalStatus('failed'), false);
|
||||
});
|
||||
|
||||
test('a processing withdrawal can never be rejected or cancelled directly', () => {
|
||||
assert.equal(canTransition('processing', 'rejected'), false);
|
||||
assert.equal(canTransition('processing', 'cancelled'), false);
|
||||
assert.equal(canTransition('failed', 'cancelled'), false);
|
||||
});
|
||||
|
||||
test('pending can never jump to completed (completion needs on-chain confirmation)', () => {
|
||||
assert.equal(canTransition('pending', 'completed'), false);
|
||||
assert.equal(canTransition('failed', 'completed'), false);
|
||||
});
|
||||
|
||||
test('legacy and unknown statuses are refused', () => {
|
||||
for (const legacy of ['pending_approval', 'broadcasting', 'confirming', 'ledger_finalize_failed', 'failed_refunded', 'x']) {
|
||||
for (const to of WITHDRAWAL_STATUSES) assert.equal(canTransition(legacy, to), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('assertTransition throws a coded error', () => {
|
||||
assert.throws(
|
||||
() => assertTransition('completed', 'rejected'),
|
||||
(e: unknown) => (e as { code?: string }).code === 'WITHDRAWAL_INVALID_TRANSITION'
|
||||
);
|
||||
assert.doesNotThrow(() => assertTransition('failed', 'processing'));
|
||||
});
|
||||
|
||||
test('allowedFromStatuses matches the table', () => {
|
||||
assert.deepEqual(allowedFromStatuses('processing').sort(), ['failed', 'pending']);
|
||||
assert.deepEqual(allowedFromStatuses('rejected').sort(), ['failed', 'pending']);
|
||||
assert.deepEqual(allowedFromStatuses('completed'), ['processing']);
|
||||
assert.deepEqual(allowedFromStatuses('cancelled'), ['pending']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('payout broadcast classification', () => {
|
||||
test('TRON node responses', () => {
|
||||
assert.deepEqual(classifyTronBroadcastResponse({ result: true }), { kind: 'accepted' });
|
||||
assert.deepEqual(classifyTronBroadcastResponse({ code: 'DUP_TRANSACTION_ERROR' }), { kind: 'accepted' });
|
||||
const refused = classifyTronBroadcastResponse({
|
||||
code: 'CONTRACT_VALIDATE_ERROR',
|
||||
message: Buffer.from('balance is not sufficient').toString('hex'),
|
||||
});
|
||||
assert.equal(refused.kind, 'rejected');
|
||||
assert.equal(refused.kind === 'rejected' && refused.message, 'balance is not sufficient');
|
||||
});
|
||||
|
||||
test('TRON refusals for missing TRX/bandwidth keep the request pending (gas)', () => {
|
||||
assert.equal(classifyTronRejection('BANDWITH_ERROR', ''), 'liquidity_gas');
|
||||
assert.equal(classifyTronRejection('CONTRACT_VALIDATE_ERROR', 'balance is not sufficient'), 'liquidity_gas');
|
||||
assert.equal(classifyTronRejection('SIGERROR', 'bad signature'), 'rejected');
|
||||
});
|
||||
|
||||
test('BSC errors: gas / usdt / refused / uncertain', () => {
|
||||
assert.equal(classifyBscError({ code: 'INSUFFICIENT_FUNDS', message: 'x' }), 'gas');
|
||||
assert.equal(classifyBscError(new Error('insufficient funds for gas * price + value')), 'gas');
|
||||
assert.equal(classifyBscError({ code: 'CALL_EXCEPTION', message: 'execution reverted' }), 'usdt');
|
||||
assert.equal(classifyBscError({ code: 'NONCE_EXPIRED', message: 'nonce too low' }), 'rejected');
|
||||
assert.equal(classifyBscError({ code: 'NETWORK_ERROR', message: 'socket hang up' }), 'uncertain');
|
||||
assert.equal(classifyBscError({ code: 'TIMEOUT', message: 'timeout' }), 'uncertain');
|
||||
assert.equal(isAlreadyKnownBroadcastError(new Error('already known')), true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('missing payout decision (no double payment)', () => {
|
||||
const now = 1_800_000_000_000;
|
||||
|
||||
test('TRON: re-broadcast the same signed tx until it expires, then declare it dropped', () => {
|
||||
assert.equal(
|
||||
decideMissingPayout({ network: 'TRON', nowMs: now, broadcastAtMs: now - 5_000, expiresAtMs: now + 60_000 }),
|
||||
'rebroadcast'
|
||||
);
|
||||
assert.equal(
|
||||
decideMissingPayout({
|
||||
network: 'TRON',
|
||||
nowMs: now,
|
||||
broadcastAtMs: now - 3_600_000,
|
||||
expiresAtMs: now - TRON_EXPIRY_MARGIN_MS - 1,
|
||||
}),
|
||||
'dropped'
|
||||
);
|
||||
});
|
||||
|
||||
test('BSC: dropped only after its nonce is consumed and the grace period passed', () => {
|
||||
assert.equal(
|
||||
decideMissingPayout({ network: 'BSC', nowMs: now, broadcastAtMs: now - 1_000, expiresAtMs: null, nonceConsumed: false }),
|
||||
'rebroadcast'
|
||||
);
|
||||
assert.equal(
|
||||
decideMissingPayout({ network: 'BSC', nowMs: now, broadcastAtMs: now - 1_000, expiresAtMs: null, nonceConsumed: true }),
|
||||
'wait'
|
||||
);
|
||||
assert.equal(
|
||||
decideMissingPayout({
|
||||
network: 'BSC',
|
||||
nowMs: now,
|
||||
broadcastAtMs: now - BSC_DROP_GRACE_MS - 1,
|
||||
expiresAtMs: null,
|
||||
nonceConsumed: true,
|
||||
}),
|
||||
'dropped'
|
||||
);
|
||||
});
|
||||
});
|
||||
@ -31,6 +31,15 @@ export function httpStatusForError(error: unknown): number {
|
||||
return 400;
|
||||
}
|
||||
if (code === 'DAILY_WITHDRAWAL_LIMIT_EXCEEDED') return 403;
|
||||
if (code === 'WITHDRAWAL_NOT_FOUND') return 404;
|
||||
if (
|
||||
code === 'WITHDRAWAL_INVALID_TRANSITION' ||
|
||||
code === 'WITHDRAWAL_LEGACY_READ_ONLY' ||
|
||||
code === 'WITHDRAWAL_AWAITING_APPROVAL' ||
|
||||
code === 'WITHDRAWAL_ALREADY_BROADCAST'
|
||||
) {
|
||||
return 409;
|
||||
}
|
||||
if (code === 'TOKEN_REVOKED') return 401;
|
||||
if (code === 'ACCOUNT_LOCKED') return 429;
|
||||
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID') return 400;
|
||||
|
||||
@ -18,6 +18,11 @@ export function clientErrorMessage(error: unknown, fallback = 'Request failed'):
|
||||
'INSUFFICIENT_BALANCE',
|
||||
'DAILY_WITHDRAWAL_LIMIT_EXCEEDED',
|
||||
'WITHDRAWAL_2FA_REQUIRED',
|
||||
'WITHDRAWAL_NOT_FOUND',
|
||||
'WITHDRAWAL_INVALID_TRANSITION',
|
||||
'WITHDRAWAL_LEGACY_READ_ONLY',
|
||||
'WITHDRAWAL_AWAITING_APPROVAL',
|
||||
'WITHDRAWAL_ALREADY_BROADCAST',
|
||||
]);
|
||||
if (code && exposeByCode.has(code) && msg.trim()) {
|
||||
return msg;
|
||||
|
||||
@ -134,3 +134,7 @@ export const uuidParamSchema = z.object({
|
||||
export const alertIdParamSchema = z.object({
|
||||
alertId: z.string().uuid(),
|
||||
});
|
||||
|
||||
export const uuidIdParamSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
});
|
||||
|
||||
@ -28,6 +28,32 @@ export const withdrawBodySchema = z.object({
|
||||
toAddress: z.string().trim().min(10).max(255),
|
||||
amount: z.union([z.string(), z.number()]),
|
||||
totpCode: z.string().trim().min(6).max(32).optional(),
|
||||
/** Client-generated per submission; a retried request with the same key is not duplicated. */
|
||||
idempotencyKey: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(8)
|
||||
.max(128)
|
||||
.regex(/^[A-Za-z0-9_.:-]+$/)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const adminWithdrawalRejectBodySchema = z.object({
|
||||
reason: z.string().trim().min(3).max(1000),
|
||||
});
|
||||
|
||||
export const adminWithdrawalsListQuerySchema = z.object({
|
||||
status: z
|
||||
.enum(['open', 'all', 'pending', 'processing', 'completed', 'failed', 'rejected', 'cancelled', 'failed_refunded'])
|
||||
.optional(),
|
||||
network: z.enum(['TRON', 'BSC']).optional(),
|
||||
from: z.string().trim().max(64).optional(),
|
||||
to: z.string().trim().max(64).optional(),
|
||||
minAmount: z.string().trim().regex(/^\d*$/).max(32).optional(),
|
||||
maxAmount: z.string().trim().regex(/^\d*$/).max(32).optional(),
|
||||
search: z.string().trim().max(200).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).optional(),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
});
|
||||
|
||||
export const transferBodySchema = z.object({
|
||||
|
||||
@ -60,7 +60,7 @@ This guide explains how to **withdraw USDT** from Tloto to an external wallet or
|
||||
</table>
|
||||
<p><strong>Important:</strong> TRC20 and BEP20 are <strong>not</strong> interchangeable.<br />
|
||||
Sending to the wrong address / network may cause <strong>permanent loss</strong> of funds.</p>
|
||||
<p>If a network is unavailable (platform liquidity or temporary disablement), try the <strong>other network</strong> or retry later.</p>
|
||||
<p>If a network is not offered in the withdrawal dialog, it is temporarily disabled: choose an available network.</p>
|
||||
</div>
|
||||
|
||||
<div style="page-break-inside: avoid; break-inside: avoid;">
|
||||
@ -77,14 +77,17 @@ Sending to the wrong address / network may cause <strong>permanent loss</strong>
|
||||
|
||||
<div style="page-break-inside: avoid; break-inside: avoid;">
|
||||
<h2>6. Tracking and statuses</h2>
|
||||
<p>After submit, check the <strong>Withdrawals</strong> activity tab in your wallet.</p>
|
||||
<p>As soon as you confirm, your request is <strong>registered</strong> and the total (amount + network fee) is <strong>reserved</strong> on your balance, so it cannot be spent twice. Check the <strong>Withdrawals</strong> activity tab in your wallet.</p>
|
||||
<ul>
|
||||
<li><strong>Pending</strong>: withdrawal recorded, processing underway</li>
|
||||
<li><strong>Processing</strong>: broadcast or confirmation in progress</li>
|
||||
<li><strong>Completed</strong>: funds sent; the debit is finalized</li>
|
||||
<li><strong>Failed</strong>: the send did not complete; locked balance may be released depending on the case</li>
|
||||
<li><strong>Pending</strong>: request registered; it will be processed as soon as possible</li>
|
||||
<li><strong>Processing</strong>: the transfer is being sent and confirmed on the blockchain</li>
|
||||
<li><strong>Completed</strong>: the transfer is confirmed on the blockchain; the reserved amount is debited</li>
|
||||
<li><strong>Failed</strong>: a technical problem occurred; your request remains registered (amount still reserved) and will be reviewed</li>
|
||||
<li><strong>Rejected</strong>: the request was declined; the full reserved amount is credited back to your balance</li>
|
||||
<li><strong>Cancelled</strong>: you cancelled the request; the full reserved amount is credited back to your balance</li>
|
||||
</ul>
|
||||
<p>A large withdrawal may sometimes wait for <strong>approval</strong> before on-chain broadcast. Timing also depends on the blockchain network.</p>
|
||||
<p>While a withdrawal is still <strong>Pending</strong>, you can <strong>cancel</strong> it from the Withdrawals activity: the full amount is credited back immediately. Once it is <strong>Processing</strong>, it can no longer be cancelled.</p>
|
||||
<p>A large withdrawal may wait for <strong>approval</strong> before it is sent. Timing also depends on the blockchain network. You are notified (in the app and by e-mail) at each important step.</p>
|
||||
</div>
|
||||
|
||||
<div style="page-break-inside: avoid; break-inside: avoid;">
|
||||
|
||||
@ -60,7 +60,7 @@ Ce guide explique comment **retirer vos USDT** hors de Tloto vers un portefeuill
|
||||
</table>
|
||||
<p><strong>Important :</strong> TRC20 et BEP20 ne sont <strong>pas</strong> interchangeables.<br />
|
||||
Envoyer vers une adresse / un réseau incorrect peut entraîner une <strong>perte définitive</strong> des fonds.</p>
|
||||
<p>Si un réseau est indisponible (liquidité plateforme ou désactivation temporaire), essayez l'<strong>autre réseau</strong> ou réessayez plus tard.</p>
|
||||
<p>Si un réseau n'est pas proposé dans la fenêtre de retrait, il est temporairement désactivé : choisissez un réseau disponible.</p>
|
||||
</div>
|
||||
|
||||
<div style="page-break-inside: avoid; break-inside: avoid;">
|
||||
@ -77,14 +77,17 @@ Envoyer vers une adresse / un réseau incorrect peut entraîner une <strong>pert
|
||||
|
||||
<div style="page-break-inside: avoid; break-inside: avoid;">
|
||||
<h2>6. Suivi et statuts</h2>
|
||||
<p>Après soumission, consultez l'onglet d'activité <strong>Retraits</strong> de votre portefeuille.</p>
|
||||
<p>Dès votre confirmation, la demande est <strong>enregistrée</strong> et le total (montant + frais réseau) est <strong>réservé</strong> sur votre solde : il ne peut pas être utilisé deux fois. Consultez l'onglet d'activité <strong>Retraits</strong> de votre portefeuille.</p>
|
||||
<ul>
|
||||
<li><strong>En attente / Pending</strong> : retrait enregistré, traitement en cours</li>
|
||||
<li><strong>En traitement / Processing</strong> : envoi ou confirmation en cours</li>
|
||||
<li><strong>Terminé / Completed</strong> : fonds envoyés ; le débit est finalisé</li>
|
||||
<li><strong>Échoué / Failed</strong> : l'envoi n'a pas abouti ; le solde concerné peut être libéré selon le cas</li>
|
||||
<li><strong>En attente / Pending</strong> : demande enregistrée ; elle sera traitée dans les meilleurs délais</li>
|
||||
<li><strong>En cours / Processing</strong> : le transfert est en cours d'envoi et de confirmation sur la blockchain</li>
|
||||
<li><strong>Terminé / Completed</strong> : le transfert est confirmé sur la blockchain ; le montant réservé est débité</li>
|
||||
<li><strong>Échoué / Failed</strong> : un problème technique est survenu ; votre demande reste enregistrée (montant toujours réservé) et sera examinée</li>
|
||||
<li><strong>Refusé / Rejected</strong> : la demande a été refusée ; la totalité du montant réservé est recréditée sur votre solde</li>
|
||||
<li><strong>Annulé / Cancelled</strong> : vous avez annulé la demande ; la totalité du montant réservé est recréditée sur votre solde</li>
|
||||
</ul>
|
||||
<p>Un retrait important peut parfois rester en attente d'<strong>approbation</strong> avant diffusion on-chain. Les délais dépendent aussi du réseau blockchain.</p>
|
||||
<p>Tant qu'un retrait est <strong>En attente</strong>, vous pouvez l'<strong>annuler</strong> depuis l'activité Retraits : le montant est recrédité immédiatement. Une fois <strong>En cours</strong>, il ne peut plus être annulé.</p>
|
||||
<p>Un retrait important peut rester en attente d'<strong>approbation</strong> avant son envoi. Les délais dépendent aussi du réseau blockchain. Vous êtes notifié (dans l'application et par e-mail) à chaque étape importante.</p>
|
||||
</div>
|
||||
|
||||
<div style="page-break-inside: avoid; break-inside: avoid;">
|
||||
|
||||
@ -24,6 +24,7 @@ abstract class WalletRepository {
|
||||
String toAddress,
|
||||
String amount, {
|
||||
String? totpCode,
|
||||
String? idempotencyKey,
|
||||
});
|
||||
Future<TransferResult> transfer(
|
||||
String toEmail,
|
||||
@ -108,14 +109,17 @@ class WalletRepositoryImpl implements WalletRepository {
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Submits an on-chain withdrawal; [amount] must be in smallest units.
|
||||
/// Records a withdrawal request (status `pending`); [amount] must be in smallest units.
|
||||
///
|
||||
/// Optional [totpCode] is required when 2FA is enabled for the account.
|
||||
/// [idempotencyKey] must stay the same for retries of one submission so the
|
||||
/// server never creates a second withdrawal (double tap, lost response).
|
||||
Future<WithdrawResult> withdraw(
|
||||
String walletType,
|
||||
String toAddress,
|
||||
String amount, {
|
||||
String? totpCode,
|
||||
String? idempotencyKey,
|
||||
}) async {
|
||||
final res = await _api.dio.post<Map<String, dynamic>>(
|
||||
'/api/v1/withdraw',
|
||||
@ -124,6 +128,7 @@ class WalletRepositoryImpl implements WalletRepository {
|
||||
'toAddress': toAddress,
|
||||
'amount': amount,
|
||||
if (totpCode != null) 'totpCode': totpCode,
|
||||
if (idempotencyKey != null) 'idempotencyKey': idempotencyKey,
|
||||
},
|
||||
);
|
||||
final data = res.data!;
|
||||
@ -133,6 +138,14 @@ class WalletRepositoryImpl implements WalletRepository {
|
||||
);
|
||||
}
|
||||
|
||||
/// Cancels the user's own withdrawal while it is still pending (amount credited back).
|
||||
Future<void> cancelWithdrawal(String transactionId) async {
|
||||
await _api.dio.post<Map<String, dynamic>>(
|
||||
'/api/v1/withdrawals/$transactionId/cancel',
|
||||
data: const <String, dynamic>{},
|
||||
);
|
||||
}
|
||||
|
||||
/// Transfers funds to another user identified by [toEmail].
|
||||
///
|
||||
/// Optional [totpCode] is required when 2FA is enabled for the account.
|
||||
|
||||
@ -377,6 +377,7 @@ class WalletBloc extends Bloc<WalletEvent, WalletState> {
|
||||
event.toAddress,
|
||||
event.amount,
|
||||
totpCode: event.totpCode,
|
||||
idempotencyKey: event.idempotencyKey,
|
||||
);
|
||||
emit(state.copyWith(withdrawTxId: result.transactionId, withdrawStatus: result.status));
|
||||
add(const WalletLoadRequested());
|
||||
|
||||
@ -52,11 +52,15 @@ class WalletWithdrawRequested extends WalletEvent {
|
||||
required this.toAddress,
|
||||
required this.amount,
|
||||
this.totpCode,
|
||||
this.idempotencyKey,
|
||||
});
|
||||
final String walletType;
|
||||
final String toAddress;
|
||||
final String amount;
|
||||
final String? totpCode;
|
||||
|
||||
/// Same value for every retry of one submission (prevents duplicate withdrawals).
|
||||
final String? idempotencyKey;
|
||||
}
|
||||
|
||||
/// Transfers balance to another registered user by email.
|
||||
|
||||
@ -20,6 +20,7 @@ import '../../../shared/widgets/section_error.dart';
|
||||
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
|
||||
import '../bloc/wallet_bloc.dart';
|
||||
import '../utils/transaction_display.dart';
|
||||
import 'withdrawal_status_extras.dart';
|
||||
|
||||
/// Scrollable list of all transactions with pull-to-refresh and pagination.
|
||||
class TransactionHistoryScreen extends StatefulWidget {
|
||||
@ -259,6 +260,10 @@ class _TransactionHistoryScreenState extends State<TransactionHistoryScreen> {
|
||||
decimals: decimals,
|
||||
assetCode: code,
|
||||
strings: s,
|
||||
onChanged: () {
|
||||
_loadPage(reset: true, force: true);
|
||||
context.read<WalletBloc>().add(const WalletLoadRequested());
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@ -271,12 +276,14 @@ class _HistoryStatusTile extends StatelessWidget {
|
||||
required this.decimals,
|
||||
required this.assetCode,
|
||||
required this.strings,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
final TransactionModel tx;
|
||||
final int decimals;
|
||||
final String assetCode;
|
||||
final AppStrings strings;
|
||||
final VoidCallback onChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@ -402,6 +409,8 @@ class _HistoryStatusTile extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
if (tx.type == 'withdrawal')
|
||||
WithdrawalStatusExtras(tx: tx, onChanged: onChanged),
|
||||
],
|
||||
),
|
||||
],
|
||||
@ -536,19 +545,16 @@ String _formatSignedAmount({
|
||||
}
|
||||
|
||||
Color _statusColor(String status) {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
case 'confirmed':
|
||||
switch (transactionStatusTone(status)) {
|
||||
case TxStatusTone.success:
|
||||
return AppColors.success;
|
||||
case 'pending':
|
||||
case 'broadcasting':
|
||||
case TxStatusTone.warning:
|
||||
return AppColors.warning;
|
||||
case 'rejected':
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
case 'canceled':
|
||||
case TxStatusTone.info:
|
||||
return AppColors.info;
|
||||
case TxStatusTone.danger:
|
||||
return AppColors.danger;
|
||||
default:
|
||||
case TxStatusTone.neutral:
|
||||
return AppColors.textSecondary;
|
||||
}
|
||||
}
|
||||
|
||||
@ -25,6 +25,7 @@ import '../../../shared/widgets/section_error.dart';
|
||||
import '../../wallet/bloc/wallet_bloc.dart';
|
||||
import '../utils/transaction_display.dart';
|
||||
import '../utils/withdraw_eligibility.dart';
|
||||
import 'withdrawal_status_extras.dart';
|
||||
import '../../share_cards/presentation/share_result_widgets.dart';
|
||||
|
||||
// Prefer shared key so Home and Wallet stay in sync (see BalanceHeroCard).
|
||||
@ -1079,6 +1080,15 @@ class _StatusTxTile extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
if (tx.type == 'withdrawal')
|
||||
WithdrawalStatusExtras(
|
||||
tx: tx,
|
||||
onChanged: () {
|
||||
final bloc = context.read<WalletBloc>();
|
||||
bloc.add(const WalletLoadRequested());
|
||||
bloc.add(const WalletActivityRequested(category: 'withdrawals', force: true));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
@ -1295,19 +1305,16 @@ String _formatSignedAmount({
|
||||
}
|
||||
|
||||
Color _statusColor(String status) {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
case 'confirmed':
|
||||
switch (transactionStatusTone(status)) {
|
||||
case TxStatusTone.success:
|
||||
return AppColors.success;
|
||||
case 'pending':
|
||||
case 'broadcasting':
|
||||
case TxStatusTone.warning:
|
||||
return AppColors.warning;
|
||||
case 'rejected':
|
||||
case 'failed':
|
||||
case 'cancelled':
|
||||
case 'canceled':
|
||||
case TxStatusTone.info:
|
||||
return AppColors.info;
|
||||
case TxStatusTone.danger:
|
||||
return AppColors.danger;
|
||||
default:
|
||||
case TxStatusTone.neutral:
|
||||
return AppColors.textSecondary;
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../core/utils/amount_utils.dart';
|
||||
@ -46,6 +47,9 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
|
||||
bool _healthFailed = false;
|
||||
bool _confirming = false;
|
||||
|
||||
/// One key per opened screen: a double tap or a retried request is not duplicated server-side.
|
||||
final String _idempotencyKey = 'wd-${const Uuid().v4()}';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@ -212,6 +216,7 @@ class _WithdrawScreenState extends State<WithdrawScreen> {
|
||||
toAddress: address,
|
||||
amount: amountRaw,
|
||||
totpCode: _totpController.text,
|
||||
idempotencyKey: _idempotencyKey,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@ -0,0 +1,101 @@
|
||||
/// Withdrawal-specific extras under a status chip: refund caption and user cancellation.
|
||||
library;
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../core/di/injection.dart';
|
||||
import '../../../core/errors/app_exception.dart';
|
||||
import '../../../core/theme/app_colors.dart';
|
||||
import '../../../data/models/transaction_model.dart';
|
||||
import '../../../data/repositories/wallet_repository_impl.dart';
|
||||
import '../../../l10n/app_strings.dart';
|
||||
import '../../../shared/widgets/app_snackbar.dart';
|
||||
import '../utils/transaction_display.dart';
|
||||
|
||||
/// Shows "credited back" for refunded withdrawals and a Cancel action while pending.
|
||||
class WithdrawalStatusExtras extends StatefulWidget {
|
||||
const WithdrawalStatusExtras({super.key, required this.tx, required this.onChanged});
|
||||
|
||||
final TransactionModel tx;
|
||||
|
||||
/// Called after a successful cancellation (or a refused one) so the list can reload.
|
||||
final VoidCallback onChanged;
|
||||
|
||||
@override
|
||||
State<WithdrawalStatusExtras> createState() => _WithdrawalStatusExtrasState();
|
||||
}
|
||||
|
||||
class _WithdrawalStatusExtrasState extends State<WithdrawalStatusExtras> {
|
||||
bool _busy = false;
|
||||
|
||||
Future<void> _cancel() async {
|
||||
final s = context.strings;
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(s.cancelWithdrawalTitle),
|
||||
content: Text(s.cancelWithdrawalBody),
|
||||
actions: [
|
||||
TextButton(onPressed: () => Navigator.of(ctx).pop(false), child: Text(s.keepWithdrawal)),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(ctx).pop(true),
|
||||
child: Text(s.cancelWithdrawalConfirm),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (confirmed != true || !mounted) return;
|
||||
setState(() => _busy = true);
|
||||
try {
|
||||
await sl<WalletRepositoryImpl>().cancelWithdrawal(widget.tx.id);
|
||||
if (!mounted) return;
|
||||
showSuccessSnackBar(context, s.cancelWithdrawalSuccess);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
final code = e is DioException ? AppException.fromDio(e).code : null;
|
||||
showErrorSnackBar(
|
||||
context,
|
||||
code == 'WITHDRAWAL_INVALID_TRANSITION' || code == 'WITHDRAWAL_NOT_FOUND'
|
||||
? s.cancelWithdrawalFailed
|
||||
: (e is DioException ? AppException.fromDio(e).message : s.cancelWithdrawalFailed),
|
||||
);
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
widget.onChanged();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final s = context.strings;
|
||||
if (isRefundedWithdrawal(widget.tx)) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
s.withdrawalRefunded,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: AppColors.textSecondary,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (!canCancelWithdrawal(widget.tx)) return const SizedBox.shrink();
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: TextButton(
|
||||
key: Key('cancel_withdrawal_${widget.tx.id}'),
|
||||
onPressed: _busy ? null : _cancel,
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: AppColors.warning,
|
||||
minimumSize: const Size(0, 28),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
child: _busy
|
||||
? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: Text(s.cancelWithdrawalAction, style: const TextStyle(fontSize: 12)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -49,11 +49,17 @@ String transactionLabel(TransactionModel tx, AppStrings s) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Localized transaction status label.
|
||||
/// Localized transaction status label (withdrawal statuses follow the backend state machine).
|
||||
String transactionStatusLabel(String status, AppStrings s) {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
case 'pending_approval':
|
||||
return s.txStatusPending;
|
||||
case 'processing':
|
||||
case 'broadcasting':
|
||||
case 'confirming':
|
||||
case 'ledger_finalize_failed':
|
||||
return s.txStatusProcessing;
|
||||
case 'completed':
|
||||
return s.txStatusCompleted;
|
||||
case 'confirmed':
|
||||
@ -61,17 +67,52 @@ String transactionStatusLabel(String status, AppStrings s) {
|
||||
case 'rejected':
|
||||
return s.txStatusRejected;
|
||||
case 'failed':
|
||||
case 'failed_refunded':
|
||||
return s.txStatusFailed;
|
||||
case 'cancelled':
|
||||
case 'canceled':
|
||||
return s.txStatusCancelled;
|
||||
case 'broadcasting':
|
||||
return s.txStatusBroadcasting;
|
||||
default:
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
/// Visual tone of a status chip.
|
||||
enum TxStatusTone { success, warning, info, danger, neutral }
|
||||
|
||||
TxStatusTone transactionStatusTone(String status) {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
case 'confirmed':
|
||||
return TxStatusTone.success;
|
||||
case 'pending':
|
||||
case 'pending_approval':
|
||||
return TxStatusTone.warning;
|
||||
case 'processing':
|
||||
case 'broadcasting':
|
||||
case 'confirming':
|
||||
case 'ledger_finalize_failed':
|
||||
return TxStatusTone.info;
|
||||
case 'rejected':
|
||||
case 'failed':
|
||||
case 'failed_refunded':
|
||||
case 'cancelled':
|
||||
case 'canceled':
|
||||
return TxStatusTone.danger;
|
||||
default:
|
||||
return TxStatusTone.neutral;
|
||||
}
|
||||
}
|
||||
|
||||
/// A withdrawal the user can still cancel (not yet picked up for payout).
|
||||
bool canCancelWithdrawal(TransactionModel tx) =>
|
||||
tx.type == 'withdrawal' && tx.status == 'pending';
|
||||
|
||||
/// Withdrawal whose reserved amount was credited back to the user.
|
||||
bool isRefundedWithdrawal(TransactionModel tx) =>
|
||||
tx.type == 'withdrawal' &&
|
||||
(tx.status == 'rejected' || tx.status == 'cancelled' || tx.status == 'failed_refunded');
|
||||
|
||||
/// Stake account kind from prediction transaction metadata (`main` / `bonus` / `test`).
|
||||
String? stakeAccountKind(TransactionModel tx) {
|
||||
final raw = tx.metadata?['stake_account_kind']?.toString();
|
||||
|
||||
@ -271,7 +271,27 @@ class AppStrings {
|
||||
String get confirmWithdrawal => t('Confirm withdrawal', 'Confirmer le retrait');
|
||||
String get confirmTransfer => t('Confirm transfer', 'Confirmer le transfert');
|
||||
String get confirmAction => t('Confirm', 'Confirmer');
|
||||
String get withdrawalSubmitted => t('Withdrawal submitted', 'Retrait soumis');
|
||||
String get withdrawalSubmitted => t(
|
||||
'Your withdrawal request has been registered. It will be processed as soon as possible.',
|
||||
'Votre demande de retrait a bien été enregistrée. Elle sera traitée dans les meilleurs délais.',
|
||||
);
|
||||
String get cancelWithdrawalAction => t('Cancel', 'Annuler');
|
||||
String get cancelWithdrawalTitle => t('Cancel this withdrawal?', 'Annuler ce retrait ?');
|
||||
String get cancelWithdrawalBody => t(
|
||||
'The request has not been processed yet. If you cancel it, the full reserved amount (amount + network fee) is credited back to your balance.',
|
||||
'La demande n’a pas encore été traitée. Si vous l’annulez, la totalité du montant réservé (montant + frais réseau) est recréditée sur votre solde.',
|
||||
);
|
||||
String get cancelWithdrawalConfirm => t('Cancel withdrawal', 'Annuler le retrait');
|
||||
String get keepWithdrawal => t('Keep it', 'Conserver');
|
||||
String get cancelWithdrawalSuccess => t(
|
||||
'Withdrawal cancelled. The amount has been credited back to your balance.',
|
||||
'Retrait annulé. Le montant a été recrédité sur votre solde.',
|
||||
);
|
||||
String get cancelWithdrawalFailed => t(
|
||||
'This withdrawal can no longer be cancelled.',
|
||||
'Ce retrait ne peut plus être annulé.',
|
||||
);
|
||||
String get withdrawalRefunded => t('Amount credited back', 'Montant recrédité');
|
||||
String get withdrawalsDisabled => t(
|
||||
'Withdrawals are temporarily disabled by the platform.',
|
||||
'Les retraits sont temporairement désactivés par la plateforme.',
|
||||
@ -430,12 +450,13 @@ class AppStrings {
|
||||
String get txTypeBonus => t('Bonus', 'Bonus');
|
||||
String get txTypeAdminAdjustment => t('Adjustment', 'Ajustement');
|
||||
String get txStatusPending => t('Pending', 'En attente');
|
||||
String get txStatusCompleted => t('Confirmed', 'Confirmé');
|
||||
String get txStatusProcessing => t('Processing', 'En cours');
|
||||
String get txStatusCompleted => t('Completed', 'Terminé');
|
||||
String get txStatusConfirmed => t('Confirmed', 'Confirmé');
|
||||
String get txStatusRejected => t('Rejected', 'Rejeté');
|
||||
String get txStatusRejected => t('Rejected', 'Refusé');
|
||||
String get txStatusFailed => t('Failed', 'Échoué');
|
||||
String get txStatusCancelled => t('Cancelled', 'Annulé');
|
||||
String get txStatusBroadcasting => t('Broadcasting', 'Diffusion');
|
||||
String get txStatusBroadcasting => t('Processing', 'En cours');
|
||||
|
||||
// Prediction
|
||||
String get predictTitle => t('Candle Predict', 'Prédiction bougie');
|
||||
|
||||
@ -97,6 +97,7 @@ class _ControllableWallet implements WalletRepository {
|
||||
String toAddress,
|
||||
String amount, {
|
||||
String? totpCode,
|
||||
String? idempotencyKey,
|
||||
}) async {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
@ -108,6 +108,7 @@ class _FakeWalletRepo implements WalletRepository {
|
||||
String toAddress,
|
||||
String amount, {
|
||||
String? totpCode,
|
||||
String? idempotencyKey,
|
||||
}) async {
|
||||
return const WithdrawResult(transactionId: 'w1', status: 'pending');
|
||||
}
|
||||
|
||||
@ -53,6 +53,7 @@ class _ControllableWallet implements WalletRepository {
|
||||
String toAddress,
|
||||
String amount, {
|
||||
String? totpCode,
|
||||
String? idempotencyKey,
|
||||
}) async =>
|
||||
const WithdrawResult(transactionId: 'w1', status: 'pending');
|
||||
|
||||
|
||||
@ -114,6 +114,7 @@ class _ControllableWallet implements WalletRepository {
|
||||
String toAddress,
|
||||
String amount, {
|
||||
String? totpCode,
|
||||
String? idempotencyKey,
|
||||
}) async {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
62
prediqo_mobile/test/withdrawal_status_display_test.dart
Normal file
62
prediqo_mobile/test/withdrawal_status_display_test.dart
Normal file
@ -0,0 +1,62 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:prediqo_mobile/data/models/transaction_model.dart';
|
||||
import 'package:prediqo_mobile/features/wallet/utils/transaction_display.dart';
|
||||
import 'package:prediqo_mobile/l10n/app_strings.dart';
|
||||
|
||||
TransactionModel _withdrawal(String status) => TransactionModel.fromJson({
|
||||
'id': 'w-$status',
|
||||
'wallet_type_id': 1,
|
||||
'type': 'withdrawal',
|
||||
'amount': '5000000',
|
||||
'fee': '1000000',
|
||||
'status': status,
|
||||
'created_at': '2026-11-12T10:00:00.000Z',
|
||||
});
|
||||
|
||||
void main() {
|
||||
final en = AppStrings(const Locale('en'));
|
||||
final fr = AppStrings(const Locale('fr'));
|
||||
|
||||
test('withdrawal state machine statuses have labels in EN and FR', () {
|
||||
expect(transactionStatusLabel('pending', en), 'Pending');
|
||||
expect(transactionStatusLabel('processing', en), 'Processing');
|
||||
expect(transactionStatusLabel('completed', en), 'Completed');
|
||||
expect(transactionStatusLabel('failed', en), 'Failed');
|
||||
expect(transactionStatusLabel('rejected', en), 'Rejected');
|
||||
expect(transactionStatusLabel('cancelled', en), 'Cancelled');
|
||||
expect(transactionStatusLabel('processing', fr), 'En cours');
|
||||
expect(transactionStatusLabel('rejected', fr), 'Refusé');
|
||||
expect(transactionStatusLabel('completed', fr), 'Terminé');
|
||||
});
|
||||
|
||||
test('legacy statuses map to the closest current label', () {
|
||||
expect(transactionStatusLabel('pending_approval', en), 'Pending');
|
||||
expect(transactionStatusLabel('broadcasting', en), 'Processing');
|
||||
expect(transactionStatusLabel('confirming', en), 'Processing');
|
||||
expect(transactionStatusLabel('failed_refunded', en), 'Failed');
|
||||
});
|
||||
|
||||
test('tones', () {
|
||||
expect(transactionStatusTone('pending'), TxStatusTone.warning);
|
||||
expect(transactionStatusTone('processing'), TxStatusTone.info);
|
||||
expect(transactionStatusTone('completed'), TxStatusTone.success);
|
||||
expect(transactionStatusTone('failed'), TxStatusTone.danger);
|
||||
expect(transactionStatusTone('rejected'), TxStatusTone.danger);
|
||||
});
|
||||
|
||||
test('only a pending withdrawal can be cancelled by the user', () {
|
||||
expect(canCancelWithdrawal(_withdrawal('pending')), isTrue);
|
||||
for (final s in ['processing', 'completed', 'failed', 'rejected', 'cancelled']) {
|
||||
expect(canCancelWithdrawal(_withdrawal(s)), isFalse, reason: s);
|
||||
}
|
||||
});
|
||||
|
||||
test('refunded withdrawals are flagged', () {
|
||||
expect(isRefundedWithdrawal(_withdrawal('rejected')), isTrue);
|
||||
expect(isRefundedWithdrawal(_withdrawal('cancelled')), isTrue);
|
||||
expect(isRefundedWithdrawal(_withdrawal('failed_refunded')), isTrue);
|
||||
expect(isRefundedWithdrawal(_withdrawal('failed')), isFalse);
|
||||
expect(isRefundedWithdrawal(_withdrawal('completed')), isFalse);
|
||||
});
|
||||
}
|
||||
@ -191,6 +191,11 @@ export const ApprovalsPage = lazyNamed(
|
||||
() => import('../../features/approvals/ApprovalsPage'),
|
||||
'ApprovalsPage'
|
||||
);
|
||||
export const WithdrawalsAdminPage = lazyNamed(
|
||||
'WithdrawalsAdminPage',
|
||||
() => import('../../features/withdrawals/WithdrawalsAdminPage'),
|
||||
'WithdrawalsAdminPage'
|
||||
);
|
||||
export const ApprovalPoliciesPage = lazyNamed(
|
||||
'ApprovalPoliciesPage',
|
||||
() => import('../../features/approvals/ApprovalPoliciesPage'),
|
||||
@ -302,6 +307,7 @@ const PATH_PRELOAD: Array<{ path: string; preload: () => Promise<unknown> }> = [
|
||||
{ path: '/admin/catalog', preload: CatalogAdminPage.preload },
|
||||
{ path: '/admin/treasury', preload: TreasuryAdminPage.preload },
|
||||
{ path: '/admin/approvals', preload: ApprovalsPage.preload },
|
||||
{ path: '/admin/withdrawals', preload: WithdrawalsAdminPage.preload },
|
||||
{ path: '/admin/approval-policies', preload: ApprovalPoliciesPage.preload },
|
||||
{ path: '/admin/security', preload: SecurityAdminPage.preload },
|
||||
{ path: '/admin/referral/regularization', preload: ReferralRegularizationPage.preload },
|
||||
|
||||
@ -36,6 +36,7 @@ import {
|
||||
TreasuryAdminPage,
|
||||
ApprovalsPage,
|
||||
ApprovalPoliciesPage,
|
||||
WithdrawalsAdminPage,
|
||||
SecurityAdminPage,
|
||||
ReferralAdminPage,
|
||||
ReferralRegularizationPage,
|
||||
@ -286,6 +287,14 @@ export const router = createBrowserRouter([
|
||||
</L>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/withdrawals',
|
||||
element: (
|
||||
<L>
|
||||
<WithdrawalsAdminPage />
|
||||
</L>
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'admin/approval-policies',
|
||||
element: (
|
||||
|
||||
@ -13,7 +13,7 @@ type SecurityNotification = {
|
||||
};
|
||||
|
||||
export function SecurityNotificationsPanel() {
|
||||
const { t } = useTranslation();
|
||||
const { t, i18n } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
|
||||
const notificationsQ = useQuery({
|
||||
@ -42,6 +42,16 @@ export function SecurityNotificationsPanel() {
|
||||
const items = notificationsQ.data?.items ?? [];
|
||||
const unread = notificationsQ.data?.unreadCount ?? 0;
|
||||
|
||||
/** Localized copy for known event types; falls back to the stored (English) text. */
|
||||
const titleOf = (n: SecurityNotification) => {
|
||||
const key = `profile.securityNotifications.events.${n.eventType}.title`;
|
||||
return i18n.exists(key) ? t(key) : n.title;
|
||||
};
|
||||
const bodyOf = (n: SecurityNotification) => {
|
||||
const key = `profile.securityNotifications.events.${n.eventType}.body`;
|
||||
return i18n.exists(key) ? t(key) : n.body;
|
||||
};
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2, alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
@ -76,16 +86,16 @@ export function SecurityNotificationsPanel() {
|
||||
}}
|
||||
>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center' }}>
|
||||
<Typography sx={{ fontWeight: 700, flex: 1 }}>{n.title}</Typography>
|
||||
<Typography sx={{ fontWeight: 700, flex: 1 }}>{titleOf(n)}</Typography>
|
||||
{!n.readAt && (
|
||||
<Button size="small" onClick={() => markReadMut.mutate(n.id)}>
|
||||
{t('profile.securityNotifications.markRead')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
{n.body && (
|
||||
{bodyOf(n) && (
|
||||
<Typography variant="body2" sx={{ mt: 0.5, opacity: 0.85 }}>
|
||||
{n.body}
|
||||
{bodyOf(n)}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="caption" sx={{ opacity: 0.5 }}>
|
||||
|
||||
@ -65,6 +65,8 @@ export function SettingsPage() {
|
||||
candle_predict_retention_days: number;
|
||||
candle_predict_retention_keep_last: number;
|
||||
withdrawal_network_fee_usdt_micro: number;
|
||||
withdrawal_auto_retry_enabled: boolean;
|
||||
withdrawal_auto_retry_interval_minutes: number;
|
||||
transfer_min_remaining_usdt_micro: number;
|
||||
support_message_edit_window_minutes: number;
|
||||
support_message_delete_window_minutes: number;
|
||||
@ -433,6 +435,32 @@ export function SettingsPage() {
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={effective.withdrawal_auto_retry_enabled ?? false}
|
||||
onChange={(e) => set('withdrawal_auto_retry_enabled', e.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={t('admin.settings.sections.withdrawals.autoRetry')}
|
||||
/>
|
||||
<Box sx={{ maxWidth: { md: '50%' } }}>
|
||||
<TextField
|
||||
label={t('admin.settings.sections.withdrawals.autoRetryInterval')}
|
||||
type="number"
|
||||
slotProps={{ htmlInput: { min: 1, max: 1440, step: 1 } }}
|
||||
value={effective.withdrawal_auto_retry_interval_minutes ?? 10}
|
||||
disabled={!effective.withdrawal_auto_retry_enabled}
|
||||
onChange={(e) =>
|
||||
set(
|
||||
'withdrawal_auto_retry_interval_minutes',
|
||||
Math.min(1440, Math.max(1, parseNum(e.target.value, 10)))
|
||||
)
|
||||
}
|
||||
helperText={t('admin.settings.sections.withdrawals.autoRetryHelper')}
|
||||
fullWidth
|
||||
/>
|
||||
</Box>
|
||||
</Stack>
|
||||
</AccordionDetails>
|
||||
</Accordion>
|
||||
|
||||
@ -327,6 +327,7 @@ export function WalletPage() {
|
||||
onPageChange={setTxPage}
|
||||
emptyMessage={t(`wallet.transactions.empty.${activityCategory}`)}
|
||||
emptyHint={t(`wallet.transactions.emptyHint.${activityCategory}`)}
|
||||
onNotify={setToast}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Lets the user cancel their own withdrawal while it is still pending (refund to balance).
|
||||
*/
|
||||
import { Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle } from '@mui/material';
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import { apiErrorMessage } from '../../../shared/utils/apiError';
|
||||
|
||||
type Props = {
|
||||
transactionId: string;
|
||||
onDone?: (message: string) => void;
|
||||
};
|
||||
|
||||
export function CancelWithdrawalButton({ transactionId, onDone }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const cancelMut = useMutation({
|
||||
mutationFn: () => api.post(`/api/v1/withdrawals/${transactionId}/cancel`),
|
||||
onSuccess: async () => {
|
||||
setOpen(false);
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
onDone?.(t('wallet.transactions.cancelWithdrawal.success'));
|
||||
},
|
||||
onError: (err) => {
|
||||
setOpen(false);
|
||||
void qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
onDone?.(apiErrorMessage(err, t('wallet.transactions.cancelWithdrawal.failed')));
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button size="small" color="warning" onClick={() => setOpen(true)} sx={{ minWidth: 0, px: 1 }}>
|
||||
{t('wallet.transactions.cancelWithdrawal.action')}
|
||||
</Button>
|
||||
<Dialog open={open} onClose={() => !cancelMut.isPending && setOpen(false)}>
|
||||
<DialogTitle>{t('wallet.transactions.cancelWithdrawal.title')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText>{t('wallet.transactions.cancelWithdrawal.body')}</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOpen(false)} disabled={cancelMut.isPending}>
|
||||
{t('common.back')}
|
||||
</Button>
|
||||
<Button
|
||||
color="warning"
|
||||
variant="contained"
|
||||
onClick={() => cancelMut.mutate()}
|
||||
disabled={cancelMut.isPending}
|
||||
>
|
||||
{t('wallet.transactions.cancelWithdrawal.confirm')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -21,9 +21,17 @@ import dayjs from 'dayjs';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { BalanceEntry, WalletTransaction } from '../types';
|
||||
import { coinColors, coinSymbol } from '../utils/coinDisplay';
|
||||
import { isCredit, txLabel, txStatusLabel } from '../utils/transactionDisplay';
|
||||
import {
|
||||
canCancelWithdrawal,
|
||||
isCredit,
|
||||
isRefundedWithdrawal,
|
||||
txLabel,
|
||||
txStatusColor,
|
||||
txStatusLabel,
|
||||
} from '../utils/transactionDisplay';
|
||||
import { rawToHuman, shortSymbol } from '../utils/walletFormat';
|
||||
import { ShareResultButton } from '../../share-cards/ShareResultButton';
|
||||
import { CancelWithdrawalButton } from './CancelWithdrawalButton';
|
||||
|
||||
type TransactionListProps = {
|
||||
transactions: WalletTransaction[];
|
||||
@ -35,6 +43,8 @@ type TransactionListProps = {
|
||||
onPageChange: (page: number) => void;
|
||||
emptyMessage?: string;
|
||||
emptyHint?: string;
|
||||
/** Feedback after a user cancels a pending withdrawal. */
|
||||
onNotify?: (message: string) => void;
|
||||
};
|
||||
|
||||
function predictionShareMeta(tx: WalletTransaction): {
|
||||
@ -100,6 +110,7 @@ export function TransactionList({
|
||||
onPageChange,
|
||||
emptyMessage,
|
||||
emptyHint,
|
||||
onNotify,
|
||||
}: TransactionListProps) {
|
||||
const { t } = useTranslation();
|
||||
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
||||
@ -258,18 +269,22 @@ export function TransactionList({
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
size="small"
|
||||
label={txStatusLabel(tx.status)}
|
||||
color={
|
||||
tx.status === 'completed'
|
||||
? 'success'
|
||||
: tx.status === 'failed'
|
||||
? 'error'
|
||||
: 'default'
|
||||
}
|
||||
variant="outlined"
|
||||
/>
|
||||
<Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Chip
|
||||
size="small"
|
||||
label={txStatusLabel(tx.status)}
|
||||
color={txStatusColor(tx.status)}
|
||||
variant="outlined"
|
||||
/>
|
||||
{isRefundedWithdrawal(tx) && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
{t('wallet.transactions.refunded')}
|
||||
</Typography>
|
||||
)}
|
||||
{canCancelWithdrawal(tx) && (
|
||||
<CancelWithdrawalButton transactionId={tx.id} onDone={onNotify} />
|
||||
)}
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ opacity: 0.8 }}>
|
||||
|
||||
@ -27,6 +27,12 @@ import type { BalanceEntry, NetworkBalanceInfo } from '../types';
|
||||
import { addressPlaceholder, networkLabel } from '../utils/coinDisplay';
|
||||
import { formatBalance, humanToRaw, rawToHuman, shortSymbol } from '../utils/walletFormat';
|
||||
|
||||
function newIdempotencyKey(): string {
|
||||
const c = globalThis.crypto as Crypto | undefined;
|
||||
if (c?.randomUUID) return `wd-${c.randomUUID()}`;
|
||||
return `wd-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
||||
}
|
||||
|
||||
type WithdrawDialogProps = {
|
||||
open: boolean;
|
||||
spendable: BalanceEntry | null;
|
||||
@ -59,6 +65,8 @@ export function WithdrawDialog({
|
||||
const [totpCode, setTotpCode] = useState('');
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
/** One key per opened dialog: a double click or retried request cannot create a second withdrawal. */
|
||||
const [idempotencyKey, setIdempotencyKey] = useState(newIdempotencyKey);
|
||||
|
||||
const withdrawRails = useMemo(
|
||||
() => networks.filter((n) => n.withdrawEnabled === true),
|
||||
@ -99,6 +107,7 @@ export function WithdrawDialog({
|
||||
setAmount('');
|
||||
setTotpCode('');
|
||||
setConfirmOpen(false);
|
||||
setIdempotencyKey(newIdempotencyKey());
|
||||
}, [open, initialRail, withdrawRails]);
|
||||
|
||||
const selectedRail = useMemo(
|
||||
@ -128,11 +137,12 @@ export function WithdrawDialog({
|
||||
const totalDebitLabel = `${rawToHuman(totalDebitRaw.toString(), decimals)} USDT`;
|
||||
|
||||
const submit = async () => {
|
||||
if (!spendable || !selectedRail) return;
|
||||
if (!spendable || !selectedRail || submitting) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const res = await api.post<{
|
||||
await api.post<{
|
||||
transactionId: string;
|
||||
status: string;
|
||||
fee?: string;
|
||||
totalDebited?: string;
|
||||
}>('/api/v1/withdraw', {
|
||||
@ -140,24 +150,17 @@ export function WithdrawDialog({
|
||||
toAddress: toAddress.trim(),
|
||||
amount: humanToRaw(amount, decimals),
|
||||
totpCode: totpCode.trim() || undefined,
|
||||
idempotencyKey,
|
||||
});
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-balances'] });
|
||||
await qc.invalidateQueries({ queryKey: ['wallet-transactions'] });
|
||||
const feeHuman =
|
||||
res.data.fee && res.data.fee !== '0' ? rawToHuman(res.data.fee, decimals) : null;
|
||||
onSuccess?.(
|
||||
feeHuman
|
||||
? t('wallet.withdrawDialog.successWithFee', { fee: feeHuman })
|
||||
: t('wallet.withdrawDialog.success')
|
||||
);
|
||||
onSuccess?.(t('wallet.withdrawDialog.registered'));
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string; code?: string } }; message?: string };
|
||||
const apiErr = err?.response?.data;
|
||||
if (apiErr?.code === 'WITHDRAWAL_2FA_REQUIRED' || /2FA must be enabled/i.test(apiErr?.error ?? '')) {
|
||||
onError?.(t('wallet.withdrawDialog.twoFaRequiredError'));
|
||||
} else if (apiErr?.code === 'HOT_WALLET_INSUFFICIENT_LIQUIDITY') {
|
||||
onError?.(t('wallet.withdrawDialog.liquidityError'));
|
||||
} else if (apiErr?.code === 'WITHDRAWALS_DISABLED') {
|
||||
onError?.(t('wallet.withdrawDisabledGlobal'));
|
||||
} else if (apiErr?.code === 'WITHDRAWAL_NETWORK_DISABLED') {
|
||||
|
||||
@ -71,7 +71,18 @@ export type WalletTransaction = {
|
||||
| 'admin_adjustment';
|
||||
amount: string;
|
||||
fee: string;
|
||||
status: 'pending' | 'confirming' | 'completed' | 'failed';
|
||||
status:
|
||||
| 'pending'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'rejected'
|
||||
| 'cancelled'
|
||||
| 'failed_refunded'
|
||||
| 'confirming'
|
||||
| 'pending_approval'
|
||||
| 'broadcasting'
|
||||
| 'ledger_finalize_failed';
|
||||
blockchain_tx_id: string | null;
|
||||
from_address: string | null;
|
||||
to_address: string | null;
|
||||
@ -90,6 +101,8 @@ export type WalletTransaction = {
|
||||
candle_open_ms?: number;
|
||||
interval_minutes?: number;
|
||||
prediction_mode?: string;
|
||||
/** Set when a rejected / cancelled withdrawal was credited back. */
|
||||
refund?: { amount: string; refunded_at: string };
|
||||
} | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
|
||||
@ -43,12 +43,52 @@ export function txLabel(tx: WalletTransaction): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** Legacy withdrawal statuses shown with their closest current label. */
|
||||
const LEGACY_STATUS_ALIAS: Record<string, string> = {
|
||||
pending_approval: 'pending',
|
||||
broadcasting: 'processing',
|
||||
confirming: 'processing',
|
||||
ledger_finalize_failed: 'processing',
|
||||
};
|
||||
|
||||
/** Localized transaction status label when a known key exists. */
|
||||
export function txStatusLabel(status: string): string {
|
||||
const key = `wallet.transactions.status.${status}`;
|
||||
const key = `wallet.transactions.status.${LEGACY_STATUS_ALIAS[status] ?? status}`;
|
||||
return i18n.exists(key) ? i18n.t(key) : status;
|
||||
}
|
||||
|
||||
export type TxStatusColor = 'success' | 'error' | 'warning' | 'info' | 'default';
|
||||
|
||||
export function txStatusColor(status: string): TxStatusColor {
|
||||
switch (LEGACY_STATUS_ALIAS[status] ?? status) {
|
||||
case 'completed':
|
||||
return 'success';
|
||||
case 'failed':
|
||||
case 'rejected':
|
||||
case 'failed_refunded':
|
||||
return 'error';
|
||||
case 'processing':
|
||||
return 'info';
|
||||
case 'pending':
|
||||
return 'warning';
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
}
|
||||
|
||||
/** A withdrawal the user can still cancel (not yet picked up for payout). */
|
||||
export function canCancelWithdrawal(tx: WalletTransaction): boolean {
|
||||
return tx.type === 'withdrawal' && tx.status === 'pending';
|
||||
}
|
||||
|
||||
/** Withdrawal whose reserved amount was credited back to the user. */
|
||||
export function isRefundedWithdrawal(tx: WalletTransaction): boolean {
|
||||
return (
|
||||
tx.type === 'withdrawal' &&
|
||||
(tx.status === 'rejected' || tx.status === 'cancelled' || tx.status === 'failed_refunded')
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the amount increases the user's balance (shown with + and credit color). */
|
||||
export function isCredit(tx: WalletTransaction): boolean {
|
||||
if (tx.type === 'transfer') return tx.metadata?.direction === 'in';
|
||||
|
||||
668
prediqo_web/src/features/withdrawals/WithdrawalsAdminPage.tsx
Normal file
668
prediqo_web/src/features/withdrawals/WithdrawalsAdminPage.tsx
Normal file
@ -0,0 +1,668 @@
|
||||
/**
|
||||
* Admin queue of withdrawal requests (pending / processing / failed) with history,
|
||||
* live hot-wallet liquidity check and process / requeue / reject actions.
|
||||
*/
|
||||
import {
|
||||
Alert,
|
||||
Box,
|
||||
Button,
|
||||
Card,
|
||||
CardActionArea,
|
||||
CardContent,
|
||||
Chip,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
Divider,
|
||||
Grid,
|
||||
MenuItem,
|
||||
Stack,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TablePagination,
|
||||
TableRow,
|
||||
TextField,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import PaymentsRoundedIcon from '@mui/icons-material/PaymentsRounded';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { api } from '../../shared/services/api';
|
||||
import { PageHeader, RefreshIconButton } from '../../shared/components/PageHeader';
|
||||
import { ScrollableTable } from '../../shared/components/ScrollableTable';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
import { apiErrorMessage } from '../../shared/utils/apiError';
|
||||
import { humanToRaw, rawToHuman } from '../wallet/utils/walletFormat';
|
||||
|
||||
type WithdrawalStatus =
|
||||
| 'pending'
|
||||
| 'processing'
|
||||
| 'completed'
|
||||
| 'failed'
|
||||
| 'rejected'
|
||||
| 'cancelled'
|
||||
| 'failed_refunded'
|
||||
| string;
|
||||
|
||||
type AdminWithdrawal = {
|
||||
id: string;
|
||||
userId: string;
|
||||
userEmail: string | null;
|
||||
userName: string | null;
|
||||
amount: string;
|
||||
fee: string;
|
||||
totalDebited: string;
|
||||
currency: string;
|
||||
network: string | null;
|
||||
railWalletType: string | null;
|
||||
toAddress: string | null;
|
||||
status: WithdrawalStatus;
|
||||
pendingReason: string | null;
|
||||
processingStage: string | null;
|
||||
attempts: number;
|
||||
lastError: string | null;
|
||||
blockchainTxId: string | null;
|
||||
abandonedTxHashes: string[];
|
||||
confirmations: number;
|
||||
requiredConfirmations: number | null;
|
||||
rejectionReason: string | null;
|
||||
refundedAt: string | null;
|
||||
fundRequestId: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
legacy: boolean;
|
||||
actions: { canProcess: boolean; canRequeue: boolean; canReject: boolean };
|
||||
};
|
||||
|
||||
type ListResponse = {
|
||||
items: AdminWithdrawal[];
|
||||
total: number;
|
||||
counts: { pending: number; processing: number; failed: number };
|
||||
pendingReasons: Record<string, number>;
|
||||
autoRetry?: { enabled: boolean; intervalMinutes: number };
|
||||
};
|
||||
|
||||
type DetailResponse = {
|
||||
withdrawal: AdminWithdrawal;
|
||||
history: Array<{
|
||||
id: string;
|
||||
fromStatus: string | null;
|
||||
toStatus: string;
|
||||
actorType: 'user' | 'admin' | 'system';
|
||||
actorUserId: string | null;
|
||||
reason: string | null;
|
||||
createdAt: string;
|
||||
}>;
|
||||
liquidity: {
|
||||
network: string;
|
||||
hotAddress: string | null;
|
||||
usdtBalanceRaw: string | null;
|
||||
nativeBalanceRaw: string | null;
|
||||
inFlightLedgerRaw: string;
|
||||
canPay: boolean;
|
||||
shortfall: 'usdt' | 'gas' | 'no_hot_wallet' | null;
|
||||
error?: string;
|
||||
} | null;
|
||||
};
|
||||
|
||||
type ProcessResult = { status: string; pendingReason?: string | null; message?: string };
|
||||
|
||||
const STATUS_FILTERS = ['open', 'pending', 'processing', 'failed', 'completed', 'rejected', 'cancelled', 'all'] as const;
|
||||
const LEDGER_DECIMALS = 6;
|
||||
|
||||
function statusColor(status: string): 'warning' | 'info' | 'error' | 'success' | 'default' {
|
||||
if (status === 'pending') return 'warning';
|
||||
if (status === 'processing') return 'info';
|
||||
if (status === 'failed' || status === 'rejected' || status === 'failed_refunded') return 'error';
|
||||
if (status === 'completed') return 'success';
|
||||
return 'default';
|
||||
}
|
||||
|
||||
function shortValue(v: string | null, head = 8, tail = 6): string {
|
||||
if (!v) return '—';
|
||||
return v.length > head + tail + 1 ? `${v.slice(0, head)}…${v.slice(-tail)}` : v;
|
||||
}
|
||||
|
||||
function usdt(raw: string): string {
|
||||
return `${rawToHuman(raw, LEDGER_DECIMALS)} USDT`;
|
||||
}
|
||||
|
||||
function chainUsdtDecimals(network: string): number {
|
||||
return network === 'BSC' ? 18 : 6;
|
||||
}
|
||||
|
||||
function nativeLabel(network: string, raw: string | null): string {
|
||||
if (raw == null) return '—';
|
||||
return network === 'BSC' ? `${rawToHuman(raw, 18)} BNB` : `${rawToHuman(raw, 6)} TRX`;
|
||||
}
|
||||
|
||||
export function WithdrawalsAdminPage() {
|
||||
const { t } = useTranslation();
|
||||
const qc = useQueryClient();
|
||||
const { can } = useAuth();
|
||||
const canManage = can('admin.withdrawals.manage');
|
||||
|
||||
const [status, setStatus] = useState<(typeof STATUS_FILTERS)[number]>('open');
|
||||
const [network, setNetwork] = useState<'' | 'TRON' | 'BSC'>('');
|
||||
const [from, setFrom] = useState('');
|
||||
const [to, setTo] = useState('');
|
||||
const [minAmount, setMinAmount] = useState('');
|
||||
const [maxAmount, setMaxAmount] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(0);
|
||||
const [rowsPerPage, setRowsPerPage] = useState(25);
|
||||
const [detailId, setDetailId] = useState<string | null>(null);
|
||||
const [rejectId, setRejectId] = useState<string | null>(null);
|
||||
const [rejectReason, setRejectReason] = useState('');
|
||||
const [message, setMessage] = useState<{ severity: 'success' | 'info' | 'warning'; text: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => setPage(0), [status, network, from, to, minAmount, maxAmount, search, rowsPerPage]);
|
||||
|
||||
const params = useMemo(() => {
|
||||
const p: Record<string, string> = {
|
||||
status,
|
||||
limit: String(rowsPerPage),
|
||||
offset: String(page * rowsPerPage),
|
||||
};
|
||||
if (network) p.network = network;
|
||||
if (from) p.from = new Date(`${from}T00:00:00`).toISOString();
|
||||
if (to) p.to = new Date(`${to}T23:59:59`).toISOString();
|
||||
try {
|
||||
if (minAmount.trim()) p.minAmount = humanToRaw(minAmount.trim(), LEDGER_DECIMALS);
|
||||
if (maxAmount.trim()) p.maxAmount = humanToRaw(maxAmount.trim(), LEDGER_DECIMALS);
|
||||
} catch {
|
||||
/* invalid amount input is ignored */
|
||||
}
|
||||
if (search.trim()) p.search = search.trim();
|
||||
return p;
|
||||
}, [status, network, from, to, minAmount, maxAmount, search, page, rowsPerPage]);
|
||||
|
||||
const listQ = useQuery({
|
||||
queryKey: ['admin-withdrawals', params],
|
||||
queryFn: async () => (await api.get<ListResponse>('/api/v1/admin/withdrawals', { params })).data,
|
||||
refetchInterval: 30_000,
|
||||
});
|
||||
|
||||
const detailQ = useQuery({
|
||||
queryKey: ['admin-withdrawals', 'detail', detailId],
|
||||
queryFn: async () => (await api.get<DetailResponse>(`/api/v1/admin/withdrawals/${detailId}`)).data,
|
||||
enabled: !!detailId,
|
||||
});
|
||||
|
||||
const refreshAll = () => void qc.invalidateQueries({ queryKey: ['admin-withdrawals'] });
|
||||
|
||||
const processMut = useMutation({
|
||||
mutationFn: async (id: string) =>
|
||||
(await api.post<ProcessResult>(`/api/v1/admin/withdrawals/${id}/process`)).data,
|
||||
onSuccess: (res) => {
|
||||
setError(null);
|
||||
if (res.status === 'processing') {
|
||||
setMessage({ severity: 'success', text: t('admin.withdrawals.processStarted') });
|
||||
} else if (res.status === 'pending') {
|
||||
setMessage({
|
||||
severity: 'warning',
|
||||
text: t('admin.withdrawals.stillPending', {
|
||||
reason: t(`admin.withdrawals.reasons.${res.pendingReason ?? 'queued'}`),
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
setMessage({ severity: 'warning', text: t('admin.withdrawals.processFailed', { error: res.message ?? '' }) });
|
||||
}
|
||||
refreshAll();
|
||||
},
|
||||
onError: (err) => setError(apiErrorMessage(err, t('admin.withdrawals.actionFailed'))),
|
||||
});
|
||||
|
||||
const requeueMut = useMutation({
|
||||
mutationFn: (id: string) => api.post(`/api/v1/admin/withdrawals/${id}/requeue`),
|
||||
onSuccess: () => {
|
||||
setError(null);
|
||||
setMessage({ severity: 'info', text: t('admin.withdrawals.requeued') });
|
||||
refreshAll();
|
||||
},
|
||||
onError: (err) => setError(apiErrorMessage(err, t('admin.withdrawals.actionFailed'))),
|
||||
});
|
||||
|
||||
const rejectMut = useMutation({
|
||||
mutationFn: ({ id, reason }: { id: string; reason: string }) =>
|
||||
api.post(`/api/v1/admin/withdrawals/${id}/reject`, { reason }),
|
||||
onSuccess: () => {
|
||||
setRejectId(null);
|
||||
setRejectReason('');
|
||||
setError(null);
|
||||
setMessage({ severity: 'success', text: t('admin.withdrawals.rejected') });
|
||||
refreshAll();
|
||||
},
|
||||
onError: (err) => setError(apiErrorMessage(err, t('admin.withdrawals.actionFailed'))),
|
||||
});
|
||||
|
||||
const busy = processMut.isPending || requeueMut.isPending || rejectMut.isPending;
|
||||
const counts = listQ.data?.counts ?? { pending: 0, processing: 0, failed: 0 };
|
||||
const reasons = listQ.data?.pendingReasons ?? {};
|
||||
const items = listQ.data?.items ?? [];
|
||||
|
||||
const statusLabel = (s: string) =>
|
||||
t(`admin.withdrawals.status.${s}`, { defaultValue: s });
|
||||
const reasonLabel = (r: string | null) =>
|
||||
r ? t(`admin.withdrawals.reasons.${r}`, { defaultValue: r }) : '';
|
||||
|
||||
const renderActions = (w: AdminWithdrawal, size: 'small' | 'medium' = 'small') => (
|
||||
<Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', rowGap: 1 }}>
|
||||
<Button size={size} onClick={() => setDetailId(w.id)}>
|
||||
{t('admin.withdrawals.details')}
|
||||
</Button>
|
||||
{canManage && w.actions.canProcess && (
|
||||
<Button size={size} variant="contained" disabled={busy} onClick={() => processMut.mutate(w.id)}>
|
||||
{w.status === 'failed' ? t('admin.withdrawals.retry') : t('admin.withdrawals.process')}
|
||||
</Button>
|
||||
)}
|
||||
{canManage && w.actions.canRequeue && (
|
||||
<Button size={size} disabled={busy} onClick={() => requeueMut.mutate(w.id)}>
|
||||
{t('admin.withdrawals.requeue')}
|
||||
</Button>
|
||||
)}
|
||||
{canManage && w.actions.canReject && (
|
||||
<Button size={size} color="error" disabled={busy} onClick={() => setRejectId(w.id)}>
|
||||
{t('admin.withdrawals.reject')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
|
||||
const counterCard = (key: 'pending' | 'processing' | 'failed', color: string) => (
|
||||
<Grid size={{ xs: 12, sm: 4 }} key={key}>
|
||||
<Card variant="outlined" sx={{ borderColor: status === key ? color : undefined }}>
|
||||
<CardActionArea onClick={() => setStatus(key)}>
|
||||
<CardContent>
|
||||
<Typography variant="overline" sx={{ opacity: 0.75 }}>
|
||||
{statusLabel(key)}
|
||||
</Typography>
|
||||
<Typography variant="h4" sx={{ fontWeight: 800, color }}>
|
||||
{counts[key]}
|
||||
</Typography>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
</Grid>
|
||||
);
|
||||
|
||||
const detail = detailQ.data;
|
||||
|
||||
return (
|
||||
<Box sx={{ minWidth: 0 }}>
|
||||
<PageHeader
|
||||
icon={<PaymentsRoundedIcon color="primary" sx={{ fontSize: 36 }} />}
|
||||
title={t('admin.withdrawals.title')}
|
||||
subtitle={t('admin.withdrawals.subtitle')}
|
||||
actions={<RefreshIconButton label={t('admin.withdrawals.refresh')} onClick={refreshAll} />}
|
||||
/>
|
||||
|
||||
{message && (
|
||||
<Alert severity={message.severity} onClose={() => setMessage(null)} sx={{ mb: 2 }}>
|
||||
{message.text}
|
||||
</Alert>
|
||||
)}
|
||||
{error && (
|
||||
<Alert severity="error" onClose={() => setError(null)} sx={{ mb: 2 }}>
|
||||
{error}
|
||||
</Alert>
|
||||
)}
|
||||
{!canManage && (
|
||||
<Alert severity="info" sx={{ mb: 2 }}>
|
||||
{t('admin.withdrawals.readOnly')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<Grid container spacing={2} sx={{ mb: 2 }}>
|
||||
{counterCard('pending', '#ED6C02')}
|
||||
{counterCard('processing', '#0288D1')}
|
||||
{counterCard('failed', '#D32F2F')}
|
||||
</Grid>
|
||||
|
||||
{listQ.data?.autoRetry && (
|
||||
<Alert severity={listQ.data.autoRetry.enabled ? 'success' : 'info'} sx={{ mb: 2 }}>
|
||||
{listQ.data.autoRetry.enabled
|
||||
? t('admin.withdrawals.autoRetryOn', { minutes: listQ.data.autoRetry.intervalMinutes })
|
||||
: t('admin.withdrawals.autoRetryOff')}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{Object.keys(reasons).length > 0 && (
|
||||
<Stack direction="row" spacing={1} sx={{ mb: 2, flexWrap: 'wrap', rowGap: 1, alignItems: 'center' }}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.7 }}>
|
||||
{t('admin.withdrawals.pendingBreakdown')}
|
||||
</Typography>
|
||||
{Object.entries(reasons).map(([reason, n]) => (
|
||||
<Chip
|
||||
key={reason}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
color={reason === 'awaiting_liquidity' || reason === 'awaiting_gas' ? 'warning' : 'default'}
|
||||
label={`${reasonLabel(reason)} · ${n}`}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
<Stack direction={{ xs: 'column', md: 'row' }} spacing={1.5} sx={{ mb: 2 }}>
|
||||
<TextField
|
||||
select
|
||||
size="small"
|
||||
label={t('common.status')}
|
||||
value={status}
|
||||
onChange={(e) => setStatus(e.target.value as (typeof STATUS_FILTERS)[number])}
|
||||
sx={{ minWidth: 170 }}
|
||||
>
|
||||
{STATUS_FILTERS.map((s) => (
|
||||
<MenuItem key={s} value={s}>
|
||||
{statusLabel(s)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
<TextField
|
||||
select
|
||||
size="small"
|
||||
label={t('admin.withdrawals.network')}
|
||||
value={network}
|
||||
onChange={(e) => setNetwork(e.target.value as '' | 'TRON' | 'BSC')}
|
||||
sx={{ minWidth: 140 }}
|
||||
>
|
||||
<MenuItem value="">{t('admin.withdrawals.allNetworks')}</MenuItem>
|
||||
<MenuItem value="TRON">TRC20 (TRON)</MenuItem>
|
||||
<MenuItem value="BSC">BEP20 (BSC)</MenuItem>
|
||||
</TextField>
|
||||
<TextField
|
||||
size="small"
|
||||
type="date"
|
||||
label={t('admin.withdrawals.from')}
|
||||
value={from}
|
||||
onChange={(e) => setFrom(e.target.value)}
|
||||
slotProps={{ inputLabel: { shrink: true } }}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
type="date"
|
||||
label={t('admin.withdrawals.to')}
|
||||
value={to}
|
||||
onChange={(e) => setTo(e.target.value)}
|
||||
slotProps={{ inputLabel: { shrink: true } }}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.withdrawals.minAmount')}
|
||||
value={minAmount}
|
||||
onChange={(e) => setMinAmount(e.target.value)}
|
||||
sx={{ maxWidth: 130 }}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.withdrawals.maxAmount')}
|
||||
value={maxAmount}
|
||||
onChange={(e) => setMaxAmount(e.target.value)}
|
||||
sx={{ maxWidth: 130 }}
|
||||
/>
|
||||
<TextField
|
||||
size="small"
|
||||
label={t('admin.withdrawals.search')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
sx={{ flex: 1, minWidth: 200 }}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{listQ.isError && (
|
||||
<Alert severity="error" sx={{ mb: 2 }}>
|
||||
{apiErrorMessage(listQ.error, t('admin.withdrawals.loadError'))}
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
<ScrollableTable minWidth={1100}>
|
||||
<Table size="small">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>{t('admin.withdrawals.created')}</TableCell>
|
||||
<TableCell>{t('admin.withdrawals.user')}</TableCell>
|
||||
<TableCell align="right">{t('admin.withdrawals.amount')}</TableCell>
|
||||
<TableCell>{t('admin.withdrawals.network')}</TableCell>
|
||||
<TableCell>{t('admin.withdrawals.destination')}</TableCell>
|
||||
<TableCell>{t('common.status')}</TableCell>
|
||||
<TableCell align="center">{t('admin.withdrawals.attempts')}</TableCell>
|
||||
<TableCell>{t('admin.withdrawals.actions')}</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{items.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={8}>
|
||||
<Typography variant="body2" sx={{ opacity: 0.6 }}>
|
||||
{listQ.isLoading ? t('common.loading') : t('admin.withdrawals.empty')}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
items.map((w) => (
|
||||
<TableRow key={w.id} hover>
|
||||
<TableCell sx={{ whiteSpace: 'nowrap' }}>{new Date(w.createdAt).toLocaleString()}</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ fontWeight: 600 }}>
|
||||
{w.userEmail ?? shortValue(w.userId)}
|
||||
</Typography>
|
||||
{w.userName && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7 }}>
|
||||
{w.userName}
|
||||
</Typography>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Typography variant="body2" sx={{ fontWeight: 700 }}>
|
||||
{usdt(w.amount)}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65 }}>
|
||||
{t('admin.withdrawals.feeAndTotal', { fee: usdt(w.fee), total: usdt(w.totalDebited) })}
|
||||
</Typography>
|
||||
</TableCell>
|
||||
<TableCell>{w.network === 'BSC' ? 'BEP20' : w.network === 'TRON' ? 'TRC20' : '—'}</TableCell>
|
||||
<TableCell sx={{ fontFamily: 'ui-monospace, monospace', fontSize: 12 }}>
|
||||
{shortValue(w.toAddress)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Stack spacing={0.5} sx={{ alignItems: 'flex-start' }}>
|
||||
<Chip size="small" label={statusLabel(w.status)} color={statusColor(w.status)} />
|
||||
{w.pendingReason && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.8 }}>
|
||||
{reasonLabel(w.pendingReason)}
|
||||
</Typography>
|
||||
)}
|
||||
{w.status === 'processing' && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.8 }}>
|
||||
{t('admin.withdrawals.confirmations', {
|
||||
n: w.confirmations,
|
||||
required: w.requiredConfirmations ?? '?',
|
||||
})}
|
||||
</Typography>
|
||||
)}
|
||||
{w.legacy && <Chip size="small" variant="outlined" label={t('admin.withdrawals.legacy')} />}
|
||||
</Stack>
|
||||
</TableCell>
|
||||
<TableCell align="center">{w.attempts}</TableCell>
|
||||
<TableCell>{renderActions(w)}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollableTable>
|
||||
<TablePagination
|
||||
component="div"
|
||||
count={listQ.data?.total ?? 0}
|
||||
page={page}
|
||||
onPageChange={(_, p) => setPage(p)}
|
||||
rowsPerPage={rowsPerPage}
|
||||
onRowsPerPageChange={(e) => setRowsPerPage(parseInt(e.target.value, 10))}
|
||||
rowsPerPageOptions={[25, 50, 100]}
|
||||
/>
|
||||
|
||||
<Dialog open={!!detailId} onClose={() => setDetailId(null)} maxWidth="md" fullWidth>
|
||||
<DialogTitle>{t('admin.withdrawals.detailTitle')}</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
{detailQ.isLoading && <Typography>{t('common.loading')}</Typography>}
|
||||
{detailQ.isError && <Alert severity="error">{apiErrorMessage(detailQ.error, t('admin.withdrawals.loadError'))}</Alert>}
|
||||
{detail && (
|
||||
<Stack spacing={2}>
|
||||
<Stack direction="row" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>
|
||||
<Chip label={statusLabel(detail.withdrawal.status)} color={statusColor(detail.withdrawal.status)} />
|
||||
{detail.withdrawal.pendingReason && (
|
||||
<Chip variant="outlined" label={reasonLabel(detail.withdrawal.pendingReason)} />
|
||||
)}
|
||||
<Typography variant="body2" sx={{ fontFamily: 'monospace', opacity: 0.7 }}>
|
||||
{detail.withdrawal.id}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
<Grid container spacing={1.5}>
|
||||
{[
|
||||
[t('admin.withdrawals.user'), detail.withdrawal.userEmail ?? detail.withdrawal.userId],
|
||||
[t('admin.withdrawals.amount'), usdt(detail.withdrawal.amount)],
|
||||
[t('admin.withdrawals.fee'), usdt(detail.withdrawal.fee)],
|
||||
[t('admin.withdrawals.totalReserved'), usdt(detail.withdrawal.totalDebited)],
|
||||
[t('admin.withdrawals.network'), `${detail.withdrawal.network ?? '—'} · ${detail.withdrawal.railWalletType ?? ''}`],
|
||||
[t('admin.withdrawals.destination'), detail.withdrawal.toAddress ?? '—'],
|
||||
[t('admin.withdrawals.created'), new Date(detail.withdrawal.createdAt).toLocaleString()],
|
||||
[t('admin.withdrawals.attempts'), String(detail.withdrawal.attempts)],
|
||||
[t('admin.withdrawals.txHash'), detail.withdrawal.blockchainTxId ?? '—'],
|
||||
[
|
||||
t('admin.withdrawals.confirmationsLabel'),
|
||||
`${detail.withdrawal.confirmations} / ${detail.withdrawal.requiredConfirmations ?? '?'}`,
|
||||
],
|
||||
].map(([label, value]) => (
|
||||
<Grid size={{ xs: 12, sm: 6 }} key={label}>
|
||||
<Typography variant="caption" sx={{ opacity: 0.65 }}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ wordBreak: 'break-all' }}>
|
||||
{value}
|
||||
</Typography>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
|
||||
{detail.withdrawal.lastError && (
|
||||
<Alert severity="warning">
|
||||
<strong>{t('admin.withdrawals.lastError')}:</strong> {detail.withdrawal.lastError}
|
||||
</Alert>
|
||||
)}
|
||||
{detail.withdrawal.rejectionReason && (
|
||||
<Alert severity="info">
|
||||
<strong>{t('admin.withdrawals.rejectionReason')}:</strong> {detail.withdrawal.rejectionReason}
|
||||
</Alert>
|
||||
)}
|
||||
{detail.withdrawal.abandonedTxHashes.length > 0 && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.7, wordBreak: 'break-all' }}>
|
||||
{t('admin.withdrawals.abandonedHashes')}: {detail.withdrawal.abandonedTxHashes.join(', ')}
|
||||
</Typography>
|
||||
)}
|
||||
{detail.withdrawal.pendingReason === 'awaiting_approval' && (
|
||||
<Alert severity="info">{t('admin.withdrawals.awaitingApprovalHint')}</Alert>
|
||||
)}
|
||||
|
||||
{detail.liquidity && (
|
||||
<Box>
|
||||
<Divider sx={{ mb: 1.5 }} />
|
||||
<Typography variant="subtitle2" sx={{ mb: 1 }}>
|
||||
{t('admin.withdrawals.liquidityTitle', { network: detail.liquidity.network })}
|
||||
</Typography>
|
||||
{detail.liquidity.error ? (
|
||||
<Alert severity="error">{detail.liquidity.error}</Alert>
|
||||
) : (
|
||||
<Stack spacing={0.5}>
|
||||
<Alert severity={detail.liquidity.canPay ? 'success' : 'warning'}>
|
||||
{detail.liquidity.canPay
|
||||
? t('admin.withdrawals.liquidityOk')
|
||||
: t(`admin.withdrawals.shortfall.${detail.liquidity.shortfall ?? 'usdt'}`)}
|
||||
</Alert>
|
||||
<Typography variant="body2">
|
||||
USDT:{' '}
|
||||
{detail.liquidity.usdtBalanceRaw != null
|
||||
? rawToHuman(detail.liquidity.usdtBalanceRaw, chainUsdtDecimals(detail.liquidity.network))
|
||||
: '—'}{' '}
|
||||
· {t('admin.withdrawals.gas')}: {nativeLabel(detail.liquidity.network, detail.liquidity.nativeBalanceRaw)} ·{' '}
|
||||
{t('admin.withdrawals.inFlight')}: {usdt(detail.liquidity.inFlightLedgerRaw)}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ fontFamily: 'monospace', opacity: 0.7 }}>
|
||||
{detail.liquidity.hotAddress ?? '—'}
|
||||
</Typography>
|
||||
</Stack>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box>
|
||||
<Divider sx={{ mb: 1.5 }} />
|
||||
<Typography variant="subtitle2" sx={{ mb: 1 }}>
|
||||
{t('admin.withdrawals.history')}
|
||||
</Typography>
|
||||
<Stack spacing={0.75}>
|
||||
{detail.history.map((h) => (
|
||||
<Stack key={h.id} direction="row" spacing={1} sx={{ alignItems: 'baseline', flexWrap: 'wrap' }}>
|
||||
<Typography variant="caption" sx={{ opacity: 0.6, minWidth: 150 }}>
|
||||
{new Date(h.createdAt).toLocaleString()}
|
||||
</Typography>
|
||||
<Typography variant="body2">
|
||||
{h.fromStatus ? `${statusLabel(h.fromStatus)} → ` : ''}
|
||||
<strong>{statusLabel(h.toStatus)}</strong>
|
||||
</Typography>
|
||||
<Chip size="small" variant="outlined" label={t(`admin.withdrawals.actor.${h.actorType}`)} />
|
||||
{h.reason && (
|
||||
<Typography variant="caption" sx={{ opacity: 0.75 }}>
|
||||
{reasonLabel(h.reason) || h.reason}
|
||||
</Typography>
|
||||
)}
|
||||
</Stack>
|
||||
))}
|
||||
</Stack>
|
||||
</Box>
|
||||
</Stack>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
{detail && renderActions(detail.withdrawal, 'medium')}
|
||||
<Box sx={{ flex: 1 }} />
|
||||
<Button onClick={() => setDetailId(null)}>{t('common.close')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={!!rejectId} onClose={() => setRejectId(null)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle>{t('admin.withdrawals.rejectTitle')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<Typography variant="body2" sx={{ mb: 2, opacity: 0.8 }}>
|
||||
{t('admin.withdrawals.rejectHint')}
|
||||
</Typography>
|
||||
<TextField
|
||||
label={t('admin.withdrawals.rejectionReason')}
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={2}
|
||||
value={rejectReason}
|
||||
onChange={(e) => setRejectReason(e.target.value)}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setRejectId(null)}>{t('common.cancel')}</Button>
|
||||
<Button
|
||||
color="error"
|
||||
variant="contained"
|
||||
disabled={rejectReason.trim().length < 3 || rejectMut.isPending}
|
||||
onClick={() => rejectId && rejectMut.mutate({ id: rejectId, reason: rejectReason.trim() })}
|
||||
>
|
||||
{t('admin.withdrawals.reject')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@ -20,12 +20,12 @@ const LEGACY_IMPLIES: Record<string, string[]> = {
|
||||
'admin.mobile_releases.manage',
|
||||
],
|
||||
'referral.admin': ['admin.referral.view', 'admin.referral.manage', 'admin.referral_fraud.view'],
|
||||
'treasury.view': ['admin.treasury.view', 'admin.treasury.manage'],
|
||||
'treasury.view': ['admin.treasury.view', 'admin.treasury.manage', 'admin.withdrawals.view'],
|
||||
'security.admin': ['admin.security.view', 'admin.security.manage'],
|
||||
'ledger.credit': ['admin.ledger_credit.manage'],
|
||||
'user.manage_roles': ['admin.rbac.view', 'admin.rbac.manage'],
|
||||
'fund_operation.request': ['admin.fund_operations.request'],
|
||||
'fund_operation.approve': ['admin.fund_operations.approve'],
|
||||
'fund_operation.approve': ['admin.fund_operations.approve', 'admin.withdrawals.manage'],
|
||||
'approval_policy.view': ['admin.approval_policies.view'],
|
||||
'approval_policy.manage': ['admin.approval_policies.manage'],
|
||||
};
|
||||
@ -66,6 +66,7 @@ export const ADMIN_PAGE_PERMISSIONS: Record<string, string> = {
|
||||
'/admin/settings': 'admin.settings.view',
|
||||
'/admin/catalog': 'admin.games.view',
|
||||
'/admin/treasury': 'admin.treasury.view',
|
||||
'/admin/withdrawals': 'admin.withdrawals.view',
|
||||
'/admin/approvals': 'admin.fund_operations.approve',
|
||||
'/admin/approval-policies': 'admin.fund_operations.approve',
|
||||
'/admin/security': 'admin.security.view',
|
||||
|
||||
@ -73,6 +73,7 @@ export const en = {
|
||||
options: 'Options',
|
||||
marketing: 'Marketing',
|
||||
users: 'Users',
|
||||
withdrawals: 'Withdrawals',
|
||||
security: 'Security',
|
||||
settings: 'Settings',
|
||||
},
|
||||
@ -450,9 +451,7 @@ export const en = {
|
||||
payoutNetwork: 'Payout network',
|
||||
withdrawable: 'up to {{amount}} USDT',
|
||||
crossNetworkHint:
|
||||
'You can withdraw on TRON or BSC regardless of where you deposited. Wins count toward your spendable USDT. If a network is temporarily unavailable, the platform hot wallet may need more USDT or gas — try the other network or retry later.',
|
||||
liquidityError:
|
||||
'Withdrawals on this network are temporarily unavailable (platform liquidity). Try the other network or try again later.',
|
||||
'You can withdraw on TRON or BSC regardless of where you deposited. Wins count toward your spendable USDT. Your request is recorded immediately and processed as soon as possible.',
|
||||
inventoryHint:
|
||||
'You can only withdraw on a network up to your inventory on that network (from deposits there). Game wins increase your spendable USDT but may not increase network inventory.',
|
||||
inventoryError: 'Not enough inventory on the selected network for this withdrawal.',
|
||||
@ -475,9 +474,9 @@ export const en = {
|
||||
networkFeeLabel: 'Network fee:',
|
||||
totalDebited: 'Total debited from your balance:',
|
||||
broadcastIrreversible: 'This transaction is irreversible once broadcast.',
|
||||
withdrawing: 'Withdrawing…',
|
||||
success: 'Withdrawal submitted successfully',
|
||||
successWithFee: 'Withdrawal submitted successfully (fee {{fee}} USDT)',
|
||||
withdrawing: 'Submitting…',
|
||||
registered:
|
||||
'Your withdrawal request has been registered. It will be processed as soon as possible.',
|
||||
},
|
||||
mainCard: {
|
||||
title: 'USDT wallet',
|
||||
@ -554,6 +553,18 @@ export const en = {
|
||||
pending: 'Pending',
|
||||
failed: 'Failed',
|
||||
processing: 'Processing',
|
||||
rejected: 'Rejected',
|
||||
cancelled: 'Cancelled',
|
||||
failed_refunded: 'Failed',
|
||||
},
|
||||
refunded: 'Amount credited back',
|
||||
cancelWithdrawal: {
|
||||
action: 'Cancel',
|
||||
title: 'Cancel this withdrawal?',
|
||||
body: 'The request has not been processed yet. If you cancel it, the full reserved amount (amount + network fee) is credited back to your balance.',
|
||||
confirm: 'Cancel withdrawal',
|
||||
success: 'Withdrawal cancelled. The amount has been credited back to your balance.',
|
||||
failed: 'This withdrawal can no longer be cancelled.',
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -672,6 +683,32 @@ export const en = {
|
||||
markRead: 'Mark read',
|
||||
loadError: 'Failed to load security notifications.',
|
||||
empty: 'No security notifications yet.',
|
||||
events: {
|
||||
withdrawal_submitted: {
|
||||
title: 'Withdrawal request registered',
|
||||
body: 'Your withdrawal request has been registered. It will be processed as soon as possible.',
|
||||
},
|
||||
withdrawal_processing: {
|
||||
title: 'Withdrawal in progress',
|
||||
body: 'Your withdrawal request is currently being processed.',
|
||||
},
|
||||
withdrawal_completed: {
|
||||
title: 'Withdrawal completed',
|
||||
body: 'Your withdrawal was completed successfully.',
|
||||
},
|
||||
withdrawal_failed: {
|
||||
title: 'Withdrawal under review',
|
||||
body: 'Processing of your withdrawal ran into a technical problem. Your request remains registered and will be reviewed.',
|
||||
},
|
||||
withdrawal_rejected: {
|
||||
title: 'Withdrawal declined',
|
||||
body: 'Your withdrawal request was declined. The corresponding amount has been credited back to your account.',
|
||||
},
|
||||
withdrawal_cancelled: {
|
||||
title: 'Withdrawal cancelled',
|
||||
body: 'Your withdrawal request was cancelled. The corresponding amount has been credited back to your account.',
|
||||
},
|
||||
},
|
||||
},
|
||||
enabled: 'Enabled',
|
||||
disabled: 'Disabled',
|
||||
@ -1393,6 +1430,101 @@ export const en = {
|
||||
empty: 'No permissions match these filters.',
|
||||
},
|
||||
},
|
||||
withdrawals: {
|
||||
title: 'Withdrawals',
|
||||
subtitle:
|
||||
'Requests not yet paid out: process them once the hot wallet has enough USDT and gas, retry technical failures, or reject with a full refund.',
|
||||
refresh: 'Refresh withdrawals',
|
||||
readOnly: 'Read-only access: processing, retry and rejection require the withdrawals management permission.',
|
||||
pendingBreakdown: 'Pending by reason:',
|
||||
autoRetryOn:
|
||||
'Automatic retry is on: requests waiting for hot wallet USDT / gas are processed automatically every {{minutes}} min once the hot wallet can pay them.',
|
||||
autoRetryOff:
|
||||
'Automatic retry is off: process requests waiting for liquidity manually (can be enabled in Settings → Withdrawals).',
|
||||
network: 'Network',
|
||||
allNetworks: 'All networks',
|
||||
from: 'From',
|
||||
to: 'To',
|
||||
minAmount: 'Min USDT',
|
||||
maxAmount: 'Max USDT',
|
||||
search: 'Search (email, request ID, address, tx hash)',
|
||||
loadError: 'Failed to load withdrawals.',
|
||||
empty: 'No withdrawal requests match these filters.',
|
||||
created: 'Requested',
|
||||
user: 'User',
|
||||
amount: 'Amount',
|
||||
fee: 'Network fee',
|
||||
totalReserved: 'Total reserved',
|
||||
feeAndTotal: 'fee {{fee}} · total {{total}}',
|
||||
destination: 'Destination',
|
||||
attempts: 'Attempts',
|
||||
actions: 'Actions',
|
||||
details: 'Details',
|
||||
process: 'Process',
|
||||
retry: 'Retry',
|
||||
requeue: 'Back to pending',
|
||||
reject: 'Reject',
|
||||
legacy: 'Legacy record',
|
||||
confirmations: '{{n}} / {{required}} confirmations',
|
||||
confirmationsLabel: 'Confirmations',
|
||||
txHash: 'Transaction hash',
|
||||
lastError: 'Last error',
|
||||
rejectionReason: 'Rejection reason',
|
||||
abandonedHashes: 'Previous attempts (never executed)',
|
||||
awaitingApprovalHint:
|
||||
'This is a large withdrawal: it is processed automatically once the approval quorum is reached on the Approvals page. You can still reject it here.',
|
||||
liquidityTitle: 'Hot wallet check ({{network}})',
|
||||
liquidityOk: 'The hot wallet can pay this withdrawal now (USDT and gas available).',
|
||||
gas: 'Gas',
|
||||
inFlight: 'Already broadcast, awaiting confirmation',
|
||||
history: 'Status history',
|
||||
detailTitle: 'Withdrawal request',
|
||||
processStarted: 'Payout broadcast. It will be marked completed after on-chain confirmation.',
|
||||
stillPending: 'Still pending: {{reason}}. Nothing was sent; try again after replenishing.',
|
||||
processFailed: 'Processing failed: {{error}}',
|
||||
requeued: 'Request put back in the pending queue.',
|
||||
rejected: 'Request rejected and the reserved amount credited back to the user.',
|
||||
actionFailed: 'Action failed.',
|
||||
rejectTitle: 'Reject withdrawal',
|
||||
rejectHint:
|
||||
'The full reserved amount (amount + network fee) is credited back to the user, who is notified. The reason is kept for audit and is not shown to the user.',
|
||||
status: {
|
||||
open: 'To handle (pending, processing, failed)',
|
||||
all: 'All',
|
||||
pending: 'Pending',
|
||||
processing: 'Processing',
|
||||
completed: 'Completed',
|
||||
failed: 'Failed',
|
||||
rejected: 'Rejected',
|
||||
cancelled: 'Cancelled by user',
|
||||
failed_refunded: 'Failed (refunded, legacy)',
|
||||
pending_approval: 'Pending approval (legacy)',
|
||||
broadcasting: 'Broadcasting (legacy)',
|
||||
confirming: 'Confirming (legacy)',
|
||||
ledger_finalize_failed: 'Ledger finalize failed (legacy)',
|
||||
},
|
||||
reasons: {
|
||||
queued: 'Queued',
|
||||
awaiting_approval: 'Awaiting approval quorum',
|
||||
awaiting_liquidity: 'Hot wallet USDT insufficient',
|
||||
awaiting_gas: 'Hot wallet gas insufficient',
|
||||
hot_wallet_unavailable: 'No active hot wallet',
|
||||
processing_interrupted: 'Processing interrupted',
|
||||
requeued_by_admin: 'Requeued by admin',
|
||||
account_on_hold: 'Account on security hold',
|
||||
cancelled_by_user: 'Cancelled by user',
|
||||
},
|
||||
shortfall: {
|
||||
usdt: 'Not enough USDT on the hot wallet (including payouts already in flight).',
|
||||
gas: 'Not enough gas (TRX / BNB) on the hot wallet.',
|
||||
no_hot_wallet: 'No active hot wallet is configured for this network.',
|
||||
},
|
||||
actor: {
|
||||
user: 'User',
|
||||
admin: 'Admin',
|
||||
system: 'System',
|
||||
},
|
||||
},
|
||||
approvals: {
|
||||
title: 'Approvals',
|
||||
subtitle: 'Review and approve sensitive fund operations (N-of-M when configured)',
|
||||
@ -2213,6 +2345,10 @@ export const en = {
|
||||
networkFee: 'Withdrawal network fee (USDT)',
|
||||
networkFeeHelper:
|
||||
"Deducted from the user's USDT balance per withdrawal (scaled per network decimals; covers on-chain gas).",
|
||||
autoRetry: 'Automatically retry withdrawals waiting for hot wallet USDT / gas',
|
||||
autoRetryInterval: 'Automatic retry interval (minutes)',
|
||||
autoRetryHelper:
|
||||
'When enabled, pending requests blocked by hot wallet liquidity, gas or a missing hot wallet are processed automatically once the hot wallet can pay them (oldest first). Off: an admin processes them from the Withdrawals page.',
|
||||
},
|
||||
transfers: {
|
||||
title: 'User transfers',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user