forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaymentController.js
More file actions
974 lines (876 loc) · 28.9 KB
/
Copy pathpaymentController.js
File metadata and controls
974 lines (876 loc) · 28.9 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
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
// controllers/stellar/paymentController.js
import mongoose from "mongoose";
import User from "../../models/User.js";
import Book from "../../models/Book.js";
import Course from "../../models/Course.js";
import Transaction from "../../models/Transaction.js";
import {
buildPaymentTransaction,
buildPathPaymentTransaction,
buildSep7Uri,
calculateFeeSplit,
preflightPayment,
submitTransaction,
verifyTransaction,
verifyPaymentOperations,
findPaymentPaths,
applySlippage,
NETWORK,
getExplorerUrl,
USDC,
PLATFORM_WALLET_PUBLIC_KEY,
} from "../../services/stellar/stellarService.js";
import { getAssetConfig, isAssetSupported, getSupportedCodes } from "../../config/assets.js";
import * as StellarSdk from "@stellar/stellar-sdk";
import { recordSaleEarnings } from "../../services/payoutService.js";
import { grantItemAccess } from "../../services/stellar/reconciliationService.js";
import { enqueue } from "../../jobs/queue.js";
import logger from "../../config/logger.js";
import {
paymentsInitialized,
paymentsSubmitted,
paymentsConfirmed,
paymentsFailed,
} from "../../config/metrics.js";
import { recordAudit } from "../../services/audit/auditService.js";
import { AUDIT_ACTIONS } from "../../models/AuditLog.js";
/**
* Resolve the item, its creator, and the settlement destination wallet for a
* purchase. Shared by initializePayment and the pre-flight endpoint so both
* look up the same destination the same way.
*/
const resolvePaymentDestination = async ({ itemType, itemId, session }) => {
const Model = itemType === "book" ? Book : Course;
const populateField = itemType === "book" ? "author" : "createdBy";
const query = Model.findById(itemId).populate(populateField, "stellarWallet name");
const item = session ? await query.session(session) : await query;
if (!item) {
return { error: { status: 404, message: `${itemType} not found` } };
}
const creator = itemType === "book" ? item.author : item.createdBy;
const platformCollectEnabled = process.env.PLATFORM_COLLECT_ENABLED === "true";
let destinationPublicKey;
let settlementMode = "direct";
if (!creator?.stellarWallet?.publicKey) {
if (!platformCollectEnabled) {
return {
error: {
status: 400,
message: "Creator has not connected their Stellar wallet yet",
},
};
}
const platformWalletKey = process.env.PLATFORM_WALLET_PUBLIC_KEY || PLATFORM_WALLET_PUBLIC_KEY;
if (!platformWalletKey) {
return {
error: {
status: 500,
message: "Platform wallet is not configured for platform-collect mode",
},
};
}
destinationPublicKey = platformWalletKey;
settlementMode = "platform_collect";
} else {
destinationPublicKey = creator.stellarWallet.publicKey;
}
return { item, creator, destinationPublicKey, settlementMode };
};
/**
* Resolve the asset code an item is priced in, defaulting to USDC for
* existing items with no currency set.
*/
const resolveItemCurrency = (item) => item.currency || "USDC";
/**
* Platform memo convention: purchases are tagged DNB-<ITEMTYPE>-<last 8 chars
* of the Mongo item id>, always as a text memo. This is always non-empty, so
* it already satisfies SEP-29 "some memo present" destinations; it does not
* substitute for a destination-specific memo (e.g. an exchange deposit id).
*/
const buildPurchaseMemo = (itemType, itemId) =>
`DNB-${itemType.toUpperCase()}-${itemId.toString().slice(-8)}`;
/**
* Get a quote for paying with a non-USDC asset via path payment
* POST /api/stellar/payment/quote
*
* NOTE: path payments always settle in USDC regardless of the item's own
* currency - that mechanism is issue #27's scope. Items priced in a
* non-USDC currency (e.g. EURC) are rejected here rather than silently
* treating item.price as a USDC amount.
*/
export const getQuote = async (req, res) => {
try {
const { itemType, itemId, sendAssetCode, sendAssetIssuer } = req.body;
if (!["book", "course"].includes(itemType)) {
return res.status(400).json({
success: false,
message: "Invalid item type. Must be 'book' or 'course'",
});
}
const Model = itemType === "book" ? Book : Course;
const item = await Model.findById(itemId);
if (!item) {
return res.status(404).json({
success: false,
message: `${itemType} not found`,
});
}
if (!item.price || item.price === 0) {
return res.status(400).json({
success: false,
message: "This item is free, no quote needed",
});
}
const itemAssetCode = resolveItemCurrency(item);
if (itemAssetCode !== "USDC") {
return res.status(400).json({
success: false,
message: `Path payment quotes are only available for USDC-priced items. This item is priced in ${itemAssetCode}; pay directly in ${itemAssetCode} instead.`,
});
}
if (sendAssetCode && !sendAssetIssuer && sendAssetCode !== "XLM" && sendAssetCode !== "native") {
return res.status(400).json({
success: false,
message: "Non-native assets require an issuer. Omit sendAssetIssuer only for native XLM.",
});
}
const sendAsset = sendAssetIssuer
? new StellarSdk.Asset(sendAssetCode, sendAssetIssuer)
: StellarSdk.Asset.native();
const destAmount = item.price.toString();
const paths = await findPaymentPaths(sendAsset, destAmount);
if (!paths || paths.length === 0) {
return res.status(404).json({
success: false,
message: "No payment path found for the given asset",
});
}
const bestPath = paths[0];
const slippageBps = Math.min(
500,
Math.max(10, Number(req.body.slippageBps) || 100)
);
const sendMax = applySlippage(bestPath.source_amount, slippageBps);
const sourceAsset = {
asset_type: bestPath.source_asset_type,
...(bestPath.source_asset_type !== "native" && {
asset_code: bestPath.source_asset_code,
asset_issuer: bestPath.source_asset_issuer,
}),
};
const pathAssets = (bestPath.path || []).map((a) => ({
asset_type: a.asset_type,
...(a.asset_type !== "native" && {
asset_code: a.asset_code,
asset_issuer: a.asset_issuer,
}),
}));
const expiresAt = new Date(Date.now() + 30 * 1000).toISOString();
res.status(200).json({
success: true,
quote: {
source_asset: sourceAsset,
source_amount: bestPath.source_amount,
destination_asset: { asset_type: "credit_alphanum4", asset_code: "USDC", asset_issuer: USDC.getIssuer() },
destination_amount: destAmount,
path: pathAssets,
sendMax,
slippageBps,
expiresAt,
note: "Quote is an estimate. The on-chain bound enforced is sendMax, not the quoted source_amount.",
},
});
} catch (error) {
logger.error("Quote error:", error);
if (
error.message?.includes("Invalid asset") ||
error.message?.includes("bad asset")
) {
return res.status(400).json({
success: false,
message: "Unknown or invalid asset",
});
}
res.status(500).json({
success: false,
message: "Failed to get quote",
error: process.env.NODE_ENV === "development" ? error.message : undefined,
});
}
};
/**
* Run pre-flight payment safety checks (destination existence, trustline
* for the item's currency, source balance/reserve, SEP-29 memo-required)
* before the frontend prompts the wallet to sign anything.
* POST /api/stellar/payment/preflight
*/
export const getPaymentPreflight = async (req, res) => {
try {
const buyerId = req.user._id;
const { itemType, itemId } = req.body;
if (!["book", "course"].includes(itemType)) {
return res.status(400).json({
success: false,
message: "Invalid item type. Must be 'book' or 'course'",
});
}
const buyer = await User.findById(buyerId);
if (!buyer?.stellarWallet?.publicKey) {
return res.status(400).json({
success: false,
message: "Please connect your Stellar wallet first",
});
}
const resolved = await resolvePaymentDestination({ itemType, itemId });
if (resolved.error) {
return res.status(resolved.error.status).json({
success: false,
message: resolved.error.message,
});
}
const { item, destinationPublicKey, settlementMode } = resolved;
if (!item.price || item.price === 0) {
return res.status(400).json({
success: false,
message: "This item is free, no payment required",
});
}
const assetCode = resolveItemCurrency(item);
if (!isAssetSupported(assetCode)) {
return res.status(400).json({
success: false,
message: `This item is priced in an unsupported asset (${assetCode}). Supported: ${getSupportedCodes().join(", ")}`,
});
}
const memo = buildPurchaseMemo(itemType, itemId);
const feeSplitPreview =
settlementMode === "direct" ? calculateFeeSplit(item.price) : null;
const preflight = await preflightPayment({
sourcePublicKey: buyer.stellarWallet.publicKey,
destinationPublicKey,
amount: item.price.toString(),
memo,
operationCount: feeSplitPreview ? 2 : 1,
assetCode,
});
res.status(200).json({
success: true,
preflight,
});
} catch (error) {
logger.error("Payment preflight error:", error);
res.status(500).json({
success: false,
message: "Failed to run payment pre-flight checks",
error:
process.env.NODE_ENV === "development" ? error.message : undefined,
});
}
};
/**
* Initialize a payment - creates pending transaction and returns XDR to sign
* POST /api/stellar/payment/initialize
*/
export const initializePayment = async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
const buyerId = req.user._id;
const { itemType, itemId, buyerWallet, sendAsset: sendAssetInput, sendMax, path: pathInput } = req.body;
if (!["book", "course"].includes(itemType)) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Invalid item type. Must be 'book' or 'course'",
});
}
const buyer = await User.findById(buyerId).session(session);
if (!buyer?.stellarWallet?.publicKey) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Please connect your Stellar wallet first",
});
}
if (buyer.stellarWallet.publicKey !== buyerWallet) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Wallet mismatch. Please reconnect your wallet.",
});
}
const resolved = await resolvePaymentDestination({ itemType, itemId, session });
if (resolved.error) {
await session.abortTransaction();
return res.status(resolved.error.status).json({
success: false,
message: resolved.error.message,
});
}
const { item, creator, destinationPublicKey, settlementMode } = resolved;
if (!item.price || item.price === 0) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "This item is free, no payment required",
});
}
const itemAssetCode = resolveItemCurrency(item);
if (!isAssetSupported(itemAssetCode)) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: `This item is priced in an unsupported asset (${itemAssetCode}). Supported: ${getSupportedCodes().join(", ")}`,
});
}
const purchasedArray =
itemType === "book" ? buyer.purchasedBooks : buyer.purchasedCourses;
const idField = itemType === "book" ? "bookId" : "courseId";
const alreadyPurchased = purchasedArray?.some(
(p) => p[idField]?.toString() === itemId
);
if (alreadyPurchased) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: `You already own this ${itemType}`,
});
}
const existingTx = await Transaction.findOne({
buyer: buyerId,
itemType,
itemId,
status: { $in: ["pending", "submitted"] },
}).session(session);
if (existingTx) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "You have a pending transaction for this item",
transactionId: existingTx._id,
});
}
const memo = buildPurchaseMemo(itemType, itemId);
const isPathPayment = sendAssetInput && sendMax;
let paymentTx;
let sep7Uri = null;
// Currency actually settled on-chain: path payments always settle in
// USDC (issue #27's mechanism); direct payments settle in the item's
// own currency. Set explicitly in each branch below rather than
// defaulting, so it's clear neither branch can silently fall through.
let settledAssetCode;
if (isPathPayment) {
// Path payments always settle in USDC. Guard against an item priced
// in a different asset, since destAmount below is item.price and
// would otherwise be misinterpreted as a USDC amount.
if (itemAssetCode !== "USDC") {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: `Path payments are only available for USDC-priced items. This item is priced in ${itemAssetCode}; pay directly in ${itemAssetCode} instead.`,
});
}
settledAssetCode = "USDC";
const sendAsset = sendAssetInput.issuer
? new StellarSdk.Asset(sendAssetInput.code, sendAssetInput.issuer)
: StellarSdk.Asset.native();
const path = (pathInput || []).map((a) => ({
asset_type: a.asset_type,
...(a.asset_type !== "native" && {
asset_code: a.asset_code,
asset_issuer: a.asset_issuer,
}),
}));
paymentTx = await buildPathPaymentTransaction({
sourcePublicKey: buyer.stellarWallet.publicKey,
destinationPublicKey,
destAmount: item.price.toString(),
sendAsset,
sendMax,
path,
memo,
applyPlatformFee: settlementMode === "direct",
});
} else {
settledAssetCode = itemAssetCode;
const feeSplitPreview =
settlementMode === "direct" ? calculateFeeSplit(item.price) : null;
const preflight = await preflightPayment({
sourcePublicKey: buyer.stellarWallet.publicKey,
destinationPublicKey,
amount: item.price.toString(),
memo,
operationCount: feeSplitPreview ? 2 : 1,
assetCode: itemAssetCode,
});
if (!preflight.ok) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Payment failed pre-flight safety checks",
reasons: preflight.reasons,
});
}
paymentTx = await buildPaymentTransaction({
sourcePublicKey: buyer.stellarWallet.publicKey,
destinationPublicKey,
amount: item.price.toString(),
memo,
applyPlatformFee: settlementMode === "direct",
assetCode: itemAssetCode,
});
sep7Uri = buildSep7Uri({
destination: destinationPublicKey,
amount: item.price.toString(),
memo,
assetCode: itemAssetCode,
});
}
const feeSplit = paymentTx.feeSplit;
const settledAssetConfig = getAssetConfig(settledAssetCode);
const transaction = new Transaction({
buyer: buyerId,
buyerWallet: buyer.stellarWallet.publicKey,
creator: creator._id,
creatorWallet: destinationPublicKey,
itemType,
itemId,
itemTypeModel: itemType === "book" ? "Book" : "Course",
itemTitle: item.title,
amount: item.price.toString(),
currency: settledAssetCode,
assetIssuer: settledAssetConfig?.issuer || null,
network: NETWORK,
status: "pending",
settlement: settlementMode,
stellarTxHash: paymentTx.hash,
...(sendAssetInput && {
sendAsset: sendAssetInput,
sendMax,
}),
...(feeSplit && {
platformFee: {
feePercent: feeSplit.feePercent,
platformWallet: feeSplit.platformWallet,
platformAmount: feeSplit.platformAmount,
creatorAmount: feeSplit.creatorAmount,
},
}),
});
await transaction.save({ session });
await session.commitTransaction();
paymentsInitialized.inc({ type: "purchase" });
logger.info(
`Payment initialized: ${transaction._id} for ${itemType} ${itemId}`
);
recordAudit({
action: AUDIT_ACTIONS.PAYMENT_INITIALIZE,
actor: buyerId,
req,
targetType: "Transaction",
targetId: transaction._id.toString(),
status: "success",
metadata: {
transactionId: transaction._id.toString(),
itemType,
itemId,
itemTitle: item.title,
amount: item.price.toString(),
settlementMode,
},
});
res.status(200).json({
success: true,
transactionId: transaction._id,
payment: {
xdr: paymentTx.xdr,
networkPassphrase: paymentTx.networkPassphrase,
expectedHash: paymentTx.hash,
},
...(sep7Uri && { sep7Uri }),
...(isPathPayment && {
pathPaymentNote:
"Path payment XDR provided. SEP-7 URI is not available for path payments; use the XDR signing flow.",
}),
item: {
title: item.title,
price: item.price,
type: itemType,
},
creator: {
name: creator.name,
wallet: creator.stellarWallet.publicKey,
},
});
} catch (error) {
await session.abortTransaction();
logger.error("Initialize payment error:", error);
res.status(500).json({
success: false,
message: "Failed to initialize payment",
error:
process.env.NODE_ENV === "development" ? error.message : undefined,
});
} finally {
session.endSession();
}
};
/**
* Submit signed transaction
* POST /api/stellar/payment/submit
*/
export const submitPayment = async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
const { transactionId, signedXdr } = req.body;
const buyerId = req.user._id;
if (!transactionId || !signedXdr) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Transaction ID and signed XDR are required",
});
}
const transaction = await Transaction.findOne({
_id: transactionId,
buyer: buyerId,
status: "pending",
}).session(session);
if (!transaction) {
await session.abortTransaction();
return res.status(404).json({
success: false,
message: "Transaction not found or already processed",
});
}
transaction.status = "submitted";
transaction.submittedAt = new Date();
await transaction.save({ session });
paymentsSubmitted.inc({ type: "purchase" });
let result;
try {
result = await submitTransaction(signedXdr);
} catch (stellarError) {
transaction.status = "failed";
transaction.failureReason = stellarError.message;
await transaction.save({ session });
await session.commitTransaction();
paymentsFailed.inc({ type: "purchase", reason: "stellar_error" });
logger.error(`Transaction ${transactionId} failed:`, stellarError);
return res.status(400).json({
success: false,
message: "Transaction failed on Stellar network",
error: stellarError.message,
});
}
const expectedPayments = transaction.platformFee?.platformAmount
? [
{
destination: transaction.creatorWallet,
amount: transaction.platformFee.creatorAmount,
},
{
destination: transaction.platformFee.platformWallet,
amount: transaction.platformFee.platformAmount,
},
]
: [
{
destination: transaction.creatorWallet,
amount: transaction.amount,
},
];
const verification = await verifyPaymentOperations(
result.hash,
expectedPayments,
transaction.currency || "USDC"
);
if (!verification.verified) {
transaction.stellarTxHash = result.hash;
if (verification.transient) {
transaction.status = "retrying";
transaction.failureReason = verification.reason;
await transaction.save({ session });
try {
await enqueue(
"verifyPaymentOnChain",
{ transactionId: transaction._id.toString() },
{
attempts: 5,
backoffMs: 1000,
idempotencyKey: `verify:${result.hash}`,
session,
}
);
} catch (enqueueErr) {
// Don't let a queue outage roll back the on-chain-verified
// "retrying" status - a sweeper can still reconcile this later
// from stellarTxHash even if scheduling the retry job failed.
logger.error(
`Failed to enqueue verifyPaymentOnChain for transaction ${transaction._id}:`,
enqueueErr
);
}
await session.commitTransaction();
return res.status(202).json({
success: true,
message: "Payment submitted; confirmation is in progress",
transactionId: transaction._id,
txHash: result.hash,
status: "retrying",
});
}
transaction.status = "failed";
transaction.failureReason = `On-chain verification failed: ${verification.reason}`;
await transaction.save({ session });
await session.commitTransaction();
paymentsFailed.inc({ type: "purchase", reason: "verification_failed" });
logger.error(
`Transaction ${transactionId} verification failed: ${verification.reason}`
);
recordAudit({
action: AUDIT_ACTIONS.PAYMENT_SUBMIT_FAILED,
actor: buyerId,
req,
targetType: "Transaction",
targetId: transactionId,
status: "failure",
metadata: {
transactionId,
stellarTxHash: result.hash,
failureReason: `On-chain verification failed: ${verification.reason}`,
},
});
return res.status(400).json({
success: false,
message: "Payment could not be verified on the Stellar network",
error: verification.reason,
});
}
transaction.stellarTxHash = result.hash;
transaction.stellarLedger = result.ledger;
transaction.status = "confirmed";
transaction.confirmedAt = new Date();
await transaction.save({ session });
paymentsConfirmed.inc({ type: "purchase" });
await recordSaleEarnings(transaction, { session });
// Grant access to the purchased item (shared with ingestion worker)
await grantItemAccess({
buyerId,
itemType: transaction.itemType,
itemId: transaction.itemId,
session,
});
try {
await enqueue(
"generateReceipt",
{ transactionId: transaction._id.toString() },
{
attempts: 5,
backoffMs: 1000,
idempotencyKey: `receipt:${result.hash}`,
session,
}
);
} catch (enqueueErr) {
// Don't let a queue outage roll back a payment that's already
// confirmed on-chain (earnings recorded, access granted) - the
// receipt can be regenerated later; the purchase itself must stand.
logger.error(
`Failed to enqueue generateReceipt for transaction ${transaction._id}:`,
enqueueErr
);
}
await session.commitTransaction();
logger.info(
`Payment successful: ${transactionId}, Stellar TX: ${result.hash}`
);
recordAudit({
action: AUDIT_ACTIONS.PAYMENT_SUBMIT_CONFIRMED,
actor: buyerId,
req,
targetType: "Transaction",
targetId: transactionId,
status: "success",
metadata: {
transactionId,
stellarTxHash: result.hash,
stellarLedger: result.ledger,
amount: transaction.amount,
itemType: transaction.itemType,
itemId: transaction.itemId.toString(),
settlementMode: transaction.settlement,
},
});
res.status(200).json({
success: true,
message: "Payment successful!",
transaction: {
id: transaction._id,
hash: result.hash,
ledger: result.ledger,
itemTitle: transaction.itemTitle,
amount: transaction.amount,
explorerUrl: getExplorerUrl(result.hash),
},
});
} catch (error) {
await session.abortTransaction();
logger.error("Submit payment error:", error);
res.status(500).json({
success: false,
message: "Failed to process payment",
error:
process.env.NODE_ENV === "development" ? error.message : undefined,
});
} finally {
session.endSession();
}
};
/**
* Get transaction history for a user
* GET /api/stellar/payment/transactions
*/
export const getTransactionHistory = async (req, res) => {
try {
const userId = req.user._id;
const { role = "buyer", page = 1, limit = 20 } = req.query;
const query =
role === "creator" ? { creator: userId } : { buyer: userId };
const transactions = await Transaction.find(query)
.sort({ createdAt: -1 })
.skip((page - 1) * limit)
.limit(parseInt(limit))
.populate("buyer", "name avatar")
.populate("creator", "name avatar");
const total = await Transaction.countDocuments(query);
const transactionsWithUrls = transactions.map((tx) => ({
...tx.toObject(),
explorerUrl:
tx.status === "confirmed" ? getExplorerUrl(tx.stellarTxHash) : null,
}));
res.status(200).json({
success: true,
transactions: transactionsWithUrls,
pagination: {
page: parseInt(page),
limit: parseInt(limit),
total,
pages: Math.ceil(total / limit),
},
});
} catch (error) {
logger.error("Get transaction history error:", error);
res.status(500).json({
success: false,
message: "Failed to fetch transactions",
});
}
};
/**
* Get single transaction details
* GET /api/stellar/payment/transactions/:transactionId
*/
export const getTransaction = async (req, res) => {
try {
const { transactionId } = req.params;
const userId = req.user._id;
const transaction = await Transaction.findOne({
_id: transactionId,
$or: [{ buyer: userId }, { creator: userId }],
})
.populate("buyer", "name avatar")
.populate("creator", "name avatar");
if (!transaction) {
return res.status(404).json({
success: false,
message: "Transaction not found",
});
}
let stellarVerification = null;
if (transaction.status === "confirmed") {
try {
stellarVerification = await verifyTransaction(
transaction.stellarTxHash
);
} catch (error) {
logger.warn(
`Failed to verify transaction ${transactionId}:`,
error
);
}
}
res.status(200).json({
success: true,
transaction: {
...transaction.toObject(),
explorerUrl:
transaction.status === "confirmed"
? getExplorerUrl(transaction.stellarTxHash)
: null,
},
stellarVerification,
});
} catch (error) {
logger.error("Get transaction error:", error);
res.status(500).json({
success: false,
message: "Failed to fetch transaction",
});
}
};
/**
* Cancel a pending transaction
* DELETE /api/stellar/payment/transactions/:transactionId
*/
export const cancelTransaction = async (req, res) => {
try {
const { transactionId } = req.params;
const userId = req.user._id;
const transaction = await Transaction.findOneAndUpdate(
{
_id: transactionId,
buyer: userId,
status: "pending",
},
{
status: "expired",
failureReason: "Cancelled by user",
},
{ new: true }
);
if (!transaction) {
return res.status(404).json({
success: false,
message: "Transaction not found or cannot be cancelled",
});
}
logger.info(`Transaction ${transactionId} cancelled by user ${userId}`);
recordAudit({
action: AUDIT_ACTIONS.PAYMENT_CANCEL,
actor: userId,
req,
targetType: "Transaction",
targetId: transactionId,
status: "success",
metadata: {
transactionId,
itemType: transaction.itemType,
itemId: transaction.itemId?.toString(),
amount: transaction.amount,
failureReason: "Cancelled by user",
},
});
res.status(200).json({
success: true,
message: "Transaction cancelled",
});
} catch (error) {
logger.error("Cancel transaction error:", error);
res.status(500).json({
success: false,
message: "Failed to cancel transaction",
});
}
};