forked from Emmy123222/Stellar-MicroPay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtipsService.js
More file actions
253 lines (212 loc) · 6.91 KB
/
Copy pathtipsService.js
File metadata and controls
253 lines (212 loc) · 6.91 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
/**
* src/services/tipsService.js
* Business logic for tracking tips received by creators.
* Uses in-memory storage for v1 (can be migrated to database later).
*/
"use strict";
// In-memory storage for tips
// Structure: Map<creatorPublicKey, TipRecord[]>
const tipsByCreator = new Map();
// Tip record structure:
// { id, senderPublicKey, creatorPublicKey, amount, asset, memo, timestamp, txHash }
let tipIdCounter = 1;
/**
* Record a tip sent to a creator.
* @param {string} senderPublicKey - The Stellar public key of the sender
* @param {string} creatorPublicKey - The Stellar public key of the creator
* @param {string} amount - The amount sent
* @param {string} asset - The asset code (XLM, USDC, etc.)
* @param {string} [memo] - Optional memo/message from sender
* @param {string} [txHash] - The transaction hash
* @returns {object} The created tip record
*/
function recordTip({ senderPublicKey, creatorPublicKey, amount, asset = "XLM", memo = "", txHash = "" }) {
if (!senderPublicKey || !creatorPublicKey || !amount) {
const error = new Error("senderPublicKey, creatorPublicKey, and amount are required");
error.status = 400;
throw error;
}
const tip = {
id: tipIdCounter++,
senderPublicKey,
creatorPublicKey,
amount: String(amount),
asset,
memo,
txHash,
timestamp: new Date().toISOString(),
};
if (!tipsByCreator.has(creatorPublicKey)) {
tipsByCreator.set(creatorPublicKey, []);
}
tipsByCreator.get(creatorPublicKey).unshift(tip); // Add to beginning (most recent first)
return tip;
}
/**
* Get all tips received by a creator.
* @param {string} creatorPublicKey - The Stellar public key of the creator
* @param {object} [options] - Optional filters
* @param {number} [options.limit] - Maximum number of tips to return
* @param {number} [options.offset] - Number of tips to skip (for pagination)
* @returns {object} Object with tips array and total count
*/
function getTipsReceived(creatorPublicKey, options = {}) {
if (!creatorPublicKey) {
const error = new Error("creatorPublicKey is required");
error.status = 400;
throw error;
}
const { limit = 50, offset = 0 } = options;
const tips = tipsByCreator.get(creatorPublicKey) || [];
const total = tips.length;
const paginatedTips = tips.slice(offset, offset + limit);
return {
tips: paginatedTips,
total,
limit,
offset,
};
}
/**
* Get statistics for tips received by a creator.
* @param {string} creatorPublicKey - The Stellar public key of the creator
* @returns {object} Object with total tips, total amount by asset
*/
function getTipsStats(creatorPublicKey) {
if (!creatorPublicKey) {
const error = new Error("creatorPublicKey is required");
error.status = 400;
throw error;
}
const tips = tipsByCreator.get(creatorPublicKey) || [];
const stats = {
totalTips: tips.length,
totalByAsset: {},
averageTip: null,
largestTip: null,
smallestTip: null,
};
// Calculate totals by asset
for (const tip of tips) {
const asset = tip.asset || "XLM";
if (!stats.totalByAsset[asset]) {
stats.totalByAsset[asset] = { count: 0, amount: 0 };
}
stats.totalByAsset[asset].count++;
stats.totalByAsset[asset].amount += parseFloat(tip.amount);
}
// Convert amounts to strings with proper precision
for (const asset of Object.keys(stats.totalByAsset)) {
stats.totalByAsset[asset].amount = String(stats.totalByAsset[asset].amount);
}
// Calculate average
if (tips.length > 0) {
const totalAmount = tips.reduce((sum, tip) => sum + parseFloat(tip.amount), 0);
stats.averageTip = String(totalAmount / tips.length);
const amounts = tips.map(t => parseFloat(t.amount));
stats.largestTip = String(Math.max(...amounts));
stats.smallestTip = String(Math.min(...amounts));
}
return stats;
}
/**
* Get all tips sent by a user (for sender's history).
* @param {string} senderPublicKey - The Stellar public key of the sender
* @param {object} [options] - Optional filters
* @returns {object} Object with tips array and total count
*/
function getTipsSent(senderPublicKey, options = {}) {
if (!senderPublicKey) {
const error = new Error("senderPublicKey is required");
error.status = 400;
throw error;
}
const { limit = 50, offset = 0 } = options;
// Search all tips to find ones sent by this user
const allTips = [];
for (const tips of tipsByCreator.values()) {
for (const tip of tips) {
if (tip.senderPublicKey === senderPublicKey) {
allTips.push(tip);
}
}
}
// Sort by timestamp descending
allTips.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
const total = allTips.length;
const paginatedTips = allTips.slice(offset, offset + limit);
return {
tips: paginatedTips,
total,
limit,
offset,
};
}
/**
* Validate tip record input.
*/
function validateTipInput(data) {
const errors = [];
if (!data.senderPublicKey) {
errors.push("senderPublicKey is required");
} else if (!/^G[A-Z0-9]{55}$/.test(data.senderPublicKey)) {
errors.push("Invalid sender public key format");
}
if (!data.creatorPublicKey) {
errors.push("creatorPublicKey is required");
} else if (!/^G[A-Z0-9]{55}$/.test(data.creatorPublicKey)) {
errors.push("Invalid creator public key format");
}
if (!data.amount) {
errors.push("amount is required");
} else if (isNaN(parseFloat(data.amount)) || parseFloat(data.amount) <= 0) {
errors.push("amount must be a positive number");
}
if (errors.length > 0) {
const error = new Error(errors.join(", "));
error.status = 400;
throw error;
}
return true;
}
/**
* Get top tippers for a creator.
* @param {string} creatorPublicKey - The creator's public key
* @param {number} limit - The number of tippers to return
* @returns {Array} Sorted array of top tippers
*/
function getTopTippers(creatorPublicKey, limit = 5) {
if (!creatorPublicKey) {
const error = new Error("creatorPublicKey is required");
error.status = 400;
throw error;
}
const tips = tipsByCreator.get(creatorPublicKey) || [];
// Aggregate total tipped per sender
const totals = new Map();
for (const tip of tips) {
const sender = tip.senderPublicKey;
const amount = parseFloat(tip.amount) || 0;
totals.set(sender, (totals.get(sender) || 0) + amount);
}
// Convert to array
const entries = Array.from(totals.entries()).map(([senderPublicKey, totalAmount]) => ({
senderPublicKey,
totalAmount: totalAmount.toFixed(7),
}));
// Sort descending by amount
// If there are ties, JavaScript's stable sort (or standard array sorting) preserves order
entries.sort((a, b) => parseFloat(b.totalAmount) - parseFloat(a.totalAmount));
// Limit result count
const result = entries.slice(0, limit);
return result;
}
module.exports = {
recordTip,
getTipsReceived,
getTipsStats,
getTipsSent,
validateTipInput,
getTopTippers,
tipsByCreator,
};