forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenTransfer.test.js
More file actions
408 lines (340 loc) · 16.3 KB
/
Copy pathtokenTransfer.test.js
File metadata and controls
408 lines (340 loc) · 16.3 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
'use strict';
/**
* Unit tests for transactionService.js — token transfer business logic.
* Closes #939
*
* All Stellar SDK calls and DB calls are mocked — no network, no DB.
* Target: 90%+ line coverage on transactionService.
*/
// ── Mock dependencies ─────────────────────────────────────────────────────
jest.mock('../../../blockchain/stellarService', () => ({
server: {
transactions: jest.fn(),
payments: jest.fn(),
},
NOVA: { code: 'NOVA', issuer: 'GISSUER' },
isValidStellarAddress: jest.fn((addr) => /^G[A-Z0-9]{55}$/.test(addr)),
}));
jest.mock('../../db/transactionRepository', () => ({
recordTransaction: jest.fn(),
getTransactionByHash: jest.fn(),
getTransactionsByUser: jest.fn(),
getTransactionHistory: jest.fn(),
processRefund: jest.fn(),
reconcileTransactions: jest.fn(),
getTransactionReport: jest.fn(),
}));
jest.mock('../../db/userRepository', () => ({
getUserById: jest.fn(),
}));
jest.mock('../../db/index', () => ({
query: jest.fn(),
}));
const VALID_WALLET = 'GABC1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGH';
const VALID_WALLET_2 = 'GXYZ1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890ABCDEFGH';
const {
recordTransaction,
getWalletHistory,
getUserHistory,
getMerchantHistory,
refundTransaction,
reconcileMerchantTransactions,
getMerchantTransactionReport,
TRANSACTION_TYPES,
REPORTABLE_STATUSES,
} = require('../../services/transactionService');
const stellarService = require('../../../blockchain/stellarService');
const txRepo = require('../../db/transactionRepository');
const userRepo = require('../../db/userRepository');
const db = require('../../db/index');
// ── Helpers ───────────────────────────────────────────────────────────────
function mockStellarTx(ledger = 12345) {
stellarService.server.transactions.mockReturnValue({
transaction: jest.fn().mockReturnValue({
call: jest.fn().mockResolvedValue({ ledger_attr: ledger }),
}),
});
}
// ── recordTransaction ─────────────────────────────────────────────────────
describe('recordTransaction', () => {
beforeEach(() => {
jest.clearAllMocks();
mockStellarTx();
txRepo.recordTransaction.mockResolvedValue({ id: 1, tx_hash: 'abc123' });
});
it('successful transfer — calls Stellar and inserts DB record', async () => {
const result = await recordTransaction({
txHash: 'abc123',
txType: 'transfer',
amount: '10.5',
fromWallet: VALID_WALLET,
toWallet: VALID_WALLET_2,
});
expect(result).toMatchObject({ id: 1, tx_hash: 'abc123' });
expect(txRepo.recordTransaction).toHaveBeenCalledWith(
expect.objectContaining({ txHash: 'abc123', amount: '10.5', stellarLedger: 12345 })
);
});
it('throws 400 when txHash is missing', async () => {
await expect(recordTransaction({ txType: 'transfer', amount: '1' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when amount is zero', async () => {
await expect(recordTransaction({ txHash: 'abc', txType: 'transfer', amount: '0' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when amount is negative', async () => {
await expect(recordTransaction({ txHash: 'abc', txType: 'transfer', amount: '-5' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when amount has too many decimal places', async () => {
await expect(recordTransaction({ txHash: 'abc', txType: 'transfer', amount: '1.12345678' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when amount is missing', async () => {
await expect(recordTransaction({ txHash: 'abc', txType: 'transfer' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 for invalid fromWallet address', async () => {
await expect(recordTransaction({
txHash: 'abc', txType: 'transfer', amount: '1', fromWallet: 'INVALID',
})).rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 for invalid toWallet address', async () => {
await expect(recordTransaction({
txHash: 'abc', txType: 'transfer', amount: '1', toWallet: 'INVALID',
})).rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 for invalid txType', async () => {
await expect(recordTransaction({ txHash: 'abc', txType: 'unknown', amount: '1' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 for refund without referenceTxHash', async () => {
await expect(recordTransaction({ txHash: 'abc', txType: 'refund', amount: '1' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('accepts refund with referenceTxHash', async () => {
await expect(recordTransaction({
txHash: 'abc', txType: 'refund', amount: '1', referenceTxHash: 'orig-hash',
})).resolves.toBeDefined();
});
it('throws 400 when Stellar transaction not found', async () => {
stellarService.server.transactions.mockReturnValue({
transaction: jest.fn().mockReturnValue({
call: jest.fn().mockRejectedValue(new Error('not found')),
}),
});
await expect(recordTransaction({ txHash: 'missing', txType: 'transfer', amount: '1' }))
.rejects.toMatchObject({ status: 400, code: 'tx_not_found' });
});
it('throws 400 for invalid metadata (array)', async () => {
await expect(recordTransaction({
txHash: 'abc', txType: 'transfer', amount: '1', metadata: [1, 2],
})).rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('accepts valid metadata object', async () => {
await expect(recordTransaction({
txHash: 'abc', txType: 'transfer', amount: '1', metadata: { note: 'test' },
})).resolves.toBeDefined();
});
it('defaults status to "completed" when not provided', async () => {
await recordTransaction({ txHash: 'abc', txType: 'transfer', amount: '1' });
expect(txRepo.recordTransaction).toHaveBeenCalledWith(
expect.objectContaining({ status: 'completed' })
);
});
it('accepts all valid transaction types', async () => {
for (const type of TRANSACTION_TYPES) {
jest.clearAllMocks();
mockStellarTx();
txRepo.recordTransaction.mockResolvedValue({ id: 1 });
const payload = { txHash: 'abc', txType: type, amount: '1' };
if (type === 'refund') payload.referenceTxHash = 'orig';
await expect(recordTransaction(payload)).resolves.toBeDefined();
}
});
});
// ── getWalletHistory ──────────────────────────────────────────────────────
describe('getWalletHistory', () => {
beforeEach(() => jest.clearAllMocks());
it('throws 400 for invalid wallet address', async () => {
await expect(getWalletHistory('INVALID'))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when wallet address is missing', async () => {
await expect(getWalletHistory(undefined))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('returns Horizon data on success', async () => {
const mockRecords = [{ type: 'payment', asset_code: 'NOVA', asset_issuer: 'GISSUER', amount: '5' }];
stellarService.server.payments.mockReturnValue({
forAccount: jest.fn().mockReturnValue({
order: jest.fn().mockReturnValue({
limit: jest.fn().mockReturnValue({
call: jest.fn().mockResolvedValue({ records: mockRecords, next: jest.fn().mockResolvedValue({ records: [] }) }),
}),
}),
}),
});
const result = await getWalletHistory(VALID_WALLET);
expect(result.source).toBe('horizon');
expect(result.data).toHaveLength(1);
});
it('falls back to DB when Horizon fails', async () => {
stellarService.server.payments.mockReturnValue({
forAccount: jest.fn().mockReturnValue({
order: jest.fn().mockReturnValue({
limit: jest.fn().mockReturnValue({
call: jest.fn().mockRejectedValue(new Error('Horizon down')),
}),
}),
}),
});
db.query.mockResolvedValue({ rows: [{ id: 1 }] });
const result = await getWalletHistory(VALID_WALLET);
expect(result.source).toBe('database');
expect(result.data).toHaveLength(1);
});
});
// ── getUserHistory ────────────────────────────────────────────────────────
describe('getUserHistory', () => {
beforeEach(() => jest.clearAllMocks());
it('throws 400 when userId is missing', async () => {
await expect(getUserHistory({}))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when userId is not a positive integer', async () => {
await expect(getUserHistory({ userId: '-1' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 404 when user does not exist', async () => {
userRepo.getUserById.mockResolvedValue(null);
await expect(getUserHistory({ userId: '999' }))
.rejects.toMatchObject({ status: 404, code: 'not_found' });
});
it('returns transactions for valid user', async () => {
userRepo.getUserById.mockResolvedValue({ id: 1 });
txRepo.getTransactionsByUser.mockResolvedValue({ data: [], total: 0, page: 1, limit: 20 });
const result = await getUserHistory({ userId: '1' });
expect(result).toMatchObject({ total: 0 });
});
it('throws 400 for invalid type filter', async () => {
userRepo.getUserById.mockResolvedValue({ id: 1 });
await expect(getUserHistory({ userId: '1', type: 'invalid' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when limit exceeds 100', async () => {
userRepo.getUserById.mockResolvedValue({ id: 1 });
await expect(getUserHistory({ userId: '1', limit: '200' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when startDate is after endDate', async () => {
userRepo.getUserById.mockResolvedValue({ id: 1 });
await expect(getUserHistory({ userId: '1', startDate: '2025-12-01', endDate: '2025-01-01' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
});
// ── refundTransaction ─────────────────────────────────────────────────────
describe('refundTransaction', () => {
const merchantId = 1;
const existingTx = {
id: 10,
tx_hash: 'orig-hash',
merchant_id: merchantId,
status: 'completed',
amount: '5',
};
beforeEach(() => {
jest.clearAllMocks();
mockStellarTx();
txRepo.getTransactionByHash.mockResolvedValue(existingTx);
txRepo.processRefund.mockResolvedValue({ originalTransaction: existingTx, refundTransaction: { id: 11 } });
});
it('successful refund returns original and refund transactions', async () => {
const result = await refundTransaction(merchantId, {
txHash: 'orig-hash',
refundTxHash: 'refund-hash',
reason: 'Customer request',
});
expect(result).toMatchObject({ originalTransaction: existingTx });
});
it('throws 400 when txHash is missing', async () => {
await expect(refundTransaction(merchantId, { refundTxHash: 'r', reason: 'x' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when refundTxHash is missing', async () => {
await expect(refundTransaction(merchantId, { txHash: 'orig', reason: 'x' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when reason is missing', async () => {
await expect(refundTransaction(merchantId, { txHash: 'orig', refundTxHash: 'r' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 400 when txHash equals refundTxHash', async () => {
await expect(refundTransaction(merchantId, { txHash: 'same', refundTxHash: 'same', reason: 'x' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
it('throws 404 when original transaction not found', async () => {
txRepo.getTransactionByHash.mockResolvedValue(null);
await expect(refundTransaction(merchantId, { txHash: 'missing', refundTxHash: 'r', reason: 'x' }))
.rejects.toMatchObject({ status: 404, code: 'not_found' });
});
it('throws 403 when transaction belongs to different merchant', async () => {
txRepo.getTransactionByHash.mockResolvedValue({ ...existingTx, merchant_id: 999 });
await expect(refundTransaction(merchantId, { txHash: 'orig-hash', refundTxHash: 'r', reason: 'x' }))
.rejects.toMatchObject({ status: 403, code: 'forbidden' });
});
it('throws 409 when transaction status is not refundable', async () => {
txRepo.getTransactionByHash.mockResolvedValue({ ...existingTx, status: 'pending' });
await expect(refundTransaction(merchantId, { txHash: 'orig-hash', refundTxHash: 'r', reason: 'x' }))
.rejects.toMatchObject({ status: 409, code: 'invalid_transaction_status' });
});
it('allows refund of reconciled transactions', async () => {
txRepo.getTransactionByHash.mockResolvedValue({ ...existingTx, status: 'reconciled' });
await expect(refundTransaction(merchantId, { txHash: 'orig-hash', refundTxHash: 'r', reason: 'x' }))
.resolves.toBeDefined();
});
});
// ── reconcileMerchantTransactions ─────────────────────────────────────────
describe('reconcileMerchantTransactions', () => {
beforeEach(() => jest.clearAllMocks());
it('calls reconcileTransactions with valid params', async () => {
txRepo.reconcileTransactions.mockResolvedValue({ count: 3, totalAmount: '15', transactions: [] });
const result = await reconcileMerchantTransactions(1, {});
expect(result.count).toBe(3);
});
it('throws 400 for invalid date range', async () => {
await expect(reconcileMerchantTransactions(1, { startDate: '2025-12-01', endDate: '2025-01-01' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
});
// ── getMerchantHistory ────────────────────────────────────────────────────
describe('getMerchantHistory', () => {
beforeEach(() => jest.clearAllMocks());
it('returns paginated history', async () => {
txRepo.getTransactionHistory.mockResolvedValue({ data: [], total: 0, page: 1, limit: 20 });
const result = await getMerchantHistory(1, {});
expect(result).toMatchObject({ total: 0 });
});
it('throws 400 for invalid status filter', async () => {
await expect(getMerchantHistory(1, { status: 'invalid' }))
.rejects.toMatchObject({ status: 400, code: 'validation_error' });
});
});
// ── getMerchantTransactionReport ──────────────────────────────────────────
describe('getMerchantTransactionReport', () => {
it('returns report data', async () => {
txRepo.getTransactionReport.mockResolvedValue({ total: 100, count: 5 });
const result = await getMerchantTransactionReport(1, {});
expect(result).toMatchObject({ total: 100 });
});
});
// ── Constants ─────────────────────────────────────────────────────────────
describe('module constants', () => {
it('TRANSACTION_TYPES includes expected types', () => {
expect(TRANSACTION_TYPES).toEqual(expect.arrayContaining(['distribution', 'redemption', 'transfer', 'refund']));
});
it('REPORTABLE_STATUSES includes expected statuses', () => {
expect(REPORTABLE_STATUSES).toEqual(expect.arrayContaining(['pending', 'completed', 'failed', 'refunded']));
});
});