-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathSmartTransactionsController.test.ts
More file actions
2846 lines (2582 loc) · 90.4 KB
/
SmartTransactionsController.test.ts
File metadata and controls
2846 lines (2582 loc) · 90.4 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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { deriveStateFromMetadata, Messenger } from '@metamask/base-controller';
import {
NetworkType,
convertHexToDecimal,
ChainId,
} from '@metamask/controller-utils';
import {
type NetworkControllerGetNetworkClientByIdAction,
type NetworkControllerGetStateAction,
type NetworkControllerStateChangeEvent,
NetworkStatus,
RpcEndpointType,
type NetworkState,
} from '@metamask/network-controller';
import {
type TransactionParams,
TransactionStatus,
TransactionType,
} from '@metamask/transaction-controller';
import nock from 'nock';
import * as sinon from 'sinon';
import packageJson from '../package.json';
import { advanceTime, flushPromises, getFakeProvider } from '../tests/helpers';
import {
API_BASE_URL,
SENTINEL_API_BASE_URL_MAP,
SmartTransactionsTraceName,
} from './constants';
import SmartTransactionsController, {
DEFAULT_INTERVAL,
getDefaultSmartTransactionsControllerState,
} from './SmartTransactionsController';
import type {
SmartTransactionsControllerActions,
SmartTransactionsControllerEvents,
} from './SmartTransactionsController';
import type { SmartTransaction, UnsignedTransaction, Hex } from './types';
import { SmartTransactionStatuses, ClientId } from './types';
import * as utils from './utils';
jest.mock('@metamask/eth-query', () => {
const EthQuery = jest.requireActual('@metamask/eth-query');
return class FakeEthQuery extends EthQuery {
sendAsync = jest.fn(({ method }, callback) => {
switch (method) {
case 'eth_getBalance': {
callback(null, '0x1000');
break;
}
case 'eth_getTransactionReceipt': {
callback(null, { blockNumber: '123' });
break;
}
case 'eth_getBlockByNumber': {
callback(null, { baseFeePerGas: '0x123' });
break;
}
case 'eth_getTransactionByHash': {
callback(null, {
maxFeePerGas: '0x123',
maxPriorityFeePerGas: '0x123',
});
break;
}
default: {
throw new Error('Invalid method');
}
}
});
};
});
const addressFrom = '0x268392a24B6b093127E8581eAfbD1DA228bAdAe3';
const txHash =
'0x0302b75dfb9fd9eb34056af031efcaee2a8cbd799ea054a85966165cd82a7356';
const createUnsignedTransaction = (chainId: number) => {
return {
from: addressFrom,
to: '0x0000000000000000000000000000000000000000',
value: 0,
data: '0x',
nonce: 1,
type: 2,
chainId,
};
};
const createGetFeesApiResponse = () => {
return {
txs: [
{
// Approval tx.
cancelFees: [
{ maxFeePerGas: 2100001000, maxPriorityFeePerGas: 466503987 },
{ maxFeePerGas: 2310003200, maxPriorityFeePerGas: 513154852 },
{ maxFeePerGas: 2541005830, maxPriorityFeePerGas: 564470851 },
{ maxFeePerGas: 2795108954, maxPriorityFeePerGas: 620918500 },
{ maxFeePerGas: 3074622644, maxPriorityFeePerGas: 683010971 },
{ maxFeePerGas: 3382087983, maxPriorityFeePerGas: 751312751 },
{ maxFeePerGas: 3720300164, maxPriorityFeePerGas: 826444778 },
{ maxFeePerGas: 4092333900, maxPriorityFeePerGas: 909090082 },
{ maxFeePerGas: 4501571383, maxPriorityFeePerGas: 1000000000 },
{ maxFeePerGas: 4951733023, maxPriorityFeePerGas: 1100001000 },
{ maxFeePerGas: 5446911277, maxPriorityFeePerGas: 1210002200 },
{ maxFeePerGas: 5991607851, maxPriorityFeePerGas: 1331003630 },
{ maxFeePerGas: 6590774628, maxPriorityFeePerGas: 1464105324 },
{ maxFeePerGas: 7249858682, maxPriorityFeePerGas: 1610517320 },
{ maxFeePerGas: 7974851800, maxPriorityFeePerGas: 1771570663 },
{ maxFeePerGas: 8772344955, maxPriorityFeePerGas: 1948729500 },
{ maxFeePerGas: 9649588222, maxPriorityFeePerGas: 2143604399 },
{ maxFeePerGas: 10614556694, maxPriorityFeePerGas: 2357966983 },
{ maxFeePerGas: 11676022978, maxPriorityFeePerGas: 2593766039 },
],
feeEstimate: 42000000000000,
fees: [
{ maxFeePerGas: 2310003200, maxPriorityFeePerGas: 513154852 },
{ maxFeePerGas: 2541005830, maxPriorityFeePerGas: 564470850 },
{ maxFeePerGas: 2795108954, maxPriorityFeePerGas: 620918500 },
{ maxFeePerGas: 3074622644, maxPriorityFeePerGas: 683010970 },
{ maxFeePerGas: 3382087983, maxPriorityFeePerGas: 751312751 },
{ maxFeePerGas: 3720300163, maxPriorityFeePerGas: 826444777 },
{ maxFeePerGas: 4092333900, maxPriorityFeePerGas: 909090082 },
{ maxFeePerGas: 4501571382, maxPriorityFeePerGas: 999999999 },
{ maxFeePerGas: 4951733022, maxPriorityFeePerGas: 1100001000 },
{ maxFeePerGas: 5446911277, maxPriorityFeePerGas: 1210002200 },
{ maxFeePerGas: 5991607851, maxPriorityFeePerGas: 1331003630 },
{ maxFeePerGas: 6590774627, maxPriorityFeePerGas: 1464105324 },
{ maxFeePerGas: 7249858681, maxPriorityFeePerGas: 1610517320 },
{ maxFeePerGas: 7974851800, maxPriorityFeePerGas: 1771570662 },
{ maxFeePerGas: 8772344954, maxPriorityFeePerGas: 1948729500 },
{ maxFeePerGas: 9649588222, maxPriorityFeePerGas: 2143604398 },
{ maxFeePerGas: 10614556693, maxPriorityFeePerGas: 2357966982 },
{ maxFeePerGas: 11676022977, maxPriorityFeePerGas: 2593766039 },
{ maxFeePerGas: 12843636951, maxPriorityFeePerGas: 2853145236 },
],
gasLimit: 21000,
gasUsed: 21000,
},
{
// Trade tx.
cancelFees: [
{ maxFeePerGas: 2100001000, maxPriorityFeePerGas: 466503987 },
{ maxFeePerGas: 2310003200, maxPriorityFeePerGas: 513154852 },
{ maxFeePerGas: 2541005830, maxPriorityFeePerGas: 564470851 },
{ maxFeePerGas: 2795108954, maxPriorityFeePerGas: 620918500 },
{ maxFeePerGas: 3074622644, maxPriorityFeePerGas: 683010971 },
{ maxFeePerGas: 3382087983, maxPriorityFeePerGas: 751312751 },
{ maxFeePerGas: 3720300164, maxPriorityFeePerGas: 826444778 },
{ maxFeePerGas: 4092333900, maxPriorityFeePerGas: 909090082 },
{ maxFeePerGas: 4501571383, maxPriorityFeePerGas: 1000000000 },
{ maxFeePerGas: 4951733023, maxPriorityFeePerGas: 1100001000 },
{ maxFeePerGas: 5446911277, maxPriorityFeePerGas: 1210002200 },
{ maxFeePerGas: 5991607851, maxPriorityFeePerGas: 1331003630 },
{ maxFeePerGas: 6590774628, maxPriorityFeePerGas: 1464105324 },
{ maxFeePerGas: 7249858682, maxPriorityFeePerGas: 1610517320 },
{ maxFeePerGas: 7974851800, maxPriorityFeePerGas: 1771570663 },
{ maxFeePerGas: 8772344955, maxPriorityFeePerGas: 1948729500 },
{ maxFeePerGas: 9649588222, maxPriorityFeePerGas: 2143604399 },
{ maxFeePerGas: 10614556694, maxPriorityFeePerGas: 2357966983 },
{ maxFeePerGas: 11676022978, maxPriorityFeePerGas: 2593766039 },
],
feeEstimate: 42000000000000,
fees: [
{ maxFeePerGas: 2310003200, maxPriorityFeePerGas: 513154852 },
{ maxFeePerGas: 2541005830, maxPriorityFeePerGas: 564470850 },
{ maxFeePerGas: 2795108954, maxPriorityFeePerGas: 620918500 },
{ maxFeePerGas: 3074622644, maxPriorityFeePerGas: 683010970 },
{ maxFeePerGas: 3382087983, maxPriorityFeePerGas: 751312751 },
{ maxFeePerGas: 3720300163, maxPriorityFeePerGas: 826444777 },
{ maxFeePerGas: 4092333900, maxPriorityFeePerGas: 909090082 },
{ maxFeePerGas: 4501571382, maxPriorityFeePerGas: 999999999 },
{ maxFeePerGas: 4951733022, maxPriorityFeePerGas: 1100001000 },
{ maxFeePerGas: 5446911277, maxPriorityFeePerGas: 1210002200 },
{ maxFeePerGas: 5991607851, maxPriorityFeePerGas: 1331003630 },
{ maxFeePerGas: 6590774627, maxPriorityFeePerGas: 1464105324 },
{ maxFeePerGas: 7249858681, maxPriorityFeePerGas: 1610517320 },
{ maxFeePerGas: 7974851800, maxPriorityFeePerGas: 1771570662 },
{ maxFeePerGas: 8772344954, maxPriorityFeePerGas: 1948729500 },
{ maxFeePerGas: 9649588222, maxPriorityFeePerGas: 2143604398 },
{ maxFeePerGas: 10614556693, maxPriorityFeePerGas: 2357966982 },
{ maxFeePerGas: 11676022977, maxPriorityFeePerGas: 2593766039 },
{ maxFeePerGas: 12843636951, maxPriorityFeePerGas: 2853145236 },
],
gasLimit: 21000,
gasUsed: 21000,
},
],
};
};
const createSubmitTransactionsApiResponse = () => {
return { uuid: 'dP23W7c2kt4FK9TmXOkz1UM2F20' };
};
const createSignedTransaction = () => {
return '0xf86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a02b79f322a625d623a2bb2911e0c6b3e7eaf741a7c7c5d2e8c67ef3ff4acf146ca01ae168fea63dc3391b75b586c8a7c0cb55cdf3b8e2e4d8e097957a3a56c6f2c5';
};
const createTxParams = (): TransactionParams => {
return {
from: addressFrom,
to: '0x0000000000000000000000000000000000000000',
value: '0',
data: '0x',
nonce: '0',
type: '2',
chainId: '0x4',
maxFeePerGas: '2310003200',
maxPriorityFeePerGas: '513154852',
};
};
const createSignedCanceledTransaction = () => {
return '0xf86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a02b79f322a625d623a2bb2911e0c6b3e7eaf741a7c7c5d2e8c67ef3ff4acf146ca01ae168fea63dc3391b75b586c8a7c0cb55cdf3b8e2e4d8e097957a3a56c6f2c5';
};
const createPendingBatchStatusApiResponse = () => ({
uuid1: {
cancellationFeeWei: 0,
cancellationReason: 'not_cancelled',
deadlineRatio: 0.0006295545895894369,
minedTx: 'not_mined',
minedHash: '',
},
});
const createStateAfterPending = () => {
return [
{
uuid: 'uuid1',
status: 'pending',
cancellable: true,
statusMetadata: {
cancellationFeeWei: 0,
cancellationReason: 'not_cancelled',
deadlineRatio: 0.0006295545895894369,
minedTx: 'not_mined',
minedHash: '',
},
accountHardwareType: 'Ledger Hardware',
accountType: 'hardware',
deviceModel: 'ledger',
},
];
};
const createSuccessBatchStatusApiResponse = () => ({
uuid2: {
cancellationFeeWei: 36777567771000,
cancellationReason: 'not_cancelled',
deadlineRatio: 0.6400288486480713,
minedHash:
'0x55ad39634ee10d417b6e190cfd3736098957e958879cffe78f1f00f4fd2654d6',
minedTx: 'success',
},
});
const createStateAfterSuccess = () => {
return [
{
uuid: 'uuid2',
status: 'success',
cancellable: false,
statusMetadata: {
cancellationFeeWei: 36777567771000,
cancellationReason: 'not_cancelled',
deadlineRatio: 0.6400288486480713,
minedHash:
'0x55ad39634ee10d417b6e190cfd3736098957e958879cffe78f1f00f4fd2654d6',
minedTx: 'success',
},
accountHardwareType: 'Ledger Hardware',
accountType: 'hardware',
deviceModel: 'ledger',
},
];
};
const createSuccessLivenessApiResponse = () => ({
smartTransactions: true,
});
const testHistory = [
{
op: 'add',
path: '/swapTokenValue',
value: '0.001',
},
];
const createTransactionMeta = (
status: TransactionStatus = TransactionStatus.signed,
) => {
return {
hash: txHash,
status,
id: '1',
txParams: {
from: addressFrom,
to: '0x1678a085c290ebd122dc42cba69373b5953b831d',
gasPrice: '0x77359400',
gas: '0x7b0d',
nonce: '0x4b',
},
type: TransactionType.simpleSend,
chainId: ChainId.mainnet,
time: 1624408066355,
defaultGasEstimates: {
gas: '0x7b0d',
gasPrice: '0x77359400',
},
error: {
name: 'Error',
message: 'Details of the error',
},
securityProviderResponse: {
flagAsDangerous: 0,
},
};
};
const ethereumChainIdDec = parseInt(ChainId.mainnet, 16);
const sepoliaChainIdDec = parseInt(ChainId.sepolia, 16);
const trackMetaMetricsEventSpy = jest.fn();
describe('SmartTransactionsController', () => {
afterEach(async () => {
jest.clearAllMocks();
nock.cleanAll();
});
it('initializes with default state', async () => {
const defaultState = getDefaultSmartTransactionsControllerState();
await withController(({ controller }) => {
expect(controller.state).toStrictEqual({
...defaultState,
smartTransactionsState: {
...defaultState.smartTransactionsState,
smartTransactions: {
[ChainId.mainnet]: [],
},
},
});
});
});
describe('onNetworkChange', () => {
it('calls poll', async () => {
await withController(({ controller, triggerNetworStateChange }) => {
const checkPollSpy = jest.spyOn(controller, 'checkPoll');
triggerNetworStateChange({
selectedNetworkClientId: NetworkType.sepolia,
networkConfigurationsByChainId: {},
networksMetadata: {},
});
expect(checkPollSpy).toHaveBeenCalled();
});
});
});
describe('checkPoll', () => {
it('calls poll if there is no pending transaction and pending transactions', async () => {
const pollSpy = jest
.spyOn(SmartTransactionsController.prototype, 'poll')
.mockImplementation(async () => {
return new Promise(() => ({}));
});
const { smartTransactionsState } =
getDefaultSmartTransactionsControllerState();
const pendingStx = createStateAfterPending();
await withController(
{
options: {
state: {
smartTransactionsState: {
...smartTransactionsState,
smartTransactions: {
[ChainId.mainnet]: pendingStx as SmartTransaction[],
},
},
},
},
},
() => {
expect(pollSpy).toHaveBeenCalled();
},
);
});
it('calls stop if there is a timeoutHandle and no pending transactions', async () => {
await withController(({ controller }) => {
const stopSpy = jest.spyOn(controller, 'stop');
controller.timeoutHandle = setTimeout(() => ({}));
controller.checkPoll(controller.state);
expect(stopSpy).toHaveBeenCalled();
clearInterval(controller.timeoutHandle);
});
});
});
describe('poll', () => {
it('does not call updateSmartTransactions on unsupported networks', async () => {
await withController(
{
options: {
supportedChainIds: [ChainId.mainnet],
},
},
({ controller, triggerNetworStateChange }) => {
const updateSmartTransactionsSpy = jest.spyOn(
controller,
'updateSmartTransactions',
);
expect(updateSmartTransactionsSpy).not.toHaveBeenCalled();
triggerNetworStateChange({
selectedNetworkClientId: NetworkType.sepolia,
networkConfigurationsByChainId: {},
networksMetadata: {},
});
expect(updateSmartTransactionsSpy).not.toHaveBeenCalled();
},
);
});
it('calls updateSmartTransactions if there is a timeoutHandle and pending transactions', async () => {
await withController(({ controller }) => {
const updateSmartTransactionsSpy = jest.spyOn(
controller,
'updateSmartTransactions',
);
controller.timeoutHandle = setTimeout(() => ({}));
controller.poll(1000);
expect(updateSmartTransactionsSpy).toHaveBeenCalled();
});
});
});
describe('updateSmartTransactions', () => {
// TODO rewrite this test... updateSmartTransactions is getting called via the checkPoll method which is called whenever state is updated.
// this test should be more isolated to the updateSmartTransactions method.
it('calls fetchSmartTransactionsStatus if there are pending transactions', async () => {
const fetchSmartTransactionsStatusSpy = jest
.spyOn(
SmartTransactionsController.prototype,
'fetchSmartTransactionsStatus',
)
.mockImplementation(async () => {
return new Promise(() => ({}));
});
const { smartTransactionsState } =
getDefaultSmartTransactionsControllerState();
const pendingStx = createStateAfterPending();
await withController(
{
options: {
state: {
smartTransactionsState: {
...smartTransactionsState,
smartTransactions: {
[ChainId.mainnet]: pendingStx as SmartTransaction[],
},
},
},
},
},
() => {
expect(fetchSmartTransactionsStatusSpy).toHaveBeenCalled();
},
);
});
});
describe('trackStxStatusChange', () => {
it('tracks status change if prevSmartTransactions is undefined', async () => {
await withController(({ controller }) => {
const smartTransaction = {
...createStateAfterPending()[0],
swapMetaData: {},
} as SmartTransaction;
controller.trackStxStatusChange(smartTransaction);
expect(trackMetaMetricsEventSpy).toHaveBeenCalledWith(
expect.objectContaining({
event: 'STX Status Updated',
category: 'Transactions',
properties: expect.objectContaining({
stx_status: SmartTransactionStatuses.PENDING,
is_smart_transaction: true,
}),
sensitiveProperties: expect.objectContaining({
account_hardware_type: 'Ledger Hardware',
account_type: 'hardware',
device_model: 'ledger',
}),
}),
);
});
});
it('does not track if smartTransaction and prevSmartTransaction have the same status', async () => {
await withController(({ controller }) => {
const smartTransaction = createStateAfterPending()[0];
controller.trackStxStatusChange(
smartTransaction as SmartTransaction,
smartTransaction as SmartTransaction,
);
expect(trackMetaMetricsEventSpy).not.toHaveBeenCalled();
});
});
it('tracks status change if smartTransaction and prevSmartTransaction have different statuses', async () => {
await withController(({ controller }) => {
const smartTransaction = {
...createStateAfterSuccess()[0],
swapMetaData: {},
};
const prevSmartTransaction = {
...smartTransaction,
status: SmartTransactionStatuses.PENDING,
};
controller.trackStxStatusChange(
smartTransaction as SmartTransaction,
prevSmartTransaction as SmartTransaction,
);
expect(trackMetaMetricsEventSpy).toHaveBeenCalledWith(
expect.objectContaining({
event: 'STX Status Updated',
category: 'Transactions',
properties: expect.objectContaining({
stx_status: SmartTransactionStatuses.SUCCESS,
is_smart_transaction: true,
}),
sensitiveProperties: expect.objectContaining({
account_hardware_type: 'Ledger Hardware',
account_type: 'hardware',
device_model: 'ledger',
}),
}),
);
});
});
});
describe('setOptInState', () => {
it('sets optIn state', async () => {
await withController(({ controller }) => {
controller.setOptInState(true);
expect(controller.state.smartTransactionsState.userOptInV2).toBe(true);
controller.setOptInState(false);
expect(controller.state.smartTransactionsState.userOptInV2).toBe(false);
controller.setOptInState(null);
expect(controller.state.smartTransactionsState.userOptInV2).toBeNull();
});
});
});
describe('clearFees', () => {
it('clears fees', async () => {
await withController(async ({ controller }) => {
const tradeTx = createUnsignedTransaction(ethereumChainIdDec);
const approvalTx = createUnsignedTransaction(ethereumChainIdDec);
const getFeesApiResponse = createGetFeesApiResponse();
nock(API_BASE_URL)
.post(`/networks/${ethereumChainIdDec}/getFees`)
.reply(200, getFeesApiResponse);
const fees = await controller.getFees(tradeTx, approvalTx);
expect(fees).toMatchObject({
approvalTxFees: getFeesApiResponse.txs[0],
tradeTxFees: getFeesApiResponse.txs[1],
});
controller.clearFees();
expect(controller.state.smartTransactionsState.fees).toStrictEqual({
approvalTxFees: null,
tradeTxFees: null,
});
});
});
});
describe('getFees', () => {
it('gets unsigned transactions and estimates based on an unsigned transaction', async () => {
await withController(async ({ controller }) => {
const tradeTx = createUnsignedTransaction(ethereumChainIdDec);
const approvalTx = createUnsignedTransaction(ethereumChainIdDec);
const getFeesApiResponse = createGetFeesApiResponse();
nock(API_BASE_URL)
.post(`/networks/${ethereumChainIdDec}/getFees`)
.reply(200, getFeesApiResponse);
const fees = await controller.getFees(tradeTx, approvalTx);
expect(fees).toMatchObject({
approvalTxFees: getFeesApiResponse.txs[0],
tradeTxFees: getFeesApiResponse.txs[1],
});
});
});
it('gets estimates based on an unsigned transaction with an undefined nonce', async () => {
await withController(async ({ controller }) => {
const tradeTx: UnsignedTransaction =
createUnsignedTransaction(ethereumChainIdDec);
tradeTx.nonce = undefined;
const getFeesApiResponse = createGetFeesApiResponse();
nock(API_BASE_URL)
.post(`/networks/${ethereumChainIdDec}/getFees`)
.reply(200, getFeesApiResponse);
const fees = await controller.getFees(tradeTx);
expect(fees).toMatchObject({
tradeTxFees: getFeesApiResponse.txs[0],
});
});
});
it('should add fee data to feesByChainId state using the networkClientId passed in to identify the appropriate chain', async () => {
await withController(async ({ controller }) => {
const tradeTx = createUnsignedTransaction(sepoliaChainIdDec);
const approvalTx = createUnsignedTransaction(sepoliaChainIdDec);
const getFeesApiResponse = createGetFeesApiResponse();
nock(API_BASE_URL)
.post(`/networks/${sepoliaChainIdDec}/getFees`)
.reply(200, getFeesApiResponse);
expect(
controller.state.smartTransactionsState.feesByChainId,
).toStrictEqual(
getDefaultSmartTransactionsControllerState().smartTransactionsState
.feesByChainId,
);
await controller.getFees(tradeTx, approvalTx, {
networkClientId: NetworkType.sepolia,
});
expect(
controller.state.smartTransactionsState.feesByChainId,
).toMatchObject({
[ChainId.mainnet]: {
approvalTxFees: null,
tradeTxFees: null,
},
[ChainId.sepolia]: {
approvalTxFees: getFeesApiResponse.txs[0],
tradeTxFees: getFeesApiResponse.txs[1],
},
});
});
});
});
describe('submitSignedTransactions', () => {
beforeEach(() => {
jest
.spyOn(SmartTransactionsController.prototype, 'checkPoll')
.mockImplementation(() => ({}));
});
it('submits a smart transaction with signed transactions', async () => {
await withController(async ({ controller }) => {
const signedTransaction = createSignedTransaction();
const signedCanceledTransaction = createSignedCanceledTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse(); // It has uuid.
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
await controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
signedCanceledTransactions: [signedCanceledTransaction],
txParams: createTxParams(),
});
const submittedSmartTransaction =
controller.state.smartTransactionsState.smartTransactions[
ChainId.mainnet
][0];
expect(submittedSmartTransaction.uuid).toBe(
'dP23W7c2kt4FK9TmXOkz1UM2F20',
);
expect(submittedSmartTransaction.accountHardwareType).toBe(
'Ledger Hardware',
);
expect(submittedSmartTransaction.accountType).toBe('hardware');
expect(submittedSmartTransaction.deviceModel).toBe('ledger');
});
});
it('should acquire nonce for Swap transactions only', async () => {
// Create a mock for getNonceLock
const mockGetNonceLock = jest.fn().mockResolvedValue({
nextNonce: 42,
nonceDetails: { test: 'details' },
releaseLock: jest.fn(),
});
await withController(
{
options: {
getNonceLock: mockGetNonceLock,
},
},
async ({ controller }) => {
const signedTransaction = createSignedTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse();
// First API mock for the case without nonce
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
// Second API mock for the case with nonce
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
// Case 1: Swap transaction without nonce (should call getNonceLock)
const txParamsWithoutNonce = {
...createTxParams(),
nonce: undefined, // Explicitly undefined nonce
};
await controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
txParams: txParamsWithoutNonce,
// No transactionMeta means type defaults to 'swap'
});
// Verify getNonceLock was called for the Swap
expect(mockGetNonceLock).toHaveBeenCalledTimes(1);
expect(mockGetNonceLock).toHaveBeenCalledWith(
txParamsWithoutNonce.from,
NetworkType.mainnet,
);
// Reset the mock
mockGetNonceLock.mockClear();
// Case 2: Transaction with nonce already set (should NOT call getNonceLock)
const txParamsWithNonce = createTxParams(); // This has nonce: '0'
await controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
txParams: txParamsWithNonce,
});
// Verify getNonceLock was NOT called for transaction with nonce
expect(mockGetNonceLock).not.toHaveBeenCalled();
},
);
});
it('should properly set nonce on txParams and mark transaction as swap type', async () => {
// Mock with a specific nextNonce value we can verify
const mockGetNonceLock = jest.fn().mockResolvedValue({
nextNonce: 42,
nonceDetails: { test: 'nonce details' },
releaseLock: jest.fn(),
});
await withController(
{
options: {
getNonceLock: mockGetNonceLock,
},
},
async ({ controller }) => {
const signedTransaction = createSignedTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse();
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
// Create txParams without nonce
const txParamsWithoutNonce = {
...createTxParams(),
nonce: undefined,
from: addressFrom,
};
await controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
txParams: txParamsWithoutNonce,
// No transactionMeta provided, should default to 'swap' type
});
// Get the created smart transaction
const createdSmartTransaction =
controller.state.smartTransactionsState.smartTransactions[
ChainId.mainnet
][0];
// Verify nonce was set correctly on the txParams in the created transaction
expect(createdSmartTransaction.txParams.nonce).toBe('0x2a'); // 42 in hex
// Verify transaction type is set to 'swap' by default
expect(createdSmartTransaction.type).toBe('swap');
// Verify nonceDetails were passed correctly
expect(createdSmartTransaction.nonceDetails).toStrictEqual({
test: 'nonce details',
});
},
);
});
it('should handle errors when acquiring nonce lock', async () => {
// Mock getNonceLock to reject with an error
const mockError = new Error('Failed to acquire nonce');
const mockGetNonceLock = jest.fn().mockRejectedValue(mockError);
// Spy on console.error to verify it's called
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
await withController(
{
options: {
getNonceLock: mockGetNonceLock,
},
},
async ({ controller }) => {
const signedTransaction = createSignedTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse();
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
// Create txParams without nonce
const txParamsWithoutNonce = {
...createTxParams(),
nonce: undefined,
from: addressFrom,
};
// Attempt to submit a transaction that will fail when acquiring nonce
await expect(
controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
txParams: txParamsWithoutNonce,
}),
).rejects.toThrow('Failed to acquire nonce');
// Verify error was logged
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Failed to acquire nonce lock:',
mockError,
);
// Cleanup spy
consoleErrorSpy.mockRestore();
},
);
});
it('submits a batch of signed transactions', async () => {
await withController(async ({ controller }) => {
const signedTransaction1 = createSignedTransaction();
const signedTransaction2 = createSignedTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse(); // It has uuid.
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
const txParams = createTxParams();
const result = await controller.submitSignedTransactions({
signedTransactions: [signedTransaction1, signedTransaction2],
txParams,
});
// Check response has both txHash and txHashes
expect(result.uuid).toBe('dP23W7c2kt4FK9TmXOkz1UM2F20');
expect(result.txHash).toBeDefined();
expect(result.txHashes).toBeDefined();
expect(result.txHashes?.length).toBe(2);
// Check smart transaction has correct properties
const submittedSmartTransaction =
controller.state.smartTransactionsState.smartTransactions[
ChainId.mainnet
][0];
expect(submittedSmartTransaction.uuid).toBe(
'dP23W7c2kt4FK9TmXOkz1UM2F20',
);
expect(submittedSmartTransaction.txHashes).toBeDefined();
expect(submittedSmartTransaction.txHashes?.length).toBe(2);
expect(submittedSmartTransaction.txHash).toBe(result.txHashes[0]);
});
});
it('works with optional signedCanceledTransactions', async () => {
await withController(async ({ controller }) => {
const signedTransaction = createSignedTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse();
// Verify that the request body has empty rawCancelTxs array when signedCanceledTransactions is omitted
let requestBody: any;
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
(body) => {
requestBody = body;
return true;
},
)
.reply(200, submitTransactionsApiResponse);
await controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
txParams: createTxParams(),
// No signedCanceledTransactions provided
});
// Verify the request was made with an empty rawCancelTxs array
expect(requestBody).toBeDefined();
expect(requestBody.rawCancelTxs).toStrictEqual([]);
});
});
it('works without txParams', async () => {
await withController(async ({ controller }) => {
const signedTransaction = createSignedTransaction();
const submitTransactionsApiResponse =
createSubmitTransactionsApiResponse();
nock(API_BASE_URL)
.post(
`/networks/${ethereumChainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`,
)
.reply(200, submitTransactionsApiResponse);
// This should not throw an error when txParams is missing
const result = await controller.submitSignedTransactions({
signedTransactions: [signedTransaction],
// No txParams provided
});
expect(result.uuid).toBe('dP23W7c2kt4FK9TmXOkz1UM2F20');
// The transaction should still be created in state
const submittedSmartTransaction =
controller.state.smartTransactionsState.smartTransactions[
ChainId.mainnet
][0];
expect(submittedSmartTransaction.uuid).toBe(
'dP23W7c2kt4FK9TmXOkz1UM2F20',
);
});
});
});