322 lines
9.9 KiB
TypeScript
322 lines
9.9 KiB
TypeScript
/**
|
|
* User-facing email + in-app notifications for wallet actions (withdrawals, transfers).
|
|
* Failures are logged but never block the primary action.
|
|
*/
|
|
|
|
import { decrypt } from '../utils/crypto';
|
|
import { formatUsdtRawHuman } from '../utils/withdrawalFee';
|
|
import * as userRepository from '../repositories/userRepository';
|
|
import * as userSecurityNotificationRepository from '../repositories/userSecurityNotificationRepository';
|
|
import * as emailService from './emailService';
|
|
|
|
async function resolveUserEmail(userId: string): Promise<string | null> {
|
|
const profile = await userRepository.getProfileForUser(userId);
|
|
if (!profile?.email_encrypted) return null;
|
|
try {
|
|
return decrypt(profile.email_encrypted);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function logNotifyError(context: string, e: unknown): void {
|
|
const detail = e instanceof Error ? e.message : String(e);
|
|
console.error(`[wallet-notify] ${context}:`, detail);
|
|
}
|
|
|
|
async function recordInAppNotification(data: {
|
|
userId: string;
|
|
eventType: string;
|
|
title: string;
|
|
body?: string;
|
|
metadata?: Record<string, unknown>;
|
|
}): Promise<void> {
|
|
try {
|
|
await userSecurityNotificationRepository.createUserSecurityNotification(data);
|
|
} catch (e) {
|
|
logNotifyError('in-app notification', e);
|
|
}
|
|
}
|
|
|
|
function maskAddress(address: string): string {
|
|
const a = address.trim();
|
|
if (a.length <= 12) return a;
|
|
return `${a.slice(0, 6)}…${a.slice(-4)}`;
|
|
}
|
|
|
|
function maskEmail(email: string): string {
|
|
const e = email.trim();
|
|
const at = e.indexOf('@');
|
|
if (at <= 1) return '***';
|
|
const user = e.slice(0, at);
|
|
const domain = e.slice(at + 1);
|
|
const visible = user.slice(0, Math.min(2, user.length));
|
|
return `${visible}***@${domain}`;
|
|
}
|
|
|
|
function amountLabel(amountRaw: bigint | string, feeRaw?: bigint | string): {
|
|
amount: string;
|
|
fee?: string;
|
|
total?: string;
|
|
} {
|
|
const amount = formatUsdtRawHuman(BigInt(amountRaw));
|
|
if (feeRaw === undefined) return { amount };
|
|
const fee = formatUsdtRawHuman(BigInt(feeRaw));
|
|
const total = formatUsdtRawHuman(BigInt(amountRaw) + BigInt(feeRaw));
|
|
return { amount, fee, total };
|
|
}
|
|
|
|
/** 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: {
|
|
amountRaw: bigint | string;
|
|
feeRaw: bigint | string;
|
|
toAddress: string;
|
|
network?: string;
|
|
transactionId: string;
|
|
pendingApproval?: boolean;
|
|
}
|
|
): Promise<void> {
|
|
const { amount, fee, total } = amountLabel(data.amountRaw, data.feeRaw);
|
|
const dest = maskAddress(data.toAddress);
|
|
const statusNote = WITHDRAWAL_MESSAGES.pending;
|
|
void recordInAppNotification({
|
|
userId,
|
|
eventType: 'withdrawal_submitted',
|
|
title: 'Withdrawal request registered',
|
|
body: `${WITHDRAWAL_MESSAGES.pending} (${amount} USDT to ${dest})`,
|
|
metadata: {
|
|
transactionId: data.transactionId,
|
|
amount,
|
|
fee,
|
|
total,
|
|
network: data.network,
|
|
pendingApproval: !!data.pendingApproval,
|
|
},
|
|
});
|
|
const email = await resolveUserEmail(userId);
|
|
if (!email) return;
|
|
try {
|
|
await emailService.sendWithdrawalSubmittedEmail(email, {
|
|
amountUsdt: amount,
|
|
feeUsdt: fee!,
|
|
totalUsdt: total!,
|
|
toAddressMasked: dest,
|
|
network: data.network,
|
|
pendingApproval: !!data.pendingApproval,
|
|
statusNote,
|
|
});
|
|
} catch (e) {
|
|
logNotifyError('withdrawal submitted email', e);
|
|
}
|
|
}
|
|
|
|
/** Withdrawal completed on-chain. */
|
|
export async function notifyWithdrawalCompleted(
|
|
userId: string,
|
|
data: {
|
|
amountRaw: bigint | string;
|
|
feeRaw: bigint | string;
|
|
toAddress: string;
|
|
network?: string;
|
|
transactionId: string;
|
|
blockchainTxId?: string | null;
|
|
}
|
|
): Promise<void> {
|
|
const { amount, fee, total } = amountLabel(data.amountRaw, data.feeRaw);
|
|
const dest = maskAddress(data.toAddress);
|
|
void recordInAppNotification({
|
|
userId,
|
|
eventType: 'withdrawal_completed',
|
|
title: 'Withdrawal completed',
|
|
body: `${WITHDRAWAL_MESSAGES.completed} (${amount} USDT to ${dest})`,
|
|
metadata: {
|
|
transactionId: data.transactionId,
|
|
amount,
|
|
fee,
|
|
total,
|
|
network: data.network,
|
|
blockchainTxId: data.blockchainTxId ?? null,
|
|
},
|
|
});
|
|
const email = await resolveUserEmail(userId);
|
|
if (!email) return;
|
|
try {
|
|
await emailService.sendWithdrawalCompletedEmail(email, {
|
|
amountUsdt: amount,
|
|
feeUsdt: fee!,
|
|
totalUsdt: total!,
|
|
toAddressMasked: dest,
|
|
network: data.network,
|
|
blockchainTxId: data.blockchainTxId ?? null,
|
|
});
|
|
} catch (e) {
|
|
logNotifyError('withdrawal completed email', e);
|
|
}
|
|
}
|
|
|
|
/** 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: {
|
|
amountRaw: bigint | string;
|
|
feeRaw?: bigint | string;
|
|
toAddress?: string;
|
|
transactionId: string;
|
|
}
|
|
): Promise<void> {
|
|
const { amount } = amountLabel(data.amountRaw, data.feeRaw);
|
|
const dest = data.toAddress ? maskAddress(data.toAddress) : null;
|
|
void recordInAppNotification({
|
|
userId,
|
|
eventType: 'withdrawal_failed',
|
|
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;
|
|
try {
|
|
await emailService.sendWithdrawalFailedEmail(email, {
|
|
amountUsdt: amount,
|
|
toAddressMasked: dest,
|
|
});
|
|
} 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,
|
|
data: {
|
|
amountRaw: bigint | string;
|
|
toEmail: string;
|
|
transactionId: string;
|
|
}
|
|
): Promise<void> {
|
|
const { amount } = amountLabel(data.amountRaw);
|
|
const toMasked = maskEmail(data.toEmail);
|
|
void recordInAppNotification({
|
|
userId,
|
|
eventType: 'transfer_sent',
|
|
title: 'Transfer sent',
|
|
body: `You sent ${amount} USDT to ${toMasked}.`,
|
|
metadata: { transactionId: data.transactionId, amount, toEmailMasked: toMasked },
|
|
});
|
|
const email = await resolveUserEmail(userId);
|
|
if (!email) return;
|
|
try {
|
|
await emailService.sendTransferSentEmail(email, {
|
|
amountUsdt: amount,
|
|
counterpartyEmailMasked: toMasked,
|
|
});
|
|
} catch (e) {
|
|
logNotifyError('transfer sent email', e);
|
|
}
|
|
}
|
|
|
|
/** Peer transfer received (recipient). */
|
|
export async function notifyTransferReceived(
|
|
userId: string,
|
|
data: {
|
|
amountRaw: bigint | string;
|
|
fromUserId: string;
|
|
transactionId: string;
|
|
}
|
|
): Promise<void> {
|
|
const { amount } = amountLabel(data.amountRaw);
|
|
let fromMasked = 'another Tloto user';
|
|
const fromEmail = await resolveUserEmail(data.fromUserId);
|
|
if (fromEmail) fromMasked = maskEmail(fromEmail);
|
|
|
|
void recordInAppNotification({
|
|
userId,
|
|
eventType: 'transfer_received',
|
|
title: 'Transfer received',
|
|
body: `You received ${amount} USDT from ${fromMasked}.`,
|
|
metadata: {
|
|
transactionId: data.transactionId,
|
|
amount,
|
|
fromEmailMasked: fromMasked,
|
|
},
|
|
});
|
|
const email = await resolveUserEmail(userId);
|
|
if (!email) return;
|
|
try {
|
|
await emailService.sendTransferReceivedEmail(email, {
|
|
amountUsdt: amount,
|
|
counterpartyEmailMasked: fromMasked,
|
|
});
|
|
} catch (e) {
|
|
logNotifyError('transfer received email', e);
|
|
}
|
|
}
|