forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstellarTransactionService.test.js
More file actions
901 lines (759 loc) · 29.9 KB
/
Copy pathstellarTransactionService.test.js
File metadata and controls
901 lines (759 loc) · 29.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
/**
* Tests for the Stellar Transaction Submission Service.
*
* Covers:
* - stellarTransactionService.submit() (build, sign, submit, fee-bump retry, DB storage)
* - stellarTransactionService.submitFeeBump() (explicit fee-bump from XDR)
* - stellarTransactionService.parseTransactionResult()
* - stellarTransactionService.extractResultCodes()
* - stellarTransactionService.getSequenceNumber()
* - Route: POST /api/transactions/submit
* - Route: POST /api/transactions/fee-bump
* - Route: GET /api/transactions/sequence/:publicKey
*/
// ---------------------------------------------------------------------------
// Module mocks
// ---------------------------------------------------------------------------
jest.mock('../../blockchain/stellarService', () => ({
server: {
loadAccount: jest.fn(),
submitTransaction: jest.fn(),
transactions: jest.fn(() => ({
transaction: jest.fn(() => ({
call: jest.fn(),
})),
})),
},
NOVA: { code: 'NOVA', issuer: 'GTESTISSUER' },
isValidStellarAddress: jest.fn((addr) => {
if (typeof addr !== 'string') return false;
try {
const { StrKey } = require('stellar-sdk');
return StrKey.isValidEd25519PublicKey(addr);
} catch {
return false;
}
}),
}));
jest.mock('../db/transactionRepository', () => ({
recordTransaction: jest.fn(),
}));
jest.mock('../lib/redis', () => ({
client: { isOpen: true, get: jest.fn(), set: jest.fn(), del: jest.fn() },
connectRedis: jest.fn(),
}));
jest.mock('../middleware/authenticateUser', () => ({
authenticateUser: (req, res, next) => {
req.user = { id: 1, role: 'user' };
next();
},
requireAdmin: (req, res, next) => next(),
}));
jest.mock('../middleware/rateLimiter', () => ({
slidingAuth: (req, res, next) => next(),
slidingGlobal: (req, res, next) => next(),
}));
const express = require('express');
const request = require('supertest');
const {
Keypair,
Account,
Operation,
Asset,
TransactionBuilder,
Networks,
BASE_FEE,
} = require('stellar-sdk');
const { server } = require('../../blockchain/stellarService');
const { recordTransaction } = require('../db/transactionRepository');
const stellarTxService = require('../services/stellarTransactionService');
// ---------------------------------------------------------------------------
// Env setup
// ---------------------------------------------------------------------------
process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';
process.env.STELLAR_NETWORK = 'testnet';
// ---------------------------------------------------------------------------
// Test app
// ---------------------------------------------------------------------------
function buildApp() {
const app = express();
app.use(express.json());
app.use('/api/transactions', require('../routes/stellarTransaction'));
app.use((err, _req, res, _next) => {
res.status(err.status || 500).json({
success: false,
error: err.code || 'internal_error',
message: err.message || 'An unexpected error occurred',
});
});
return app;
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function mockAccount(publicKey, sequence = '12345') {
return new Account(publicKey, sequence);
}
function buildSignedTx(sourceKeypair, destination, amount = '10') {
const account = mockAccount(sourceKeypair.publicKey());
const tx = new TransactionBuilder(account, {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(
Operation.payment({
destination,
asset: Asset.native(),
amount,
}),
)
.setTimeout(180)
.build();
tx.sign(sourceKeypair);
return tx;
}
// ---------------------------------------------------------------------------
// Tests: stellarTransactionService internals
// ---------------------------------------------------------------------------
describe('stellarTransactionService — parseTransactionResult', () => {
it('parses a successful result', () => {
const result = stellarTxService.parseTransactionResult({
hash: 'abc123',
ledger: 42,
successful: true,
result_xdr: 'AAAAAA==',
});
expect(result.txHash).toBe('abc123');
expect(result.ledger).toBe(42);
expect(result.status).toBe('completed');
expect(result.successful).toBe(true);
expect(result.resultXdr).toBe('AAAAAA==');
});
it('parses a failed result', () => {
const result = stellarTxService.parseTransactionResult({
hash: 'def456',
ledger: 99,
successful: false,
result_xdr: 'BBBBBB==',
});
expect(result.status).toBe('failed');
expect(result.successful).toBe(false);
});
});
describe('stellarTransactionService — extractResultCodes', () => {
it('extracts result codes from Horizon error', () => {
const err = {
response: {
data: {
extras: {
result_codes: {
transaction: ['tx_bad_seq'],
operations: ['op_no_source_account'],
},
},
},
},
};
const codes = stellarTxService.extractResultCodes(err);
expect(codes).toContain('tx_bad_seq');
expect(codes).toContain('op_no_source_account');
});
it('returns empty array for errors without extras', () => {
expect(stellarTxService.extractResultCodes(new Error('network error'))).toEqual([]);
});
});
describe('stellarTransactionService — getSequenceNumber', () => {
beforeEach(() => jest.clearAllMocks());
it('fetches sequence from Horizon', async () => {
const kp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(kp.publicKey(), '98765'));
const seq = await stellarTxService.getSequenceNumber(kp.publicKey());
expect(seq).toBe('98765');
expect(server.loadAccount).toHaveBeenCalledWith(kp.publicKey());
});
});
// ---------------------------------------------------------------------------
// Tests: stellarTransactionService.submit()
// ---------------------------------------------------------------------------
describe('stellarTransactionService — submit', () => {
beforeEach(() => jest.clearAllMocks());
it('builds, signs, and submits a transaction with fresh sequence number', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey()));
server.submitTransaction.mockResolvedValue({
hash: 'txhash123',
ledger: 100,
result_xdr: 'AAAAAA==',
});
recordTransaction.mockResolvedValue({ id: 1 });
const result = await stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: destKp.publicKey(),
asset: Asset.native(),
amount: '10',
}),
],
signers: [sourceKp],
options: { txType: 'transfer', amount: '10' },
});
expect(result.txHash).toBe('txhash123');
expect(result.ledger).toBe(100);
expect(result.status).toBe('submitted');
// Sequence number fetched fresh
expect(server.loadAccount).toHaveBeenCalledWith(sourceKp.publicKey());
// Transaction was submitted
expect(server.submitTransaction).toHaveBeenCalledTimes(1);
// Result stored in DB
expect(recordTransaction).toHaveBeenCalledWith(
expect.objectContaining({
txHash: 'txhash123',
txType: 'transfer',
amount: '10',
stellarLedger: 100,
}),
);
});
it('throws on missing sourceAddress', async () => {
await expect(
stellarTxService.submit({
sourceAddress: '',
operations: [Operation.payment({ destination: 'G', asset: Asset.native(), amount: '1' })],
signers: [Keypair.random()],
}),
).rejects.toThrow('sourceAddress is required');
});
it('throws on missing operations', async () => {
await expect(
stellarTxService.submit({
sourceAddress: Keypair.random().publicKey(),
operations: [],
signers: [Keypair.random()],
}),
).rejects.toThrow('At least one operation is required');
});
it('throws on missing signers', async () => {
await expect(
stellarTxService.submit({
sourceAddress: Keypair.random().publicKey(),
operations: [Operation.payment({ destination: 'G', asset: Asset.native(), amount: '1' })],
signers: [],
}),
).rejects.toThrow('At least one signer is required');
});
it('refreshes sequence and retries once when transaction is stuck (tx_bad_seq)', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
server.loadAccount
.mockResolvedValueOnce(mockAccount(sourceKp.publicKey(), '111'))
.mockResolvedValueOnce(mockAccount(sourceKp.publicKey(), '222'));
const stuckError = new Error('tx_bad_seq');
stuckError.response = {
data: {
extras: {
result_codes: { transaction: ['tx_bad_seq'] },
},
},
};
server.submitTransaction
.mockRejectedValueOnce(stuckError)
.mockResolvedValueOnce({
hash: 'retryhash',
ledger: 101,
result_xdr: 'CCCCCC==',
});
recordTransaction.mockResolvedValue({ id: 2 });
const result = await stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: destKp.publicKey(),
asset: Asset.native(),
amount: '5',
}),
],
signers: [sourceKp],
options: {},
});
expect(result.txHash).toBe('retryhash');
// One for initial submit attempt, one for retry submission
expect(server.submitTransaction).toHaveBeenCalledTimes(2);
// Sequence refreshed via loadAccount on tx_bad_seq
expect(server.loadAccount).toHaveBeenCalledTimes(2);
});
it('retries Horizon timeout errors up to 3 times with exponential backoff', async () => {
jest.useFakeTimers();
const sourceKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey(), '111'));
const timeoutErr1 = new Error('timeout');
const timeoutErr2 = new Error('timeout');
const timeoutErr3 = new Error('timeout');
server.submitTransaction
.mockRejectedValueOnce(timeoutErr1)
.mockRejectedValueOnce(timeoutErr2)
.mockRejectedValueOnce(timeoutErr3);
recordTransaction.mockResolvedValue({ id: 2 });
const p = stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: Keypair.random().publicKey(),
asset: Asset.native(),
amount: '5',
}),
],
signers: [sourceKp],
options: {},
});
// Run pending timers (backoffs: 0ms, 500ms, 1000ms)
await Promise.resolve();
jest.advanceTimersByTime(2000);
await expect(p).rejects.toThrow('Horizon error');
expect(server.submitTransaction).toHaveBeenCalledTimes(3);
jest.useRealTimers();
});
it('maps Horizon insufficient_balance to a 400 response code', async () => {
const sourceKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey(), '111'));
const err = new Error('insufficient_balance');
err.response = {
data: {
extras: {
result_codes: { transaction: ['insufficient_balance'] },
},
},
};
server.submitTransaction.mockRejectedValue(err);
await expect(
stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: Keypair.random().publicKey(),
asset: Asset.native(),
amount: '5',
}),
],
signers: [sourceKp],
options: {},
}),
).rejects.toMatchObject({ status: 400 });
});
it('maps all other Horizon errors to 503 with original code', async () => {
const sourceKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey(), '111'));
const err = new Error('some_horizon_failure');
err.response = {
data: {
extras: {
result_codes: { transaction: ['tx_internal_error'] },
},
},
};
server.submitTransaction.mockRejectedValue(err);
await expect(
stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: Keypair.random().publicKey(),
asset: Asset.native(),
amount: '5',
}),
],
signers: [sourceKp],
options: {},
}),
).rejects.toMatchObject({ status: 503, code: 'tx_internal_error' });
});
it('does not retry fee-bump for non-stuck errors', async () => {
const sourceKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey()));
const otherError = new Error('op_bad_auth');
otherError.response = {
data: {
extras: {
result_codes: { transaction: ['op_bad_auth'] },
},
},
};
server.submitTransaction.mockRejectedValue(otherError);
await expect(
stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: Keypair.random().publicKey(),
asset: Asset.native(),
amount: '1',
}),
],
signers: [sourceKp],
}),
).rejects.toThrow('Transaction submission failed');
// Only one submission attempt (no retry)
expect(server.submitTransaction).toHaveBeenCalledTimes(1);
});
it('stores result in DB even with default status mapping', async () => {
const sourceKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey()));
server.submitTransaction.mockResolvedValue({
hash: 'abc',
ledger: 50,
result_xdr: null,
});
recordTransaction.mockResolvedValue({ id: 3 });
await stellarTxService.submit({
sourceAddress: sourceKp.publicKey(),
operations: [
Operation.payment({
destination: Keypair.random().publicKey(),
asset: Asset.native(),
amount: '1',
}),
],
signers: [sourceKp],
});
expect(recordTransaction).toHaveBeenCalledWith(
expect.objectContaining({ status: 'completed' }),
);
});
});
// ---------------------------------------------------------------------------
// Tests: stellarTransactionService.submitFeeBump()
// ---------------------------------------------------------------------------
describe('stellarTransactionService — submitFeeBump (explicit)', () => {
beforeEach(() => jest.clearAllMocks());
it('throws on missing innerTxXDR', async () => {
await expect(
stellarTxService.submitFeeBump({ innerTxXDR: '', feeSourceSecret: 'S...' }),
).rejects.toThrow('innerTxXDR is required');
});
it('throws on missing feeSourceSecret', async () => {
await expect(
stellarTxService.submitFeeBump({ innerTxXDR: 'abc', feeSourceSecret: '' }),
).rejects.toThrow('feeSourceSecret is required');
});
it('builds and submits a fee-bump transaction', async () => {
const sourceKp = Keypair.random();
const feeSourceKp = Keypair.random();
const innerTx = buildSignedTx(sourceKp, Keypair.random().publicKey());
server.submitTransaction.mockResolvedValue({
hash: 'bump123',
ledger: 200,
result_xdr: 'DDDDDD==',
});
const result = await stellarTxService.submitFeeBump({
innerTxXDR: innerTx.toXDR(),
feeSourceSecret: feeSourceKp.secret(),
});
expect(result.txHash).toBe('bump123');
expect(result.ledger).toBe(200);
expect(server.submitTransaction).toHaveBeenCalledTimes(1);
});
});
// ---------------------------------------------------------------------------
// Tests: Routes
// ---------------------------------------------------------------------------
describe('Route: POST /api/transactions/submit', () => {
const app = buildApp();
beforeEach(() => jest.clearAllMocks());
it('returns 400 when sourceAddress is missing', async () => {
const res = await request(app)
.post('/api/transactions/submit')
.send({ signerSecret: 'S...', operations: [{ type: 'payment' }] });
expect(res.status).toBe(400);
expect(res.body.error).toBe('validation_error');
});
it('returns 400 when signerSecret is missing', async () => {
const kp = Keypair.random();
const res = await request(app)
.post('/api/transactions/submit')
.send({ sourceAddress: kp.publicKey(), operations: [{ type: 'payment' }] });
expect(res.status).toBe(400);
expect(res.body.error).toBe('validation_error');
});
it('returns 400 when operations is empty', async () => {
const kp = Keypair.random();
const res = await request(app)
.post('/api/transactions/submit')
.send({ sourceAddress: kp.publicKey(), signerSecret: kp.secret(), operations: [] });
expect(res.status).toBe(400);
expect(res.body.error).toBe('validation_error');
});
it('returns 400 for unsupported operation type', async () => {
const kp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(kp.publicKey()));
const res = await request(app)
.post('/api/transactions/submit')
.send({
sourceAddress: kp.publicKey(),
signerSecret: kp.secret(),
operations: [{ type: 'bogus_op' }],
});
expect(res.status).toBe(400);
expect(res.body.message).toContain('Unsupported operation type');
});
it('successfully submits a payment transaction', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(sourceKp.publicKey()));
server.submitTransaction.mockResolvedValue({
hash: 'routetx123',
ledger: 300,
result_xdr: 'EEEEEE==',
});
recordTransaction.mockResolvedValue({ id: 10 });
const res = await request(app)
.post('/api/transactions/submit')
.send({
sourceAddress: sourceKp.publicKey(),
signerSecret: sourceKp.secret(),
operations: [
{
type: 'payment',
destination: destKp.publicKey(),
assetCode: 'XLM',
amount: '25',
},
],
txType: 'distribution',
amount: '25',
});
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.data.txHash).toBe('routetx123');
expect(res.body.data.ledger).toBe(300);
});
});
describe('Route: POST /api/transactions/fee-bump', () => {
const app = buildApp();
beforeEach(() => jest.clearAllMocks());
it('returns 400 when innerTxXDR is missing', async () => {
const res = await request(app)
.post('/api/transactions/fee-bump')
.send({ feeSourceSecret: 'S...' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('validation_error');
});
it('returns 400 when feeSourceSecret is missing', async () => {
const res = await request(app)
.post('/api/transactions/fee-bump')
.send({ innerTxXDR: 'abc' });
expect(res.status).toBe(400);
expect(res.body.error).toBe('validation_error');
});
});
describe('Route: GET /api/transactions/sequence/:publicKey', () => {
const app = buildApp();
beforeEach(() => jest.clearAllMocks());
it('returns the current sequence number', async () => {
const kp = Keypair.random();
server.loadAccount.mockResolvedValue(mockAccount(kp.publicKey(), '55555'));
const res = await request(app)
.get(`/api/transactions/sequence/${kp.publicKey()}`);
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(res.body.data.sequence).toBe('55555');
});
it('returns 404 for non-existent account', async () => {
const kp = Keypair.random();
const err = new Error('Not found');
err.response = { status: 404 };
server.loadAccount.mockRejectedValue(err);
const res = await request(app)
.get(`/api/transactions/sequence/${kp.publicKey()}`);
expect(res.status).toBe(404);
expect(res.body.error).toBe('account_not_found');
});
});
// ---------------------------------------------------------------------------
// Tests: Fee-bump retry logic (acceptance criteria)
//
// These tests use the _deps injection seam on stellarTransactionService to
// mock loadAccount and submitTransaction without relying on vitest module
// interception of CJS require() calls (which doesn't work reliably).
// ---------------------------------------------------------------------------
describe('stellarTransactionService — fee-bump retry logic', () => {
const { Keypair, Account, BASE_FEE } = require('stellar-sdk');
const stellarTxSvc = require('../services/stellarTransactionService');
// Generate a valid fee-source keypair for all fee-bump tests
const feeSourceKp = Keypair.random();
const feeSourceSecret = feeSourceKp.secret();
// Build a minimal Account mock the TransactionBuilder accepts
function makeFakeAccount(publicKey, sequence = '100') {
return new Account(publicKey, sequence);
}
let mockLoadAccount;
let mockSubmitTransaction;
let mockRecordTx;
let savedDeps;
beforeEach(() => {
mockLoadAccount = vi.fn();
mockSubmitTransaction = vi.fn();
mockRecordTx = vi.fn().mockResolvedValue({ id: 1 });
// Save real deps and inject mocks
savedDeps = { server: stellarTxSvc._deps.server, recordTransaction: stellarTxSvc._deps.recordTransaction };
stellarTxSvc._deps.server = {
loadAccount: mockLoadAccount,
submitTransaction: mockSubmitTransaction,
};
stellarTxSvc._deps.recordTransaction = mockRecordTx;
});
afterEach(() => {
// Restore real deps so other test suites are unaffected
stellarTxSvc._deps.server = savedDeps.server;
stellarTxSvc._deps.recordTransaction = savedDeps.recordTransaction;
});
// ── AC-1: tx_bad_seq → sequence refresh → success on fee-bump ────────────
it('AC-1: resolves with correct txHash when tx_bad_seq triggers a fee-bump retry', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
const badSeqError = Object.assign(new Error('tx_bad_seq'), {
response: { data: { extras: { result_codes: { transaction: ['tx_bad_seq'] } } } },
});
// loadAccount calls:
// 1 — initial submit (inside submit())
// 2 — inline tx_bad_seq refresh (inside submitHorizonTransaction)
// 3 — fee-bump attempt 1 (inside submitWithFeeBumpRetry loop)
mockLoadAccount
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '100'))
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '101'))
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '102'));
// submitTransaction calls:
// 1 — initial fails with tx_bad_seq
// 2 — after inline refresh also fails with tx_bad_seq → fee-bump loop
// 3 — fee-bump attempt 1 succeeds
mockSubmitTransaction
.mockRejectedValueOnce(badSeqError)
.mockRejectedValueOnce(badSeqError)
.mockResolvedValueOnce({ hash: 'feebump_success_hash', ledger: 55, result_xdr: 'AAAAAA==' });
const result = await stellarTxSvc.submit({
sourceAddress: sourceKp.publicKey(),
operations: [Operation.payment({ destination: destKp.publicKey(), asset: Asset.native(), amount: '10' })],
signers: [sourceKp],
options: { feeSourceSecret },
});
expect(result.txHash).toBe('feebump_success_hash');
expect(result.status).toBe('submitted');
});
// ── AC-2: MAX_FEE_BUMP_ATTEMPTS exhausted → typed error ─────────────────
it('AC-2: rejects with typed error (code=tx_submission_failed) after MAX_FEE_BUMP_ATTEMPTS consecutive failures', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
const insufficientFeeErr = Object.assign(new Error('tx_insufficient_fee'), {
response: { data: { extras: { result_codes: { transaction: ['tx_insufficient_fee'] } } } },
});
// Every loadAccount and submitTransaction call fails with tx_insufficient_fee
mockLoadAccount.mockResolvedValue(makeFakeAccount(sourceKp.publicKey(), '200'));
mockSubmitTransaction.mockRejectedValue(insufficientFeeErr);
const err = await stellarTxSvc.submit({
sourceAddress: sourceKp.publicKey(),
operations: [Operation.payment({ destination: destKp.publicKey(), asset: Asset.native(), amount: '1' })],
signers: [sourceKp],
options: { feeSourceSecret },
}).catch(e => e);
expect(err).toBeInstanceOf(Error);
expect(err.code).toBe('tx_submission_failed');
expect(err.message).toMatch(/tx_insufficient_fee/);
expect(err.status).toBe(400);
});
// ── AC-3: No sequence number reuse — loadAccount called per attempt ──────
it('AC-3: calls loadAccount before each fee-bump attempt (no stale sequence reuse)', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
const tooLateErr = Object.assign(new Error('tx_too_late'), {
response: { data: { extras: { result_codes: { transaction: ['tx_too_late'] } } } },
});
// 1 initial + 3 fee-bump refreshes = 4 total loadAccount calls
mockLoadAccount
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '300'))
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '301'))
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '302'))
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '303'));
mockSubmitTransaction.mockRejectedValue(tooLateErr);
await stellarTxSvc.submit({
sourceAddress: sourceKp.publicKey(),
operations: [Operation.payment({ destination: destKp.publicKey(), asset: Asset.native(), amount: '2' })],
signers: [sourceKp],
options: { feeSourceSecret },
}).catch(() => {});
// 1 initial + 3 fee-bump refreshes = 4 calls total
expect(mockLoadAccount).toHaveBeenCalledTimes(1 + stellarTxSvc.MAX_FEE_BUMP_ATTEMPTS);
// Every call must use the source address (NOT the fee-source address)
mockLoadAccount.mock.calls.forEach(call => {
expect(call[0]).toBe(sourceKp.publicKey());
});
});
// ── AC-4: tx_insufficient_fee — fee doubled per attempt (FEE_BUMP_MULTIPLIER=2) ──
it('AC-4: doubles the base fee on each tx_insufficient_fee fee-bump attempt', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
const insufficientFeeErr = Object.assign(new Error('tx_insufficient_fee'), {
response: { data: { extras: { result_codes: { transaction: ['tx_insufficient_fee'] } } } },
});
mockLoadAccount.mockResolvedValue(makeFakeAccount(sourceKp.publicKey(), '400'));
// initial fails, fee-bump 1 fails, fee-bump 2 fails, fee-bump 3 succeeds
mockSubmitTransaction
.mockRejectedValueOnce(insufficientFeeErr)
.mockRejectedValueOnce(insufficientFeeErr)
.mockRejectedValueOnce(insufficientFeeErr)
.mockResolvedValueOnce({ hash: 'feebump_fee_hash', ledger: 77, result_xdr: 'BBBBBB==' });
const result = await stellarTxSvc.submit({
sourceAddress: sourceKp.publicKey(),
operations: [Operation.payment({ destination: destKp.publicKey(), asset: Asset.native(), amount: '3' })],
signers: [sourceKp],
options: { feeSourceSecret },
});
expect(result.txHash).toBe('feebump_fee_hash');
// 1 initial + 3 fee-bump attempts = 4 total
expect(mockSubmitTransaction).toHaveBeenCalledTimes(4);
// Verify fee increases on each fee-bump attempt.
// stellar-sdk computes feeBumpTx.fee = baseFee * (innerTxOps + 1).
// With 1 inner operation: fee = baseFee * 2.
// attempt 1: bumpedFee = BASE_FEE*FEE_BUMP_MULTIPLIER*1 = 200 → tx.fee = 400
// attempt 2: bumpedFee = BASE_FEE*FEE_BUMP_MULTIPLIER*2 = 400 → tx.fee = 800
// attempt 3: bumpedFee = BASE_FEE*FEE_BUMP_MULTIPLIER*3 = 600 → tx.fee = 1200
const { FEE_BUMP_MULTIPLIER: mult } = stellarTxSvc;
const baseFeeNum = parseInt(BASE_FEE, 10);
const feeBumpCalls = mockSubmitTransaction.mock.calls.slice(1); // skip initial
expect(feeBumpCalls.length).toBe(stellarTxSvc.MAX_FEE_BUMP_ATTEMPTS);
// Each successive fee-bump must have a strictly higher fee than the previous
const fees = feeBumpCalls.map(call => parseInt(call[0].fee, 10));
for (let i = 1; i < fees.length; i++) {
expect(fees[i]).toBeGreaterThan(fees[i - 1]);
}
// Verify multiplier scaling: fee[i] / fee[0] should equal (i+1)
for (let i = 0; i < fees.length; i++) {
expect(fees[i]).toBe(fees[0] * (i + 1));
}
// fee[0] must use FEE_BUMP_MULTIPLIER
expect(fees[0]).toBe(baseFeeNum * mult * 2); // *2 because stellar fee-bump fee = baseFee*(innerOps+1)
});
// ── AC-5: tx_too_late → success on first fee-bump ────────────────────────
it('AC-5: resolves on first fee-bump attempt when initial tx_too_late fails', async () => {
const sourceKp = Keypair.random();
const destKp = Keypair.random();
const tooLateErr = Object.assign(new Error('tx_too_late'), {
response: { data: { extras: { result_codes: { transaction: ['tx_too_late'] } } } },
});
// 1 initial + 1 fee-bump refresh = 2 loadAccount calls
mockLoadAccount
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '500'))
.mockResolvedValueOnce(makeFakeAccount(sourceKp.publicKey(), '501'));
mockSubmitTransaction
.mockRejectedValueOnce(tooLateErr)
.mockResolvedValueOnce({ hash: 'too_late_bump_hash', ledger: 88, result_xdr: 'CCCCCC==' });
const result = await stellarTxSvc.submit({
sourceAddress: sourceKp.publicKey(),
operations: [Operation.payment({ destination: destKp.publicKey(), asset: Asset.native(), amount: '4' })],
signers: [sourceKp],
options: { feeSourceSecret },
});
expect(result.txHash).toBe('too_late_bump_hash');
expect(mockSubmitTransaction).toHaveBeenCalledTimes(2);
expect(mockLoadAccount).toHaveBeenCalledTimes(2);
});
});