forked from StellarEdu/StellarEduPay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstellar.test.js
More file actions
482 lines (398 loc) · 18.7 KB
/
Copy pathstellar.test.js
File metadata and controls
482 lines (398 loc) · 18.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
'use strict';
// Must set required env vars before any module that loads config/index.js
process.env.MONGO_URI = 'mongodb://localhost:27017/test';
process.env.SCHOOL_WALLET_ADDRESS = 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B';
const {
verifyTransaction,
syncPaymentsForSchool,
parseIncomingTransaction,
validatePaymentAgainstFee,
detectAsset,
normalizeAmount,
extractValidPayment,
} = require('../backend/src/services/stellarService');
// ─── Mocks ────────────────────────────────────────────────────────────────────
const mockOperations = jest.fn();
jest.mock('../backend/src/config/stellarConfig', () => ({
SCHOOL_WALLET: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B',
CONFIRMATION_THRESHOLD: 2,
ACCEPTED_ASSETS: {
XLM: { code: 'XLM', type: 'native', issuer: null },
USDC: { code: 'USDC', type: 'credit_alphanum4', issuer: 'GISSUER' },
},
isAcceptedAsset: (code, type) => {
const map = { XLM: 'native', USDC: 'credit_alphanum4' };
if (map[code] && map[code] === type) return { accepted: true, asset: { code, type } };
return { accepted: false, asset: null };
},
server: {
transactions: () => ({
forAccount: () => ({
order: () => ({ limit: () => ({ call: async () => ({ records: [], next: async () => ({ records: [] }) }) }) }),
}),
transaction: (txHash) => ({
call: async () => ({
hash: txHash,
memo: 'STU001',
successful: true,
created_at: new Date().toISOString(),
operations: mockOperations,
}),
}),
}),
ledgers: () => ({
order: () => ({ limit: () => ({ call: async () => ({ records: [{ sequence: 100 }] }) }) }),
}),
},
}));
jest.mock('../backend/src/models/paymentModel', () => ({
findOne: jest.fn(),
create: jest.fn().mockResolvedValue({}),
exists: jest.fn().mockResolvedValue(false),
}));
jest.mock('../backend/src/models/paymentIntentModel', () => ({
findOne: jest.fn().mockResolvedValue({ _id: 'intent123', studentId: 'STU001', amount: 200, memo: 'STU001', status: 'pending' }),
findByIdAndUpdate: jest.fn().mockResolvedValue({}),
}));
jest.mock('../backend/src/models/studentModel', () => ({
findOne: jest.fn(),
findOneAndUpdate: jest.fn().mockResolvedValue({}),
}));
const Payment = require('../backend/src/models/paymentModel');
const Student = require('../backend/src/models/studentModel');
// ─── validatePaymentAgainstFee ────────────────────────────────────────────────
describe('validatePaymentAgainstFee', () => {
test('valid when payment equals fee', () => {
expect(validatePaymentAgainstFee(200, 200).status).toBe('valid');
});
test('underpaid when payment is less than fee', () => {
expect(validatePaymentAgainstFee(150, 200).status).toBe('underpaid');
});
test('overpaid when payment exceeds fee', () => {
expect(validatePaymentAgainstFee(250, 200).status).toBe('overpaid');
});
test('messages include the amounts', () => {
expect(validatePaymentAgainstFee(50, 200).message).toContain('50');
expect(validatePaymentAgainstFee(50, 200).message).toContain('200');
});
});
// ─── detectAsset ─────────────────────────────────────────────────────────────
describe('detectAsset', () => {
test('recognizes native XLM', () => {
expect(detectAsset({ asset_type: 'native' })).toEqual({
assetCode: 'XLM',
assetType: 'native',
assetIssuer: null,
});
});
test('recognizes USDC', () => {
expect(detectAsset({ asset_type: 'credit_alphanum4', asset_code: 'USDC', asset_issuer: 'GISSUER' })).toEqual({
assetCode: 'USDC',
assetType: 'credit_alphanum4',
assetIssuer: 'GISSUER',
});
});
test('returns null for unsupported asset', () => {
expect(detectAsset({ asset_type: 'credit_alphanum4', asset_code: 'SHIB', asset_issuer: 'GRANDOM' })).toBeNull();
});
test('returns null when asset type does not match', () => {
// XLM code but wrong type
expect(detectAsset({ asset_type: 'credit_alphanum4', asset_code: 'XLM', asset_issuer: 'GISSUER' })).toBeNull();
});
});
// ─── normalizeAmount ──────────────────────────────────────────────────────────
describe('normalizeAmount', () => {
test('rounds to 7 decimal places', () => {
expect(normalizeAmount('100.123456789')).toBe(100.1234568);
});
test('handles whole numbers', () => {
expect(normalizeAmount('200')).toBe(200.0);
});
test('handles smallest XLM unit', () => {
expect(normalizeAmount('0.0000001')).toBe(0.0000001);
});
});
// ─── extractValidPayment ──────────────────────────────────────────────────────
describe('extractValidPayment', () => {
const validOps = async () => ({
records: [{ type: 'payment', to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B', amount: '100.0', asset_type: 'native' }],
});
test('returns payOp, memo, asset for a valid transaction', async () => {
const tx = { successful: true, memo: 'STU001', operations: validOps };
const result = await extractValidPayment(tx, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B');
expect(result).not.toBeNull();
expect(result.memo).toBe('STU001');
expect(result.asset.assetCode).toBe('XLM');
});
test('returns null for a failed transaction', async () => {
const tx = { successful: false, memo: 'STU001', operations: validOps };
expect(await extractValidPayment(tx, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).toBeNull();
});
test('returns null when memo is missing', async () => {
const tx = { successful: true, memo: undefined, operations: validOps };
expect(await extractValidPayment(tx, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).toBeNull();
});
test('returns null when memo is empty string', async () => {
const tx = { successful: true, memo: ' ', operations: validOps };
expect(await extractValidPayment(tx, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).toBeNull();
});
test('returns null when no payment op to school wallet', async () => {
const tx = {
successful: true,
memo: 'STU001',
operations: async () => ({ records: [{ type: 'payment', to: 'GOTHER', amount: '100.0', asset_type: 'native' }] }),
};
expect(await extractValidPayment(tx, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).toBeNull();
});
test('returns null for unsupported asset', async () => {
const tx = {
successful: true,
memo: 'STU001',
operations: async () => ({
records: [{ type: 'payment', to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B', amount: '100.0', asset_type: 'credit_alphanum4', asset_code: 'SHIB', asset_issuer: 'GRANDOM' }],
}),
};
expect(await extractValidPayment(tx, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).toBeNull();
});
});
// ─── verifyTransaction ────────────────────────────────────────────────────────
describe('verifyTransaction', () => {
beforeEach(() => {
Student.findOne.mockResolvedValue({ studentId: 'STU001', feeAmount: 100 });
});
test('returns payment details with asset info for a valid XLM transaction', async () => {
mockOperations.mockResolvedValue({
records: [{ type: 'payment', to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B', amount: '100.0', asset_type: 'native' }],
});
const result = await verifyTransaction('abc123', 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B');
expect(result).toMatchObject({ hash: 'abc123', memo: 'STU001', amount: 100, assetCode: 'XLM', assetType: 'native' });
expect(result.feeValidation.status).toBe('valid');
});
test('throws INVALID_DESTINATION when no matching payment op', async () => {
mockOperations.mockResolvedValue({ records: [] });
await expect(verifyTransaction('abc123', 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).rejects.toMatchObject({ code: 'INVALID_DESTINATION' });
});
test('throws INVALID_DESTINATION when payment is to a different wallet', async () => {
mockOperations.mockResolvedValue({
records: [{ type: 'payment', to: 'GOTHER999', amount: '100.0', asset_type: 'native' }],
});
await expect(verifyTransaction('abc123', 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).rejects.toMatchObject({ code: 'INVALID_DESTINATION' });
});
test('throws UNSUPPORTED_ASSET for unsupported asset', async () => {
mockOperations.mockResolvedValue({
records: [{ type: 'payment', to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B', amount: '100.0', asset_type: 'credit_alphanum4', asset_code: 'SHIB', asset_issuer: 'GRANDOM' }],
});
await expect(verifyTransaction('abc123', 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B')).rejects.toMatchObject({ code: 'UNSUPPORTED_ASSET' });
});
test('feeValidation status is unknown when student not found', async () => {
Student.findOne.mockResolvedValue(null);
mockOperations.mockResolvedValue({
records: [{ type: 'payment', to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B', amount: '100.0', asset_type: 'native' }],
});
const result = await verifyTransaction('abc123', 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B');
expect(result.feeValidation.status).toBe('unknown');
});
});
// ─── parseIncomingTransaction ─────────────────────────────────────────────────
describe('parseIncomingTransaction', () => {
test('correctly extracts memo and amount from payment op', async () => {
const txHash = 'abc123';
mockOperations.mockResolvedValue({
records: [
{ type: 'payment', from: 'GFROM', to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B', amount: '150.0', asset_type: 'native' },
{ type: 'payment', from: 'GFROM', to: 'GOTHER', amount: '50.0', asset_type: 'native' },
],
});
const parsed = await parseIncomingTransaction(txHash, 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B');
expect(parsed.memo).toBe('STU001');
expect(parsed.payments).toHaveLength(1);
expect(parsed.payments[0]).toMatchObject({
from: 'GFROM',
to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B',
amount: 150.0,
assetCode: 'XLM',
assetType: 'native',
});
});
});
// ─── syncPayments ─────────────────────────────────────────────────────────────
// Shared mock transaction factory for sync tests
function makeSyncTx(amount, memo = 'STU001') {
return {
hash: `tx-${amount}`,
successful: true,
memo,
created_at: new Date().toISOString(),
ledger_attr: 90, // below CONFIRMATION_THRESHOLD of 2 from sequence 100 → confirmed
operations: jest.fn().mockResolvedValue({
records: [{
type: 'payment',
to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B',
from: 'GSENDER',
amount: String(amount),
asset_type: 'native',
}],
}),
};
}
const stellarConfig = require('../backend/src/config/stellarConfig');
describe('syncPaymentsForSchool', () => {
const school = { schoolId: 'SCH001', stellarAddress: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B' };
beforeEach(() => {
jest.clearAllMocks();
Payment.findOne.mockResolvedValue(null); // tx not yet recorded
Payment.exists.mockResolvedValue(false);
});
test('resolves without error when no transactions exist', async () => {
await expect(syncPaymentsForSchool(school)).resolves.toBeUndefined();
});
test('skips transaction with unmatched memo (no matching student)', async () => {
const school = { schoolId: 'SCH001', stellarAddress: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B' };
// Transaction with memo that doesn't match any student
const unmatchedTx = makeSyncTx(100, 'UNKNOWN_STUDENT_999');
// Override stellarConfig mock to return our unmatched transaction
const stellarConfig = require('../backend/src/config/stellarConfig');
const origTransactions = stellarConfig.server.transactions;
stellarConfig.server.transactions = () => ({
forAccount: () => ({
order: () => ({
limit: () => ({
call: async () => ({
records: [unmatchedTx],
next: async () => ({ records: [] })
})
})
}),
}),
});
// Mock PaymentIntent to return null (no matching intent for this memo)
const PaymentIntent = require('../backend/src/models/paymentIntentModel');
PaymentIntent.findOne.mockResolvedValue(null);
// Track if Payment.create was called
const createSpy = Payment.create;
// Track if Student.findOneAndUpdate was called
const studentUpdateSpy = Student.findOneAndUpdate;
await syncPaymentsForSchool(school);
// Verify no payment was created
expect(createSpy).not.toHaveBeenCalled();
// Verify no student was updated
expect(studentUpdateSpy).not.toHaveBeenCalled();
// Restore
stellarConfig.server.transactions = origTransactions;
});
test('skips transaction with no memo field', async () => {
const school = { schoolId: 'SCH001', stellarAddress: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B' };
// Transaction with no memo
const noMemoTx = {
hash: 'tx-no-memo',
successful: true,
memo: undefined, // No memo field
created_at: new Date().toISOString(),
ledger_attr: 90,
operations: jest.fn().mockResolvedValue({
records: [{
type: 'payment',
to: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B',
from: 'GSENDER',
amount: '100.0',
asset_type: 'native',
}],
}),
};
// Override stellarConfig mock to return transaction without memo
const stellarConfig = require('../backend/src/config/stellarConfig');
const origTransactions = stellarConfig.server.transactions;
stellarConfig.server.transactions = () => ({
forAccount: () => ({
order: () => ({
limit: () => ({
call: async () => ({
records: [noMemoTx],
next: async () => ({ records: [] })
})
})
}),
}),
});
// Track if Payment.create was called
const createSpy = Payment.create;
// Track if Student.findOneAndUpdate was called
const studentUpdateSpy = Student.findOneAndUpdate;
// Should not throw error
await expect(syncPaymentsForSchool(school)).resolves.toBeDefined();
// Verify no payment was created
expect(createSpy).not.toHaveBeenCalled();
// Verify no student was updated
expect(studentUpdateSpy).not.toHaveBeenCalled();
// Restore
stellarConfig.server.transactions = origTransactions;
});
test('skips transaction with empty string memo', async () => {
const school = { schoolId: 'SCH001', stellarAddress: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B' };
// Transaction with empty memo
const emptyMemoTx = makeSyncTx(100, ' '); // Whitespace-only memo
// Override stellarConfig mock
const stellarConfig = require('../backend/src/config/stellarConfig');
const origTransactions = stellarConfig.server.transactions;
stellarConfig.server.transactions = () => ({
forAccount: () => ({
order: () => ({
limit: () => ({
call: async () => ({
records: [emptyMemoTx],
next: async () => ({ records: [] })
})
})
}),
}),
});
// Track calls
const createSpy = Payment.create;
const studentUpdateSpy = Student.findOneAndUpdate;
await syncPaymentsForSchool(school);
// Verify no payment was created
expect(createSpy).not.toHaveBeenCalled();
// Verify no student was updated
expect(studentUpdateSpy).not.toHaveBeenCalled();
// Restore
stellarConfig.server.transactions = origTransactions;
});
test('stops pagination when a known txHash is encountered', async () => {
const school = { schoolId: 'SCH001', stellarAddress: 'GCICZOP346CKADPWOZ6JAQ7OCGH44UELNS3GSDXFOTSZRW6OYZZ6KSY7B' };
// 200 new records on page 1 (full page → triggers next())
const page1Records = Array.from({ length: 200 }, (_, i) => ({
hash: `tx_new_${i}`, successful: false, memo: null, created_at: new Date().toISOString(),
}));
// Page 2 has one already-known record → pagination stops
const page2Records = [{ hash: 'known_tx', successful: false, memo: null, created_at: new Date().toISOString() }];
const nextFn = jest.fn().mockResolvedValue({ records: page2Records, next: jest.fn() });
// Override the stellarConfig mock for this test only
const stellarConfig = require('../backend/src/config/stellarConfig');
const origTransactions = stellarConfig.server.transactions;
stellarConfig.server.transactions = () => ({
forAccount: () => ({
order: () => ({ limit: () => ({ call: async () => ({ records: page1Records, next: nextFn }) }) }),
}),
});
// All page1 records are new (null), then the page2 record is known
Payment.findOne
.mockResolvedValue(null)
.mockResolvedValueOnce({ hash: 'known_tx' }); // called for page2[0] → stop
// Reset so page1 records all return null first
Payment.findOne.mockReset();
Payment.findOne.mockResolvedValue(null); // default: all unknown
// Override for the first call on page2 (201st call overall)
const calls = [];
Payment.findOne.mockImplementation(({ txHash }) => {
calls.push(txHash);
if (txHash === 'known_tx') return Promise.resolve({ hash: 'known_tx' });
return Promise.resolve(null);
});
await syncPaymentsForSchool(school);
expect(nextFn).toHaveBeenCalledTimes(1);
// Restore
stellarConfig.server.transactions = origTransactions;
Payment.findOne.mockReset();
Payment.findOne.mockResolvedValue(null);
});
});