-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathtradeModule.spec.ts
More file actions
1850 lines (1548 loc) · 78.8 KB
/
tradeModule.spec.ts
File metadata and controls
1850 lines (1548 loc) · 78.8 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 "module-alias/register";
import Web3 from "web3";
import { BigNumber } from "ethers";
import { utils } from "ethers";
import { ethers } from "hardhat";
import { Address, Bytes } from "@utils/types";
import { Account } from "@utils/test/types";
import {
KyberExchangeAdapter,
KyberNetworkProxyMock,
ManagerIssuanceHookMock,
OneInchExchangeAdapter,
OneInchExchangeMock,
SetToken,
StandardTokenMock,
StandardTokenWithFeeMock,
TradeModule,
UniswapV2ExchangeAdapter,
UniswapV2TransferFeeExchangeAdapter,
UniswapV2ExchangeAdapterV2,
WETH9,
ZeroExApiAdapter,
ZeroExMock,
UniswapV3ExchangeAdapter,
} from "@utils/contracts";
import { ADDRESS_ZERO, EMPTY_BYTES, MAX_UINT_256, ZERO } from "@utils/constants";
import DeployHelper from "@utils/deploys";
import {
ether,
bitcoin,
} from "@utils/index";
import {
cacheBeforeEach,
getAccounts,
getRandomAccount,
getSystemFixture,
getUniswapFixture,
getUniswapV3Fixture,
getWaffleExpect,
} from "@utils/test/index";
import { SystemFixture, UniswapFixture, UniswapV3Fixture } from "@utils/fixtures";
const web3 = new Web3();
const expect = getWaffleExpect();
describe("TradeModule", () => {
let owner: Account;
let manager: Account;
let mockModule: Account;
let deployer: DeployHelper;
let kyberNetworkProxy: KyberNetworkProxyMock;
let kyberExchangeAdapter: KyberExchangeAdapter;
let kyberAdapterName: string;
let oneInchExchangeMock: OneInchExchangeMock;
let oneInchExchangeAdapter: OneInchExchangeAdapter;
let oneInchAdapterName: string;
let uniswapExchangeAdapter: UniswapV2ExchangeAdapter;
let uniswapAdapterName: string;
let uniswapTransferFeeExchangeAdapter: UniswapV2TransferFeeExchangeAdapter;
let uniswapTransferFeeAdapterName: string;
let uniswapExchangeAdapterV2: UniswapV2ExchangeAdapterV2;
let uniswapAdapterV2Name: string;
let uniswapV3ExchangeAdapter: UniswapV3ExchangeAdapter;
let uniswapV3AdapterName: string;
let zeroExMock: ZeroExMock;
let zeroExApiAdapter: ZeroExApiAdapter;
let zeroExApiAdapterName: string;
let wbtcRate: BigNumber;
let setup: SystemFixture;
let uniswapSetup: UniswapFixture;
let uniswapV3Setup: UniswapV3Fixture;
let tradeModule: TradeModule;
cacheBeforeEach(async () => {
[
owner,
manager,
mockModule,
] = await getAccounts();
deployer = new DeployHelper(owner.wallet);
setup = getSystemFixture(owner.address);
await setup.initialize();
wbtcRate = ether(33); // 1 WBTC = 33 ETH
// Mock Kyber reserve only allows trading from/to WETH
kyberNetworkProxy = await deployer.mocks.deployKyberNetworkProxyMock(setup.weth.address);
await kyberNetworkProxy.addToken(
setup.wbtc.address,
wbtcRate,
8
);
kyberExchangeAdapter = await deployer.adapters.deployKyberExchangeAdapter(kyberNetworkProxy.address);
// Mock OneInch exchange that allows for only fixed exchange amounts
oneInchExchangeMock = await deployer.mocks.deployOneInchExchangeMock(
setup.wbtc.address,
setup.weth.address,
BigNumber.from(100000000), // 1 WBTC
wbtcRate, // Trades for 33 WETH
);
// 1inch function signature
const oneInchFunctionSignature = web3.eth.abi.encodeFunctionSignature(
"swap(address,address,uint256,uint256,uint256,address,address[],bytes,uint256[],uint256[])"
);
oneInchExchangeAdapter = await deployer.adapters.deployOneInchExchangeAdapter(
oneInchExchangeMock.address,
oneInchExchangeMock.address,
oneInchFunctionSignature
);
uniswapSetup = getUniswapFixture(owner.address);
await uniswapSetup.initialize(
owner,
setup.weth.address,
setup.wbtc.address,
setup.dai.address
);
uniswapV3Setup = getUniswapV3Fixture(owner.address);
await uniswapV3Setup.initialize(
owner,
setup.weth,
2500,
setup.wbtc,
35000,
setup.dai
);
uniswapExchangeAdapter = await deployer.adapters.deployUniswapV2ExchangeAdapter(uniswapSetup.router.address);
uniswapTransferFeeExchangeAdapter = await deployer.adapters.deployUniswapV2TransferFeeExchangeAdapter(uniswapSetup.router.address);
uniswapExchangeAdapterV2 = await deployer.adapters.deployUniswapV2ExchangeAdapterV2(uniswapSetup.router.address);
uniswapV3ExchangeAdapter = await deployer.adapters.deployUniswapV3ExchangeAdapter(uniswapV3Setup.swapRouter.address);
zeroExMock = await deployer.mocks.deployZeroExMock(
setup.wbtc.address,
setup.weth.address,
BigNumber.from(100000000), // 1 WBTC
wbtcRate, // Trades for 33 WETH
);
zeroExApiAdapter = await deployer.adapters.deployZeroExApiAdapter(zeroExMock.address, setup.weth.address);
kyberAdapterName = "KYBER";
oneInchAdapterName = "ONEINCH";
uniswapAdapterName = "UNISWAP";
uniswapTransferFeeAdapterName = "UNISWAP_TRANSFER_FEE";
uniswapAdapterV2Name = "UNISWAPV2";
zeroExApiAdapterName = "ZERO_EX";
uniswapV3AdapterName = "UNISWAPV3";
tradeModule = await deployer.modules.deployTradeModule(setup.controller.address);
await setup.controller.addModule(tradeModule.address);
await setup.integrationRegistry.batchAddIntegration(
[
tradeModule.address,
tradeModule.address,
tradeModule.address,
tradeModule.address,
tradeModule.address,
tradeModule.address,
tradeModule.address,
],
[
kyberAdapterName,
oneInchAdapterName,
uniswapAdapterName,
uniswapTransferFeeAdapterName,
uniswapAdapterV2Name,
zeroExApiAdapterName,
uniswapV3AdapterName,
],
[
kyberExchangeAdapter.address,
oneInchExchangeAdapter.address,
uniswapExchangeAdapter.address,
uniswapTransferFeeExchangeAdapter.address,
uniswapExchangeAdapterV2.address,
zeroExApiAdapter.address,
uniswapV3ExchangeAdapter.address,
]
);
});
describe("#constructor", async () => {
let subjectTradeModule: TradeModule;
async function subject(): Promise<TradeModule> {
return deployer.modules.deployTradeModule(setup.controller.address);
}
it("should have the correct controller", async () => {
subjectTradeModule = await subject();
const expectedController = await subjectTradeModule.controller();
expect(expectedController).to.eq(setup.controller.address);
});
});
context("when there is a deployed SetToken with enabled TradeModule", async () => {
let sourceToken: StandardTokenMock;
let wbtcUnits: BigNumber;
let destinationToken: WETH9;
let setToken: SetToken;
let issueQuantity: BigNumber;
let mockPreIssuanceHook: ManagerIssuanceHookMock;
cacheBeforeEach(async () => {
// Selling WBTC
sourceToken = setup.wbtc;
destinationToken = setup.weth;
wbtcUnits = BigNumber.from(100000000); // 1 WBTC in base units 1 * 10 ** 8
// Create Set token
setToken = await setup.createSetToken(
[sourceToken.address],
[wbtcUnits],
[setup.issuanceModule.address, tradeModule.address],
manager.address
);
});
describe("#initialize", async () => {
let subjectSetToken: Address;
let subjectCaller: Account;
beforeEach(async () => {
subjectSetToken = setToken.address;
subjectCaller = manager;
});
async function subject(): Promise<any> {
tradeModule = tradeModule.connect(subjectCaller.wallet);
return tradeModule.initialize(subjectSetToken);
}
it("should enable the Module on the SetToken", async () => {
await subject();
const isModuleEnabled = await setToken.isInitializedModule(tradeModule.address);
expect(isModuleEnabled).to.eq(true);
});
describe("when the caller is not the SetToken manager", async () => {
beforeEach(async () => {
subjectCaller = await getRandomAccount();
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be the SetToken manager");
});
});
describe("when the module is not pending", async () => {
beforeEach(async () => {
await subject();
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be pending initialization");
});
});
describe("when the SetToken is not enabled on the controller", async () => {
beforeEach(async () => {
const nonEnabledSetToken = await setup.createNonControllerEnabledSetToken(
[setup.dai.address],
[ether(1)],
[tradeModule.address],
manager.address
);
subjectSetToken = nonEnabledSetToken.address;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be controller-enabled SetToken");
});
});
});
describe("#trade", async () => {
let tokenWithFee: StandardTokenWithFeeMock;
let sourceTokenQuantity: BigNumber;
let destinationTokenQuantity: BigNumber;
let isInitialized: boolean;
let subjectDestinationToken: Address;
let subjectSourceToken: Address;
let subjectSourceQuantity: BigNumber;
let subjectAdapterName: string;
let subjectSetToken: Address;
let subjectMinDestinationQuantity: BigNumber;
let subjectData: Bytes;
let subjectCaller: Account;
context("when trading a Default component on Kyber", async () => {
before(async () => {
isInitialized = true;
});
const initializeContracts = async () => {
// Fund Kyber reserve with destinationToken WETH
destinationToken = destinationToken.connect(owner.wallet);
await destinationToken.transfer(kyberNetworkProxy.address, ether(1000));
// Initialize module if set to true
if (isInitialized) {
tradeModule = tradeModule.connect(manager.wallet);
await tradeModule.initialize(setToken.address);
}
sourceTokenQuantity = wbtcUnits.div(2); // Trade 0.5 WBTC
const sourceTokenDecimals = await sourceToken.decimals();
destinationTokenQuantity = wbtcRate.mul(sourceTokenQuantity).div(10 ** sourceTokenDecimals);
// Transfer sourceToken from owner to manager for issuance
sourceToken = sourceToken.connect(owner.wallet);
await sourceToken.transfer(manager.address, wbtcUnits.mul(100));
// Approve tokens to Controller and call issue
sourceToken = sourceToken.connect(manager.wallet);
await sourceToken.approve(setup.issuanceModule.address, ethers.constants.MaxUint256);
// Deploy mock issuance hook and initialize issuance module
setup.issuanceModule = setup.issuanceModule.connect(manager.wallet);
mockPreIssuanceHook = await deployer.mocks.deployManagerIssuanceHookMock();
await setup.issuanceModule.initialize(setToken.address, mockPreIssuanceHook.address);
// Issue 10 SetTokens
issueQuantity = ether(10);
await setup.issuanceModule.issue(setToken.address, issueQuantity, owner.address);
};
const initializeSubjectVariables = () => {
subjectSourceToken = sourceToken.address;
subjectDestinationToken = destinationToken.address;
subjectSourceQuantity = sourceTokenQuantity;
subjectSetToken = setToken.address;
subjectAdapterName = kyberAdapterName;
subjectData = EMPTY_BYTES;
subjectMinDestinationQuantity = destinationTokenQuantity.sub(ether(0.5)); // Receive a min of 16 WETH for 0.5 WBTC
subjectCaller = manager;
};
async function subject(): Promise<any> {
tradeModule = tradeModule.connect(subjectCaller.wallet);
return tradeModule.trade(
subjectSetToken,
subjectAdapterName,
subjectSourceToken,
subjectSourceQuantity,
subjectDestinationToken,
subjectMinDestinationQuantity,
subjectData
);
}
describe("when the module is initialized", () => {
cacheBeforeEach(initializeContracts);
beforeEach(initializeSubjectVariables);
it("should transfer the correct components to the SetToken", async () => {
const oldDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
await subject();
const totalDestinationQuantity = issueQuantity.mul(destinationTokenQuantity).div(ether(1));
const expectedDestinationTokenBalance = oldDestinationTokenBalance.add(totalDestinationQuantity);
const newDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
it("should transfer the correct components from the SetToken", async () => {
const oldSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
await subject();
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const expectedSourceTokenBalance = oldSourceTokenBalance.sub(totalSourceQuantity);
const newSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should transfer the correct components to the exchange", async () => {
const oldSourceTokenBalance = await sourceToken.balanceOf(kyberNetworkProxy.address);
await subject();
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const expectedSourceTokenBalance = oldSourceTokenBalance.add(totalSourceQuantity);
const newSourceTokenBalance = await sourceToken.balanceOf(kyberNetworkProxy.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should transfer the correct components from the exchange", async () => {
const oldDestinationTokenBalance = await destinationToken.balanceOf(kyberNetworkProxy.address);
await subject();
const totalDestinationQuantity = issueQuantity.mul(destinationTokenQuantity).div(ether(1));
const expectedDestinationTokenBalance = oldDestinationTokenBalance.sub(totalDestinationQuantity);
const newDestinationTokenBalance = await destinationToken.balanceOf(kyberNetworkProxy.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
it("should update the positions on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
const initialFirstPosition = (await setToken.getPositions())[0];
await subject();
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
const newSecondPosition = (await setToken.getPositions())[1];
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newFirstPosition.component).to.eq(sourceToken.address);
expect(newFirstPosition.unit).to.eq(initialFirstPosition.unit.sub(sourceTokenQuantity));
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
expect(newSecondPosition.component).to.eq(destinationToken.address);
expect(newSecondPosition.unit).to.eq(destinationTokenQuantity);
expect(newSecondPosition.module).to.eq(ADDRESS_ZERO);
});
describe("when there is a protocol fee charged", async () => {
let feePercentage: BigNumber;
beforeEach(async () => {
feePercentage = ether(0.05);
setup.controller = setup.controller.connect(owner.wallet);
await setup.controller.addFee(
tradeModule.address,
ZERO, // Fee type on trade function denoted as 0
feePercentage // Set fee to 5 bps
);
});
it("should transfer the correct components minus fee to the SetToken", async () => {
const oldDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
await subject();
const totalDestinationQuantity = issueQuantity.mul(destinationTokenQuantity).div(ether(1));
const totalProtocolFee = feePercentage.mul(totalDestinationQuantity).div(ether(1));
const expectedDestinationTokenBalance = oldDestinationTokenBalance
.add(totalDestinationQuantity)
.sub(totalProtocolFee);
const newDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
it("should transfer the correct components from the SetToken to the exchange", async () => {
const oldSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
await subject();
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const expectedSourceTokenBalance = oldSourceTokenBalance.sub(totalSourceQuantity);
const newSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should update the positions on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
const initialFirstPosition = (await setToken.getPositions())[0];
await subject();
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
const newSecondPosition = (await setToken.getPositions())[1];
const unitProtocolFee = feePercentage.mul(destinationTokenQuantity).div(ether(1));
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newFirstPosition.component).to.eq(sourceToken.address);
expect(newFirstPosition.unit).to.eq(initialFirstPosition.unit.sub(sourceTokenQuantity));
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
expect(newSecondPosition.component).to.eq(destinationToken.address);
expect(newSecondPosition.unit).to.eq(destinationTokenQuantity.sub(unitProtocolFee));
expect(newSecondPosition.module).to.eq(ADDRESS_ZERO);
});
it("should emit the correct ComponentExchanged event", async () => {
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const totalDestinationQuantity = issueQuantity.mul(destinationTokenQuantity).div(ether(1));
const totalProtocolFee = feePercentage.mul(totalDestinationQuantity).div(ether(1));
await expect(subject()).to.emit(tradeModule, "ComponentExchanged").withArgs(
setToken.address,
subjectSourceToken,
subjectDestinationToken,
kyberExchangeAdapter.address,
totalSourceQuantity,
totalDestinationQuantity.sub(totalProtocolFee),
totalProtocolFee
);
});
describe("when receive token is more than total position units tracked on SetToken", async () => {
let extraTokenQuantity: BigNumber;
beforeEach(async () => {
extraTokenQuantity = ether(1);
destinationToken = destinationToken.connect(owner.wallet);
// Transfer destination token to SetToken
await destinationToken.transfer(setToken.address, extraTokenQuantity);
});
it("should transfer the correct components minus fee to the SetToken", async () => {
const oldDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
await subject();
const totalDestinationQuantity = issueQuantity.mul(destinationTokenQuantity).div(ether(1));
const totalProtocolFee = feePercentage.mul(totalDestinationQuantity).div(ether(1));
const expectedDestinationTokenBalance = oldDestinationTokenBalance
.add(totalDestinationQuantity)
.sub(totalProtocolFee);
const newDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
it("should update the positions on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
const initialFirstPosition = (await setToken.getPositions())[0];
await subject();
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
const newSecondPosition = (await setToken.getPositions())[1];
const unitProtocolFee = feePercentage.mul(destinationTokenQuantity).div(ether(1));
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newFirstPosition.component).to.eq(sourceToken.address);
expect(newFirstPosition.unit).to.eq(initialFirstPosition.unit.sub(sourceTokenQuantity));
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
expect(newSecondPosition.component).to.eq(destinationToken.address);
expect(newSecondPosition.unit).to.eq(destinationTokenQuantity.sub(unitProtocolFee));
expect(newSecondPosition.module).to.eq(ADDRESS_ZERO);
});
});
describe("when send token is more than total position units tracked on SetToken", async () => {
let extraTokenQuantity: BigNumber;
beforeEach(async () => {
extraTokenQuantity = ether(1);
sourceToken = sourceToken.connect(owner.wallet);
// Transfer source token to SetToken
await sourceToken.transfer(setToken.address, extraTokenQuantity);
});
it("should transfer the correct components from the SetToken", async () => {
const oldSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
await subject();
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const expectedSourceTokenBalance = oldSourceTokenBalance.sub(totalSourceQuantity);
const newSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should update the positions on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
const initialFirstPosition = (await setToken.getPositions())[0];
await subject();
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
const newSecondPosition = (await setToken.getPositions())[1];
const unitProtocolFee = feePercentage.mul(destinationTokenQuantity).div(ether(1));
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newFirstPosition.component).to.eq(sourceToken.address);
expect(newFirstPosition.unit).to.eq(initialFirstPosition.unit.sub(sourceTokenQuantity));
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
expect(newSecondPosition.component).to.eq(destinationToken.address);
expect(newSecondPosition.unit).to.eq(destinationTokenQuantity.sub(unitProtocolFee));
expect(newSecondPosition.module).to.eq(ADDRESS_ZERO);
});
});
});
describe("when SetToken is locked", async () => {
beforeEach(async () => {
// Add mock module to controller
setup.controller = setup.controller.connect(owner.wallet);
await setup.controller.addModule(mockModule.address);
// Add new mock module to SetToken
setToken = setToken.connect(manager.wallet);
await setToken.addModule(mockModule.address);
// Lock SetToken
setToken = setToken.connect(mockModule.wallet);
await setToken.initializeModule();
await setToken.lock();
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("When locked, only the locker can call");
});
});
describe("when the exchange is not valid", async () => {
beforeEach(async () => {
subjectAdapterName = "NOTVALIDEXCHANGE";
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be valid adapter");
});
});
describe("when quantity of token to sell is 0", async () => {
beforeEach(async () => {
subjectSourceQuantity = ZERO;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Token to sell must be nonzero");
});
});
describe("when quantity sold is more than total units available", async () => {
beforeEach(async () => {
// Set to 1 base unit more WBTC
subjectSourceQuantity = wbtcUnits.add(1);
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Unit cant be greater than existing");
});
});
describe("when slippage is greater than allowed", async () => {
beforeEach(async () => {
// Set to 1 base unit above the exchange rate
subjectMinDestinationQuantity = wbtcRate.add(1);
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Slippage greater than allowed");
});
});
describe("when the caller is not the SetToken manager", async () => {
beforeEach(async () => {
subjectCaller = await getRandomAccount();
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be the SetToken manager");
});
});
describe("when SetToken is not valid", async () => {
beforeEach(async () => {
const nonEnabledSetToken = await setup.createNonControllerEnabledSetToken(
[setup.weth.address],
[ether(1)],
[tradeModule.address],
manager.address
);
subjectSetToken = nonEnabledSetToken.address;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be a valid and initialized SetToken");
});
});
});
describe("when module is not initialized", async () => {
beforeEach(async () => {
isInitialized = false;
await initializeContracts();
initializeSubjectVariables();
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be a valid and initialized SetToken");
});
});
});
context("when trading a Default component on Uniswap", async () => {
cacheBeforeEach(async () => {
await setup.weth.connect(owner.wallet).approve(uniswapSetup.router.address, ether(3400));
await setup.wbtc.connect(owner.wallet).approve(uniswapSetup.router.address, bitcoin(100));
await uniswapSetup.router.addLiquidity(
setup.weth.address,
setup.wbtc.address,
ether(3400),
bitcoin(100),
ether(3395),
ether(99.5),
owner.address,
MAX_UINT_256
);
tradeModule = tradeModule.connect(manager.wallet);
await tradeModule.initialize(setToken.address);
sourceTokenQuantity = wbtcUnits;
const sourceTokenDecimals = await sourceToken.decimals();
destinationTokenQuantity = wbtcRate.mul(sourceTokenQuantity).div(10 ** sourceTokenDecimals);
// Transfer sourceToken from owner to manager for issuance
sourceToken = sourceToken.connect(owner.wallet);
await sourceToken.transfer(manager.address, wbtcUnits.mul(100));
// Approve tokens to Controller and call issue
sourceToken = sourceToken.connect(manager.wallet);
await sourceToken.approve(setup.issuanceModule.address, ethers.constants.MaxUint256);
// Deploy mock issuance hook and initialize issuance module
setup.issuanceModule = setup.issuanceModule.connect(manager.wallet);
mockPreIssuanceHook = await deployer.mocks.deployManagerIssuanceHookMock();
await setup.issuanceModule.initialize(setToken.address, mockPreIssuanceHook.address);
issueQuantity = ether(1);
await setup.issuanceModule.issue(setToken.address, issueQuantity, owner.address);
});
beforeEach(() => {
subjectSourceToken = sourceToken.address;
subjectDestinationToken = destinationToken.address;
subjectSourceQuantity = sourceTokenQuantity;
subjectSetToken = setToken.address;
subjectAdapterName = uniswapAdapterName;
subjectData = EMPTY_BYTES;
subjectMinDestinationQuantity = destinationTokenQuantity.sub(ether(1)); // Receive a min of 32 WETH for 1 WBTC
subjectCaller = manager;
});
async function subject(): Promise<any> {
tradeModule = tradeModule.connect(subjectCaller.wallet);
return tradeModule.trade(
subjectSetToken,
subjectAdapterName,
subjectSourceToken,
subjectSourceQuantity,
subjectDestinationToken,
subjectMinDestinationQuantity,
subjectData
);
}
it("should transfer the correct components to the SetToken", async () => {
const oldDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
const [, expectedReceiveQuantity] = await uniswapSetup.router.getAmountsOut(
subjectSourceQuantity,
[subjectSourceToken, subjectDestinationToken]
);
await subject();
const expectedDestinationTokenBalance = oldDestinationTokenBalance.add(expectedReceiveQuantity);
const newDestinationTokenBalance = await destinationToken.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
it("should transfer the correct components from the SetToken", async () => {
const oldSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
await subject();
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const expectedSourceTokenBalance = oldSourceTokenBalance.sub(totalSourceQuantity);
const newSourceTokenBalance = await sourceToken.balanceOf(setToken.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should update the positions on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
const [, expectedReceiveQuantity] = await uniswapSetup.router.getAmountsOut(
subjectSourceQuantity,
[subjectSourceToken, subjectDestinationToken]
);
await subject();
// All WBTC is sold for WETH
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(1);
expect(newFirstPosition.component).to.eq(destinationToken.address);
expect(newFirstPosition.unit).to.eq(expectedReceiveQuantity);
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
});
describe("when path is through multiple trading pairs", async () => {
beforeEach(async () => {
await setup.weth.connect(owner.wallet).approve(uniswapSetup.router.address, ether(1000));
await setup.dai.connect(owner.wallet).approve(uniswapSetup.router.address, ether(1000000));
await uniswapSetup.router.addLiquidity(
setup.weth.address,
setup.dai.address,
ether(1000),
ether(1000000),
ether(995),
ether(995000),
owner.address,
MAX_UINT_256
);
subjectDestinationToken = setup.dai.address;
const tradePath = [subjectSourceToken, setup.weth.address, subjectDestinationToken];
subjectData = utils.defaultAbiCoder.encode(
["address[]"],
[tradePath]
);
});
it("should transfer the correct components to the SetToken", async () => {
const oldDestinationTokenBalance = await setup.dai.balanceOf(setToken.address);
const [, , expectedReceiveQuantity] = await uniswapSetup.router.getAmountsOut(
subjectSourceQuantity,
[subjectSourceToken, setup.weth.address, subjectDestinationToken]
);
await subject();
const expectedDestinationTokenBalance = oldDestinationTokenBalance.add(expectedReceiveQuantity);
const newDestinationTokenBalance = await setup.dai.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
});
});
context("when trading a Default component with a transfer fee on Uniswap", async () => {
cacheBeforeEach(async () => {
tokenWithFee = await deployer.mocks.deployTokenWithFeeMock(owner.address, ether(10000), ether(0.01));
await tokenWithFee.connect(owner.wallet).approve(uniswapSetup.router.address, ether(10000));
await setup.wbtc.connect(owner.wallet).approve(uniswapSetup.router.address, bitcoin(100));
const poolPair = await uniswapSetup.createNewPair(tokenWithFee.address, setup.wbtc.address);
await uniswapSetup.router.addLiquidity(
tokenWithFee.address,
setup.wbtc.address,
ether(3400),
bitcoin(100),
ether(3000),
bitcoin(99.5),
owner.address,
MAX_UINT_256
);
await tokenWithFee.transfer(poolPair.address, ether(0.01));
tradeModule = tradeModule.connect(manager.wallet);
await tradeModule.initialize(setToken.address);
const wbtcSendQuantity = wbtcUnits;
const destinationTokenDecimals = await setup.wbtc.decimals();
sourceTokenQuantity = wbtcRate.mul(wbtcSendQuantity).div(10 ** destinationTokenDecimals);
// Transfer sourceToken from owner to manager for issuance
await setup.wbtc.connect(owner.wallet).transfer(manager.address, wbtcUnits.mul(100));
// Approve tokens to Controller and call issue
await setup.wbtc.connect(manager.wallet).approve(setup.issuanceModule.address, ethers.constants.MaxUint256);
// Deploy mock issuance hook and initialize issuance module
setup.issuanceModule = setup.issuanceModule.connect(manager.wallet);
mockPreIssuanceHook = await deployer.mocks.deployManagerIssuanceHookMock();
await setup.issuanceModule.initialize(setToken.address, mockPreIssuanceHook.address);
issueQuantity = ether(1);
await setup.issuanceModule.issue(setToken.address, issueQuantity, owner.address);
// Trade into token with fee
await tradeModule.connect(manager.wallet).trade(
setToken.address,
uniswapTransferFeeAdapterName,
setup.wbtc.address,
wbtcSendQuantity,
tokenWithFee.address,
ZERO,
EMPTY_BYTES
);
});
beforeEach(() => {
// Trade token with fee back to WBTC
subjectSourceToken = tokenWithFee.address;
subjectDestinationToken = setup.wbtc.address;
subjectSourceQuantity = sourceTokenQuantity;
subjectSetToken = setToken.address;
subjectAdapterName = uniswapTransferFeeAdapterName;
subjectData = EMPTY_BYTES;
subjectMinDestinationQuantity = ZERO;
subjectCaller = manager;
});
async function subject(): Promise<any> {
tradeModule = tradeModule.connect(subjectCaller.wallet);
return tradeModule.trade(
subjectSetToken,
subjectAdapterName,
subjectSourceToken,
subjectSourceQuantity,
subjectDestinationToken,
subjectMinDestinationQuantity,
subjectData
);
}
it("should transfer the correct components to the SetToken", async () => {
const oldDestinationTokenBalance = await setup.wbtc.balanceOf(setToken.address);
const [, expectedReceiveQuantity] = await uniswapSetup.router.getAmountsOut(
subjectSourceQuantity.sub(ether(0.01)), // Sub transfer fee
[subjectSourceToken, subjectDestinationToken]
);
await subject();
const expectedDestinationTokenBalance = oldDestinationTokenBalance.add(expectedReceiveQuantity);
const newDestinationTokenBalance = await setup.wbtc.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
it("should transfer the correct components from the SetToken", async () => {
const oldSourceTokenBalance = await tokenWithFee.balanceOf(setToken.address);
await subject();
const totalSourceQuantity = issueQuantity.mul(sourceTokenQuantity).div(ether(1));
const expectedSourceTokenBalance = oldSourceTokenBalance.sub(totalSourceQuantity);
const newSourceTokenBalance = await tokenWithFee.balanceOf(setToken.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should update the positions on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
const [, expectedReceiveQuantity] = await uniswapSetup.router.getAmountsOut(
subjectSourceQuantity.sub(ether(0.01)), // Sub transfer fee
[subjectSourceToken, subjectDestinationToken]
);
await subject();
// All WBTC is sold for WETH
const currentPositions = await setToken.getPositions();
const newSecondPosition = (await setToken.getPositions())[1];
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newSecondPosition.component).to.eq(subjectDestinationToken);
expect(newSecondPosition.unit).to.eq(expectedReceiveQuantity);
expect(newSecondPosition.module).to.eq(ADDRESS_ZERO);
});
describe("when path is through multiple trading pairs", async () => {
beforeEach(async () => {
await setup.wbtc.connect(owner.wallet).approve(uniswapSetup.router.address, bitcoin(1000));
await setup.dai.connect(owner.wallet).approve(uniswapSetup.router.address, ether(1000000));
await uniswapSetup.router.addLiquidity(
setup.wbtc.address,
setup.dai.address,
bitcoin(10),
ether(1000000),
ether(995),
ether(995000),
owner.address,
MAX_UINT_256
);
subjectDestinationToken = setup.dai.address;
const tradePath = [subjectSourceToken, setup.wbtc.address, subjectDestinationToken];
subjectData = utils.defaultAbiCoder.encode(
["address[]"],
[tradePath]
);
});
it("should transfer the correct components to the SetToken", async () => {
const oldDestinationTokenBalance = await setup.dai.balanceOf(setToken.address);
const [, , expectedReceiveQuantity] = await uniswapSetup.router.getAmountsOut(
subjectSourceQuantity.sub(ether(0.01)), // Sub transfer fee
[subjectSourceToken, setup.wbtc.address, subjectDestinationToken]
);
await subject();
const expectedDestinationTokenBalance = oldDestinationTokenBalance.add(expectedReceiveQuantity);
const newDestinationTokenBalance = await setup.dai.balanceOf(setToken.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);