forked from Deen-Bridge/dnb-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdonationController.js
More file actions
337 lines (304 loc) · 9.67 KB
/
Copy pathdonationController.js
File metadata and controls
337 lines (304 loc) · 9.67 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
// controllers/stellar/donationController.js
import mongoose from "mongoose";
import Transaction from "../../models/Transaction.js";
import {
isValidPublicKey,
getAccountBalance,
buildPaymentTransaction,
buildSep7Uri,
submitTransaction,
verifyPaymentOperations,
getExplorerUrl,
NETWORK,
DONATION_WALLET_PUBLIC_KEY,
} from "../../services/stellar/stellarService.js";
import logger from "../../config/logger.js";
import { enqueue } from "../../jobs/queue.js";
import {
paymentsInitialized,
paymentsSubmitted,
paymentsConfirmed,
paymentsFailed,
} from "../../config/metrics.js";
const DONATION_MEMO = "DNB-SADAQAH";
/**
* Initialize a sadaqah donation - creates pending record and returns XDR to sign
* POST /api/stellar/donation/initialize
*/
export const initializeDonation = async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
const donorId = req.user._id;
const { amount, publicKey } = req.body;
// Donation wallet must be configured on the server
if (!DONATION_WALLET_PUBLIC_KEY) {
await session.abortTransaction();
return res.status(503).json({
success: false,
message: "Donations are not available right now. Please try again later.",
});
}
// Validate donor public key
if (!publicKey || !isValidPublicKey(publicKey)) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Invalid Stellar public key",
});
}
// Validate amount (positive, max 7 decimal places)
const parsedAmount = Number(amount);
if (
!amount ||
!Number.isFinite(parsedAmount) ||
parsedAmount <= 0 ||
!/^\d+(\.\d{1,7})?$/.test(amount.toString())
) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message:
"Invalid amount. Must be a positive number with at most 7 decimal places",
});
}
// Build the donation payment transaction (donor -> donation fund)
const paymentTx = await buildPaymentTransaction({
sourcePublicKey: publicKey,
destinationPublicKey: DONATION_WALLET_PUBLIC_KEY,
amount: amount.toString(),
memo: DONATION_MEMO,
});
// SEP-7 URI so wallets can deep-link the same payment
const sep7Uri = buildSep7Uri({
destination: DONATION_WALLET_PUBLIC_KEY,
amount: amount.toString(),
memo: DONATION_MEMO,
});
// Create pending donation record
const donation = new Transaction({
type: "donation",
buyer: donorId,
buyerWallet: publicKey,
creatorWallet: DONATION_WALLET_PUBLIC_KEY,
amount: amount.toString(),
network: NETWORK,
status: "pending",
stellarTxHash: paymentTx.hash, // Temporary hash, will be replaced with actual
});
await donation.save({ session });
await session.commitTransaction();
paymentsInitialized.inc({ type: "donation" });
logger.info(`Donation initialized: ${donation._id} for ${amount} USDC`);
res.status(200).json({
success: true,
donationId: donation._id,
transactionXdr: paymentTx.xdr,
sep7Uri,
networkPassphrase: paymentTx.networkPassphrase,
});
} catch (error) {
await session.abortTransaction();
logger.error("Initialize donation error:", error);
res.status(500).json({
success: false,
message: "Failed to initialize donation",
error:
process.env.NODE_ENV === "development" ? error.message : undefined,
});
} finally {
session.endSession();
}
};
/**
* Submit signed donation transaction
* POST /api/stellar/donation/submit
*/
export const submitDonation = async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
const { donationId, signedXdr } = req.body;
const donorId = req.user._id;
if (!donationId || !signedXdr) {
await session.abortTransaction();
return res.status(400).json({
success: false,
message: "Donation ID and signed XDR are required",
});
}
// Find the pending donation
const donation = await Transaction.findOne({
_id: donationId,
buyer: donorId,
type: "donation",
status: "pending",
}).session(session);
if (!donation) {
await session.abortTransaction();
return res.status(404).json({
success: false,
message: "Donation not found or already processed",
});
}
// Update status to submitted
donation.status = "submitted";
donation.submittedAt = new Date();
await donation.save({ session });
paymentsSubmitted.inc({ type: "donation" });
// Submit to Stellar network
let result;
try {
result = await submitTransaction(signedXdr);
} catch (stellarError) {
donation.status = "failed";
donation.failureReason = stellarError.message;
await donation.save({ session });
await session.commitTransaction();
paymentsFailed.inc({ type: "donation", reason: "stellar_error" });
logger.error(`Donation ${donationId} failed:`, stellarError);
return res.status(400).json({
success: false,
message: "Donation failed on Stellar network",
error: stellarError.message,
});
}
// Verify on-chain that the donation actually paid the fund (amount, destination, asset)
const verification = await verifyPaymentOperations(result.hash, [
{
destination: donation.creatorWallet,
amount: donation.amount,
},
]);
if (!verification.verified) {
donation.stellarTxHash = result.hash;
if (verification.transient) {
donation.status = "retrying";
donation.failureReason = verification.reason;
await donation.save({ session });
await enqueue(
"verifyPaymentOnChain",
{ transactionId: donation._id.toString() },
{
attempts: 5,
backoffMs: 1000,
idempotencyKey: `verify:${result.hash}`,
session,
}
);
await session.commitTransaction();
return res.status(202).json({
success: true,
message: "Donation submitted; confirmation is in progress",
donationId: donation._id,
txHash: result.hash,
status: "retrying",
});
}
donation.status = "failed";
donation.failureReason = `On-chain verification failed: ${verification.reason}`;
await donation.save({ session });
await session.commitTransaction();
paymentsFailed.inc({ type: "donation", reason: "verification_failed" });
logger.error(
`Donation ${donationId} verification failed: ${verification.reason}`
);
return res.status(400).json({
success: false,
message: "Donation could not be verified on the Stellar network",
error: verification.reason,
});
}
// Mark confirmed
donation.stellarTxHash = result.hash;
donation.stellarLedger = result.ledger;
donation.status = "confirmed";
donation.confirmedAt = new Date();
await donation.save({ session });
await enqueue(
"generateReceipt",
{ transactionId: donation._id.toString() },
{
attempts: 5,
backoffMs: 1000,
idempotencyKey: `receipt:${result.hash}`,
session,
}
);
await session.commitTransaction();
paymentsConfirmed.inc({ type: "donation" });
logger.info(
`Donation successful: ${donationId}, Stellar TX: ${result.hash}`
);
res.status(200).json({
success: true,
message: "JazakAllah khair! Your sadaqah has been received.",
txHash: result.hash,
explorerUrl: getExplorerUrl(result.hash),
});
} catch (error) {
await session.abortTransaction();
logger.error("Submit donation error:", error);
res.status(500).json({
success: false,
message: "Failed to process donation",
error:
process.env.NODE_ENV === "development" ? error.message : undefined,
});
} finally {
session.endSession();
}
};
/**
* Get public donation pool stats (no donor identity exposed)
* GET /api/stellar/donation/stats
*/
export const getDonationStats = async (req, res) => {
try {
if (!DONATION_WALLET_PUBLIC_KEY) {
return res.status(503).json({
success: false,
message: "Donation wallet is not configured",
});
}
// Live USDC balance of the donation fund from Horizon
const balance = await getAccountBalance(DONATION_WALLET_PUBLIC_KEY);
// Aggregate confirmed donations
const [totals] = await Transaction.aggregate([
{ $match: { type: "donation", status: "confirmed" } },
{
$group: {
_id: null,
donationCount: { $sum: 1 },
totalDonated: { $sum: { $toDouble: "$amount" } },
},
},
]);
// Recent confirmed donations - amounts and hashes only, no donor identity
const recentDonations = await Transaction.find({
type: "donation",
status: "confirmed",
})
.sort({ createdAt: -1 })
.limit(10)
.select("amount stellarTxHash createdAt");
res.status(200).json({
success: true,
poolBalance: balance.usdcBalance,
donationCount: totals?.donationCount || 0,
totalDonated: totals?.totalDonated || 0,
recent: recentDonations.map((donation) => ({
amount: donation.amount,
txHash: donation.stellarTxHash,
explorerUrl: getExplorerUrl(donation.stellarTxHash),
createdAt: donation.createdAt,
})),
});
} catch (error) {
logger.error("Get donation stats error:", error);
res.status(500).json({
success: false,
message: "Failed to fetch donation stats",
});
}
};