games_app/backend/src/services/transferService.ts

123 lines
4.7 KiB
TypeScript

/**
* Internal peer-to-peer transfer service.
* Moves ledger balance between users by email; requires 2FA when enabled.
*/
import { randomUUID } from 'crypto';
import { hashForIndex } from '../utils/crypto';
import * as authService from './authService';
import * as ledgerRepository from '../repositories/ledgerRepository';
import * as settingsRepository from '../repositories/settingsRepository';
import * as transactionRepository from '../repositories/transactionRepository';
import * as userRepository from '../repositories/userRepository';
import * as walletRepository from '../repositories/walletRepository';
import * as auditLogRepository from '../repositories/auditLogRepository';
import { USDT_TRC20_CODE } from './walletCapabilities';
import {
formatUsdtRawHuman,
getTransferMinRemainingRaw,
} from '../utils/withdrawalFee';
import { queueUserAdminStatsRefresh } from './userAdminStatsService';
/**
* Transfers balance from one user to another identified by email.
* Peer transfers always debit/credit the unified main ledger (USDT_TRC20).
* Deposit/withdraw rails such as USDT_BEP20 are not valid transfer assets.
* @param userId Sender user UUID
* @param toEmail Recipient email (normalized and hashed for lookup)
* @param walletTypeCode Asset code for the transfer (must be USDT_TRC20)
* @param amountRaw Amount in smallest ledger unit
* @param totpCode TOTP code when sender has 2FA enabled
* @returns Sender transaction ID and status (always completed on success)
* @throws {Error} On invalid amount, failed 2FA, recipient not found, self-transfer, insufficient balance, or min remaining
*/
export async function requestTransfer(
userId: string,
toEmail: string,
walletTypeCode: string,
amountRaw: bigint,
totpCode?: string
): Promise<{ transactionId: string; status: string }> {
if (walletTypeCode !== USDT_TRC20_CODE) {
const err = new Error(
'Peer transfers use the main USDT balance only (not deposit/withdraw networks)'
) as Error & { code?: string };
err.code = 'TRANSFER_LEDGER_ONLY';
throw err;
}
const walletType = await walletRepository.getWalletTypeByCode(USDT_TRC20_CODE);
if (!walletType) throw new Error('Unknown wallet type');
if (amountRaw <= 0n) throw new Error('Invalid amount');
await authService.assertWithdrawalSecondFactor(userId, totpCode);
const toEmailHash = hashForIndex(toEmail.trim().toLowerCase());
const recipient = await userRepository.findByEmailHash(toEmailHash);
if (!recipient) throw new Error('Recipient not found');
if (recipient.id === userId) throw new Error('Cannot transfer to yourself');
const settings = await settingsRepository.getSettings();
const minRemaining = getTransferMinRemainingRaw(settings, walletType.decimals);
const senderAccount = await ledgerRepository.getOrCreateAccount(userId, walletType.id);
const recipientAccount = await ledgerRepository.getOrCreateAccount(recipient.id, walletType.id);
const available = BigInt(senderAccount.available_balance);
if (available < amountRaw) throw new Error('Insufficient balance');
if (minRemaining > 0n && available - amountRaw < minRemaining) {
const human = formatUsdtRawHuman(minRemaining, walletType.decimals);
const err = new Error(
`Transfer would leave balance below the minimum required remaining balance (${human} USDT)`
) as Error & { code?: string };
err.code = 'TRANSFER_MIN_REMAINING';
throw err;
}
const refId = randomUUID();
await ledgerRepository.transferBetweenAccounts(
senderAccount.id,
recipientAccount.id,
amountRaw,
'transfer',
refId,
{ minRemaining }
);
const senderTx = await transactionRepository.create({
userId,
walletTypeId: walletType.id,
type: 'transfer',
amount: amountRaw,
status: 'completed',
metadata: { direction: 'out', to_user_id: recipient.id, reference: refId },
});
const receiverTx = await transactionRepository.create({
userId: recipient.id,
walletTypeId: walletType.id,
type: 'transfer',
amount: amountRaw,
status: 'completed',
metadata: { direction: 'in', from_user_id: userId, reference: refId },
});
await auditLogRepository.create({
userId,
action: 'transfer_sent',
resourceType: 'transaction',
resourceId: senderTx.id,
metadata: { amount: amountRaw.toString(), to_user_id: recipient.id },
});
await auditLogRepository.create({
userId: recipient.id,
action: 'transfer_received',
resourceType: 'transaction',
resourceId: receiverTx.id,
metadata: { amount: amountRaw.toString(), from_user_id: userId },
});
queueUserAdminStatsRefresh(userId);
queueUserAdminStatsRefresh(recipient.id);
return { transactionId: senderTx.id, status: 'completed' };
}