/** * 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 transactionRepository from '../repositories/transactionRepository'; import * as userRepository from '../repositories/userRepository'; import * as walletRepository from '../repositories/walletRepository'; import * as auditLogRepository from '../repositories/auditLogRepository'; import { queueUserAdminStatsRefresh } from './userAdminStatsService'; /** * Transfers balance from one user to another identified by email. * @param userId Sender user UUID * @param toEmail Recipient email (normalized and hashed for lookup) * @param walletTypeCode Asset code for the transfer * @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, or insufficient balance */ export async function requestTransfer( userId: string, toEmail: string, walletTypeCode: string, amountRaw: bigint, totpCode?: string ): Promise<{ transactionId: string; status: string }> { const walletType = await walletRepository.getWalletTypeByCode(walletTypeCode); if (!walletType) throw new Error('Unknown wallet type'); if (amountRaw <= 0n) throw new Error('Invalid amount'); await authService.verifyTotp(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 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'); const refId = randomUUID(); await ledgerRepository.transferBetweenAccounts( senderAccount.id, recipientAccount.id, amountRaw, 'transfer', refId ); 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' }; }