forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment-processor.service.ts
More file actions
719 lines (634 loc) · 22.7 KB
/
Copy pathpayment-processor.service.ts
File metadata and controls
719 lines (634 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
import {
Injectable,
Logger,
BadRequestException,
NotFoundException,
ConflictException,
Optional,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository, DataSource } from "typeorm";
import { StellarService } from "../stellar/stellar.service";
import { PaymentGateway } from "../websocket/payment.gateway";
import {
Payment,
PaymentProcessingStatus,
PaymentSettlementStatus,
} from "../entities/payment.entity";
import { Participant } from "../entities/participant.entity";
import { Split } from "../entities/split.entity";
import { EmailService } from "../email/email.service";
import { MultiCurrencyService } from "../multi-currency/multi-currency.service";
import { EventsGateway } from "../gateway/events.gateway";
import { AnalyticsService } from "../analytics/analytics.service";
import { FraudDetectionService } from '../fraud-detection/fraud-detection.service';
import type { AnalyzePaymentRequestDto } from "../fraud-detection/dto/analyze-split.dto";
import * as crypto from "crypto";
import { ReputationService } from "../reputation/reputation.service";
import { ReputationEventType } from "../reputation/enums/reputation-event-type.enum";
/**
* Result of processing a payment submission
*/
export interface PaymentSubmissionResult {
success: boolean;
message: string;
paymentId?: string;
isDuplicate?: boolean;
idempotencyKey?: string;
}
/**
* Options for processing a payment
*/
export interface ProcessPaymentOptions {
splitId: string;
participantId: string;
txHash: string;
idempotencyKey?: string;
externalReference?: string;
isRetry?: boolean;
maxRetries?: number;
}
/**
* Configuration for payment processing
*/
export interface PaymentProcessorConfig {
maxReconciliationAttempts: number;
reconciliationTimeoutMinutes: number;
stalePaymentThresholdMinutes: number;
enableIdempotencyChecks: boolean;
}
const DEFAULT_CONFIG: PaymentProcessorConfig = {
maxReconciliationAttempts: 5,
reconciliationTimeoutMinutes: 30,
stalePaymentThresholdMinutes: 60,
enableIdempotencyChecks: true,
};
@Injectable()
export class PaymentProcessorService {
private readonly logger = new Logger(PaymentProcessorService.name);
private readonly config: PaymentProcessorConfig;
constructor(
private readonly stellarService: StellarService,
private readonly paymentGateway: PaymentGateway,
private readonly eventsGateway: EventsGateway,
@InjectRepository(Payment) private paymentRepository: Repository<Payment>,
@InjectRepository(Participant)
private participantRepository: Repository<Participant>,
@InjectRepository(Split) private splitRepository: Repository<Split>,
private readonly emailService: EmailService,
private readonly multiCurrencyService: MultiCurrencyService,
private readonly dataSource: DataSource,
@Optional() private readonly analyticsService?: AnalyticsService,
@Optional() private readonly fraudDetectionService?: FraudDetectionService,
@Optional() private readonly reputationService?: ReputationService,
@Optional() private readonly customConfig?: Partial<PaymentProcessorConfig>,
) {
this.config = { ...DEFAULT_CONFIG, ...customConfig };
}
/**
* Generate an idempotency key for a payment
*/
generateIdempotencyKey(
splitId: string,
participantId: string,
txHash: string,
): string {
const payload = `${splitId}:${participantId}:${txHash}`;
return crypto.createHash("sha256").update(payload).digest("hex");
}
private resolveSplitDeadline(split: Partial<Split>, processedAt: Date): Date {
const directDeadline = split.dueDate ?? split.expiryDate;
if (directDeadline instanceof Date) {
return directDeadline;
}
if (typeof directDeadline === "string" || typeof directDeadline === "number") {
const parsedDeadline = new Date(directDeadline);
if (!Number.isNaN(parsedDeadline.getTime())) {
return parsedDeadline;
}
}
const createdAt = split.createdAt;
if (createdAt instanceof Date) {
return new Date(createdAt.getTime() + 30 * 24 * 60 * 60 * 1000);
}
if (typeof createdAt === "string" || typeof createdAt === "number") {
const parsedCreatedAt = new Date(createdAt);
if (!Number.isNaN(parsedCreatedAt.getTime())) {
return new Date(parsedCreatedAt.getTime() + 30 * 24 * 60 * 60 * 1000);
}
}
return processedAt;
}
/**
* Process a payment submission with idempotency and transaction support
* @param options Payment processing options
*/
async processPaymentSubmission(
options: ProcessPaymentOptions,
): Promise<PaymentSubmissionResult> {
const { splitId, participantId, txHash, idempotencyKey, externalReference, isRetry } =
options;
this.logger.log(
`Processing payment submission for split ${splitId}, participant ${participantId}, tx ${txHash}`,
);
// Generate idempotency key if not provided
const key = idempotencyKey || this.generateIdempotencyKey(splitId, participantId, txHash);
// Start a database transaction for atomic operations
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
// Check for existing payment with idempotency key
const existingByKey = await queryRunner.manager.findOne(Payment, {
where: { idempotencyKey: key },
});
if (existingByKey) {
this.logger.warn(`Duplicate payment detected via idempotency key: ${key}`);
await queryRunner.rollbackTransaction();
return {
success: true,
message: "Payment already processed",
paymentId: existingByKey.id,
isDuplicate: true,
idempotencyKey: key,
};
}
// Check for duplicate txHash (legacy check)
const existingByTxHash = await queryRunner.manager.findOne(Payment, {
where: { txHash },
});
if (existingByTxHash) {
this.logger.warn(`Duplicate payment detected via txHash: ${txHash}`);
await queryRunner.rollbackTransaction();
return {
success: true,
message: "Payment with this transaction hash already exists",
paymentId: existingByTxHash.id,
isDuplicate: true,
idempotencyKey: key,
};
}
// Verify the transaction on Stellar network
const verificationResult = await this.stellarService.verifyTransaction(txHash);
if (!verificationResult || !verificationResult.valid) {
await queryRunner.rollbackTransaction();
throw new BadRequestException(
"Invalid or unsuccessful Stellar transaction",
);
}
// Get the participant record with lock
const participant = await queryRunner.manager.findOne(Participant, {
where: { id: participantId, splitId },
lock: { mode: "pessimistic_write" },
});
if (!participant) {
await queryRunner.rollbackTransaction();
throw new NotFoundException(
`Participant ${participantId} not found for split ${splitId}`,
);
}
// Get split to check preferred currency
const split = await queryRunner.manager.findOne(Split, {
where: { id: splitId },
lock: { mode: "pessimistic_write" },
});
if (!split) {
await queryRunner.rollbackTransaction();
throw new NotFoundException(`Split ${splitId} not found`);
}
// Check if split is frozen
if (split.isFrozen) {
await queryRunner.rollbackTransaction();
throw new ConflictException(
"Split is frozen due to an active dispute",
);
}
// Determine the paid asset (from path payment source or regular payment)
const paidAsset =
verificationResult.isPathPayment && verificationResult.sourceAsset
? verificationResult.sourceAsset
: verificationResult.asset;
const paidAmount =
verificationResult.isPathPayment && verificationResult.sourceAmount
? verificationResult.sourceAmount
: verificationResult.amount;
// Process multi-currency payment if needed
let receivedAmount = verificationResult.amount;
let receivedAsset = verificationResult.asset;
let multiCurrencyResult = null;
// Check if conversion is needed (paid asset differs from received asset)
if (verificationResult.isPathPayment || paidAsset !== receivedAsset) {
try {
multiCurrencyResult =
await this.multiCurrencyService.processMultiCurrencyPayment({
splitId,
participantId,
txHash,
paidAsset,
paidAmount,
receivedAsset: (split as any).preferredCurrency || receivedAsset,
slippageTolerance: 0.01,
});
receivedAmount = multiCurrencyResult.receivedAmount;
receivedAsset = multiCurrencyResult.receivedAsset;
} catch (error: any) {
this.logger.warn(
`Multi-currency processing failed, using direct payment: ${error.message}`,
);
}
}
// Perform fraud detection check
if (this.fraudDetectionService) {
try {
const fraudRequest: AnalyzePaymentRequestDto = {
payment_data: {
payment_id: key, // use idempotency key as temp id
split_id: splitId,
participant_id: participantId,
amount: receivedAmount,
asset: receivedAsset,
tx_hash: txHash,
sender_address: verificationResult.sender || '',
receiver_address: verificationResult.receiver || '',
timestamp: new Date(),
},
};
const fraudResult = await this.fraudDetectionService.checkPayment(fraudRequest);
if (!fraudResult.allowed) {
this.logger.warn(`Payment blocked due to fraud risk: ${fraudResult.riskLevel} for split ${splitId}`);
await queryRunner.rollbackTransaction();
throw new BadRequestException('Payment blocked due to fraud risk');
}
} catch (error) {
if (error instanceof BadRequestException) {
throw error;
}
// Log but don't fail the payment
this.logger.error(`Fraud detection failed for payment in split ${splitId}:`, error);
}
}
// Determine payment status based on amount
let paymentStatus: PaymentProcessingStatus;
let settlementStatus: PaymentSettlementStatus;
if (receivedAmount < participant.amountOwed) {
paymentStatus = PaymentProcessingStatus.PARTIAL;
settlementStatus = PaymentSettlementStatus.CONFIRMED;
} else if (receivedAmount > participant.amountOwed) {
paymentStatus = PaymentProcessingStatus.CONFIRMED;
settlementStatus = PaymentSettlementStatus.CONFIRMED;
} else {
paymentStatus = PaymentProcessingStatus.CONFIRMED;
settlementStatus = PaymentSettlementStatus.CONFIRMED;
}
// One timestamp drives both persistence and reputation timing.
const processedAt = new Date();
// Create payment record with idempotency key
const payment = queryRunner.manager.create(Payment, {
idempotencyKey: key,
splitId,
participantId,
txHash,
amount: receivedAmount,
asset: receivedAsset,
status: paymentStatus,
settlementStatus,
lastSettlementCheck: new Date(),
reconciliationAttempts: 0,
maxReconciliationAttempts: this.config.maxReconciliationAttempts,
notificationsSent: false,
processedAt,
externalReference,
});
const savedPayment = await queryRunner.manager.save(Payment, payment);
// Update participant's paid amount and status
const wasFullyPaidBefore = Number(participant.amountPaid) >= Number(participant.amountOwed) || participant.status === "paid";
const newAmountPaid = participant.amountPaid + receivedAmount;
let participantStatus: "pending" | "paid" | "partial" = "partial";
if (newAmountPaid >= participant.amountOwed) {
participantStatus = "paid";
} else if (newAmountPaid === 0) {
participantStatus = "pending";
}
await queryRunner.manager.update(Participant, { id: participantId }, {
amountPaid: newAmountPaid,
status: participantStatus,
});
// Update split's total paid amount
await this.updateSplitAmountPaidTransactional(queryRunner, splitId);
// Record reputation only when transitioning to fully paid (to avoid double counting).
if (participantStatus === "paid" && !wasFullyPaidBefore) {
const deadline = this.resolveSplitDeadline(split, processedAt);
const eventType =
processedAt.getTime() <= deadline.getTime()
? ReputationEventType.PAID_ON_TIME
: ReputationEventType.PAID_LATE;
if (this.reputationService) {
await this.reputationService.recordEvent(
participant.userId,
splitId,
eventType,
queryRunner.manager,
);
}
}
// Commit the transaction
await queryRunner.commitTransaction();
// Send notifications (outside transaction)
await this.sendPaymentNotifications(
participantId,
splitId,
paymentStatus,
{
txHash,
amount: receivedAmount,
asset: receivedAsset,
},
);
// Invalidate analytics cache
await this.invalidateAnalyticsCache(participant.userId);
const statusMessage =
paymentStatus === PaymentProcessingStatus.PARTIAL
? `Partial payment received. Amount: ${paidAmount} ${paidAsset}${multiCurrencyResult?.requiresConversion ? ` (converted to ${receivedAmount} ${receivedAsset})` : ""}. Expected: ${participant.amountOwed}`
: paymentStatus === PaymentProcessingStatus.CONFIRMED && receivedAmount > participant.amountOwed
? `Payment received with overpayment. Amount: ${paidAmount} ${paidAsset}${multiCurrencyResult?.requiresConversion ? ` (converted to ${receivedAmount} ${receivedAsset})` : ""}. Expected: ${participant.amountOwed}`
: `Payment confirmed. Amount: ${paidAmount} ${paidAsset}${multiCurrencyResult?.requiresConversion ? ` (converted to ${receivedAmount} ${receivedAsset})` : ""}`;
return {
success: true,
message: statusMessage,
paymentId: savedPayment.id,
idempotencyKey: key,
};
} catch (error: any) {
await queryRunner.rollbackTransaction();
this.logger.error(
`Error processing payment submission: ${error.message}`,
error.stack,
);
throw error;
} finally {
await queryRunner.release();
}
}
/**
* Handle webhook replay of payment events
* This ensures idempotent processing of webhook events
*/
async handleWebhookReplay(
txHash: string,
externalReference: string,
): Promise<PaymentSubmissionResult> {
this.logger.log(`Handling webhook replay for tx: ${txHash}, ref: ${externalReference}`);
// Check if we already processed this
const existingPayment = await this.paymentRepository.findOne({
where: { txHash },
});
if (existingPayment) {
// If already processed and notifications sent, return success
if (existingPayment.notificationsSent) {
return {
success: true,
message: "Payment already processed and notifications sent",
paymentId: existingPayment.id,
isDuplicate: true,
};
}
// If not notifications sent, resend them
if (!existingPayment.notificationsSent) {
await this.resendNotifications(existingPayment);
return {
success: true,
message: "Notifications resent for existing payment",
paymentId: existingPayment.id,
};
}
}
// For webhook replays without existing payment, we need to find the split/participant
// This requires additional context - return error with guidance
throw new BadRequestException(
"Cannot process webhook replay without existing payment record. Provide idempotency key for original submission.",
);
}
/**
* Retry a failed payment
*/
async retryPayment(
paymentId: string,
newTxHash: string,
): Promise<PaymentSubmissionResult> {
const payment = await this.paymentRepository.findOne({
where: { id: paymentId },
relations: ["participant", "participant.split"],
});
if (!payment) {
throw new NotFoundException(`Payment ${paymentId} not found`);
}
if (payment.status !== PaymentProcessingStatus.FAILED) {
throw new ConflictException(
"Only failed payments can be retried",
);
}
// Generate new idempotency key for the retry
const newIdempotencyKey = this.generateIdempotencyKey(
payment.splitId,
payment.participantId,
newTxHash,
);
return this.processPaymentSubmission({
splitId: payment.splitId,
participantId: payment.participantId,
txHash: newTxHash,
idempotencyKey: newIdempotencyKey,
isRetry: true,
});
}
/**
* Update split amount paid within a transaction
*/
private async updateSplitAmountPaidTransactional(
queryRunner: any,
splitId: string,
): Promise<void> {
// Calculate total amount paid by summing all participants' paid amounts
const participants = await queryRunner.manager.find(Participant, {
where: { splitId },
});
const totalPaid = participants.reduce(
(sum: number, participant: Participant) =>
sum + Number(participant.amountPaid || 0),
0,
);
// Get the split to update
const split = await queryRunner.manager.findOne(Split, {
where: { id: splitId },
});
if (!split) {
throw new NotFoundException(`Split ${splitId} not found`);
}
// Determine split status based on total paid vs total amount
let status: "active" | "completed" | "partial" = "active";
if (Number(totalPaid) >= Number(split.totalAmount)) {
status = "completed";
} else if (Number(totalPaid) > 0) {
status = "partial";
}
await queryRunner.manager.update(
Split,
{ id: splitId },
{
amountPaid: totalPaid,
status,
},
);
// Send split update notification
this.eventsGateway.emitSplitUpdated(splitId, {
splitId,
status,
amountPaid: totalPaid,
timestamp: new Date().toISOString(),
});
if (status === "completed") {
this.sendSplitCompletedNotification(splitId);
}
}
/**
* Send payment notifications
*/
private async sendPaymentNotifications(
participantId: string,
splitId: string,
status: PaymentProcessingStatus,
data: { txHash: string; amount: number; asset: string },
): Promise<void> {
const notificationType =
status === PaymentProcessingStatus.PARTIAL
? "partial_payment_received"
: "payment_confirmed";
// Emit to WebSocket gateway
const roomId = `participant_${participantId}`;
this.paymentGateway.emitPaymentNotification(roomId, {
type: notificationType,
data,
timestamp: new Date(),
});
this.eventsGateway.emitPaymentReceived(splitId, {
participantId,
type: notificationType,
...data,
timestamp: new Date().toISOString(),
});
this.logger.log(
`Sending payment notification for participant ${participantId}: ${notificationType}`,
);
// Trigger Email Notification
await this.triggerPaymentConfirmationEmail(participantId, {
amount: data.amount,
splitId,
txHash: data.txHash,
});
}
/**
* Resend notifications for an existing payment
*/
private async resendNotifications(payment: Payment): Promise<void> {
const notificationType =
payment.status === PaymentProcessingStatus.PARTIAL
? "partial_payment_received"
: "payment_confirmed";
this.paymentGateway.emitPaymentNotification(`participant_${payment.participantId}`, {
type: notificationType,
data: {
txHash: payment.txHash,
amount: payment.amount,
asset: payment.asset,
},
timestamp: new Date(),
});
this.eventsGateway.emitPaymentReceived(payment.splitId, {
participantId: payment.participantId,
type: notificationType,
txHash: payment.txHash,
amount: payment.amount,
asset: payment.asset,
timestamp: new Date().toISOString(),
});
// Update notification sent flag
await this.paymentRepository.update(payment.id, {
notificationsSent: true,
});
}
/**
* Send split completion notification
*/
private sendSplitCompletedNotification(splitId: string): void {
const roomId = `split_${splitId}`;
this.paymentGateway.emitSplitCompletion(roomId, {
splitId,
status: "completed",
timestamp: new Date(),
});
this.eventsGateway.emitSplitUpdated(splitId, {
splitId,
status: "completed",
timestamp: new Date().toISOString(),
});
this.logger.log(`Sending split completed notification for split ${splitId}`);
this.triggerSplitCompletedEmail(splitId);
}
/**
* Trigger payment confirmation email
*/
private async triggerPaymentConfirmationEmail(
participantId: string,
data: { amount: number; splitId: string; txHash: string },
) {
try {
const participant = await this.participantRepository.findOne({
where: { id: participantId },
});
const split = await this.splitRepository.findOne({
where: { id: data.splitId },
});
if (participant) {
const user = await this.emailService.getUser(participant.userId);
if (user) {
await this.emailService.sendPaymentConfirmation(user.email, {
amount: data.amount,
splitDescription: split?.description || "Payment",
txHash: data.txHash,
});
}
}
} catch (error) {
this.logger.warn(`Failed to send payment confirmation email: ${error}`);
}
}
/**
* Trigger split completed email
*/
private triggerSplitCompletedEmail(splitId: string): void {
// Implementation would send emails to all participants
this.logger.log(`Triggering split completed email for split ${splitId}`);
}
/**
* Invalidate analytics cache
*/
private async invalidateAnalyticsCache(userId: string): Promise<void> {
try {
if (this.analyticsService) {
await this.analyticsService.invalidateUserCache(userId);
this.analyticsService.refreshMaterializedViewsNow();
}
} catch (err) {
this.logger.warn(
"Failed to notify analytics service about payment",
err,
);
}
}
/**
* Generate a unique ID
*/
private generateId(): string {
return crypto.randomUUID();
}
}