-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathaaveLeverageModule.spec.ts
More file actions
3959 lines (3271 loc) · 148 KB
/
aaveLeverageModule.spec.ts
File metadata and controls
3959 lines (3271 loc) · 148 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 { Address, Bytes } from "@utils/types";
import { Account } from "@utils/test/types";
import {
AaveV2,
AaveLeverageModule,
DebtIssuanceMock,
OneInchExchangeAdapter,
OneInchExchangeMock,
SetToken,
UniswapV2ExchangeAdapterV2
} from "@utils/contracts";
import {
AaveV2AToken,
AaveV2VariableDebtToken
} from "@utils/contracts/aaveV2";
import DeployHelper from "@utils/deploys";
import {
ether,
preciseDiv,
preciseMul
} from "@utils/index";
import {
cacheBeforeEach,
getAccounts,
getWaffleExpect,
getSystemFixture,
getAaveV2Fixture,
getRandomAccount,
getRandomAddress,
getUniswapFixture
} from "@utils/test/index";
import { AaveV2Fixture, SystemFixture, UniswapFixture } from "@utils/fixtures";
import { BigNumber, ContractTransaction } from "ethers";
import { ADDRESS_ZERO, ZERO, EMPTY_BYTES, MAX_UINT_256 } from "@utils/constants";
import { ReserveTokens } from "@utils/fixtures/aaveV2Fixture";
const expect = getWaffleExpect();
const web3 = new Web3();
describe("AaveLeverageModule", () => {
let owner: Account;
let mockModule: Account;
let deployer: DeployHelper;
let setup: SystemFixture;
let aaveSetup: AaveV2Fixture;
let aaveV2Library: AaveV2;
let aaveLeverageModule: AaveLeverageModule;
let debtIssuanceMock: DebtIssuanceMock;
let aWETH: AaveV2AToken;
let aDAI: AaveV2AToken;
let variableDebtWETH: AaveV2VariableDebtToken;
let variableDebtDAI: AaveV2VariableDebtToken;
let oneInchFunctionSignature: Bytes;
let oneInchExchangeMockToWeth: OneInchExchangeMock;
let oneInchExchangeMockFromWeth: OneInchExchangeMock;
let oneInchExchangeMockWithSlippage: OneInchExchangeMock;
let oneInchExchangeMockOneWei: OneInchExchangeMock;
let oneInchExchangeAdapterToWeth: OneInchExchangeAdapter;
let oneInchExchangeAdapterFromWeth: OneInchExchangeAdapter;
cacheBeforeEach(async () => {
[
owner,
mockModule,
] = await getAccounts();
deployer = new DeployHelper(owner.wallet);
setup = getSystemFixture(owner.address);
await setup.initialize();
aaveSetup = getAaveV2Fixture(owner.address);
await aaveSetup.initialize(setup.weth.address, setup.dai.address);
// Create a WBTC reserve
await aaveSetup.createAndEnableReserve(
setup.wbtc.address, "WBTC", BigNumber.from(18),
BigNumber.from(8000), // base LTV: 80%
BigNumber.from(8250), // liquidation threshold: 82.5%
BigNumber.from(10500), // liquidation bonus: 105.00%
BigNumber.from(1000), // reserve factor: 10%
true, // enable borrowing on reserve
true // enable stable debts
);
// Create liquidity
const ape = await getRandomAccount(); // The wallet which aped in first and added initial liquidity
await setup.weth.transfer(ape.address, ether(50));
await setup.weth.connect(ape.wallet).approve(aaveSetup.lendingPool.address, ether(50));
await aaveSetup.lendingPool.connect(ape.wallet).deposit(
setup.weth.address,
ether(50),
ape.address,
ZERO
);
await setup.dai.transfer(ape.address, ether(50000));
await setup.dai.connect(ape.wallet).approve(aaveSetup.lendingPool.address, ether(50000));
await aaveSetup.lendingPool.connect(ape.wallet).deposit(
setup.dai.address,
ether(50000),
ape.address,
ZERO
);
aWETH = aaveSetup.wethReserveTokens.aToken;
variableDebtWETH = aaveSetup.wethReserveTokens.variableDebtToken;
aDAI = aaveSetup.daiReserveTokens.aToken;
variableDebtDAI = aaveSetup.daiReserveTokens.variableDebtToken;
debtIssuanceMock = await deployer.mocks.deployDebtIssuanceMock();
await setup.controller.addModule(debtIssuanceMock.address);
aaveV2Library = await deployer.libraries.deployAaveV2();
aaveLeverageModule = await deployer.modules.deployAaveLeverageModule(
setup.controller.address,
aaveSetup.lendingPoolAddressesProvider.address,
"contracts/protocol/integration/lib/AaveV2.sol:AaveV2",
aaveV2Library.address,
);
await setup.controller.addModule(aaveLeverageModule.address);
// Deploy 1inch mock contracts
// 1inch function signature
oneInchFunctionSignature = web3.eth.abi.encodeFunctionSignature(
"swap(address,address,uint256,uint256,uint256,address,address[],bytes,uint256[],uint256[])"
);
// Mock OneInch exchange that allows for fixed exchange amounts. So we need to setup separate exchange adapters
oneInchExchangeMockToWeth = await deployer.mocks.deployOneInchExchangeMock(
setup.dai.address,
setup.weth.address,
ether(1000), // 1000 DAI
ether(1), // Trades for 1 WETH
);
oneInchExchangeAdapterToWeth = await deployer.adapters.deployOneInchExchangeAdapter(
oneInchExchangeMockToWeth.address,
oneInchExchangeMockToWeth.address,
oneInchFunctionSignature
);
await setup.integrationRegistry.addIntegration(
aaveLeverageModule.address,
"ONEINCHTOWETH",
oneInchExchangeAdapterToWeth.address
);
oneInchExchangeMockFromWeth = await deployer.mocks.deployOneInchExchangeMock(
setup.weth.address,
setup.dai.address,
ether(1), // 1 WETH
ether(1000), // Trades for 1000 DAI
);
oneInchExchangeAdapterFromWeth = await deployer.adapters.deployOneInchExchangeAdapter(
oneInchExchangeMockFromWeth.address,
oneInchExchangeMockFromWeth.address,
oneInchFunctionSignature
);
await setup.integrationRegistry.addIntegration(
aaveLeverageModule.address,
"ONEINCHFROMWETH",
oneInchExchangeAdapterFromWeth.address
);
// Setup Mock 1inch exchange that does not return sufficient units to satisfy slippage requirement
oneInchExchangeMockWithSlippage = await deployer.mocks.deployOneInchExchangeMock(
setup.dai.address,
setup.weth.address,
ether(1000), // 1000 DAI
ether(0.9), // Trades for 0.9 WETH
);
const oneInchExchangeAdapterWithSlippage = await deployer.adapters.deployOneInchExchangeAdapter(
oneInchExchangeMockWithSlippage.address,
oneInchExchangeMockWithSlippage.address,
oneInchFunctionSignature
);
await setup.integrationRegistry.addIntegration(
aaveLeverageModule.address,
"ONEINCHSLIPPAGE",
oneInchExchangeAdapterWithSlippage.address
);
// Setup Mock 1inch exchange that takes in 1 wei of DAI
oneInchExchangeMockOneWei = await deployer.mocks.deployOneInchExchangeMock(
setup.dai.address,
setup.weth.address,
BigNumber.from(1), // 1 wei of DAI
ether(1), // Trades for 1 WETH
);
const oneInchExchangeAdapterOneWei = await deployer.adapters.deployOneInchExchangeAdapter(
oneInchExchangeMockOneWei.address,
oneInchExchangeMockOneWei.address,
oneInchFunctionSignature
);
await setup.integrationRegistry.addIntegration(
aaveLeverageModule.address,
"ONEINCHWEI",
oneInchExchangeAdapterOneWei.address
);
// Add debt issuance address to integration
await setup.integrationRegistry.addIntegration(
aaveLeverageModule.address,
"DefaultIssuanceModule",
debtIssuanceMock.address
);
});
describe("#constructor", async () => {
let subjectController: Address;
let subjectLendingPoolAddressesProvider: Address;
beforeEach(async () => {
subjectController = setup.controller.address;
subjectLendingPoolAddressesProvider = aaveSetup.lendingPoolAddressesProvider.address;
});
async function subject(): Promise<AaveLeverageModule> {
return deployer.modules.deployAaveLeverageModule(
subjectController,
subjectLendingPoolAddressesProvider,
"contracts/protocol/integration/lib/AaveV2.sol:AaveV2",
aaveV2Library.address
);
}
it("should set the correct controller", async () => {
const aaveLeverageModule = await subject();
const controller = await aaveLeverageModule.controller();
expect(controller).to.eq(subjectController);
});
it("should set the correct Aave contracts", async () => {
const aaveLeverageModule = await subject();
const lendingPoolAddressesProvider = await aaveLeverageModule.lendingPoolAddressesProvider();
const protocolDataProvider = await aaveLeverageModule.protocolDataProvider();
expect(lendingPoolAddressesProvider).to.eq(aaveSetup.lendingPoolAddressesProvider.address);
expect(protocolDataProvider).to.eq(aaveSetup.protocolDataProvider.address);
});
it("should set the correct underlying to reserve tokens mappings", async () => {
const aaveLeverageModule = await subject();
const wethReserveTokens = await aaveLeverageModule.underlyingToReserveTokens(setup.weth.address);
const daiReserveTokens = await aaveLeverageModule.underlyingToReserveTokens(setup.dai.address);
expect(wethReserveTokens.aToken).to.eq(aWETH.address);
expect(wethReserveTokens.variableDebtToken).to.eq(aaveSetup.wethReserveTokens.variableDebtToken.address);
expect(daiReserveTokens.aToken).to.eq(aaveSetup.daiReserveTokens.aToken.address);
expect(daiReserveTokens.variableDebtToken).to.eq(aaveSetup.daiReserveTokens.variableDebtToken.address);
});
});
describe("#initialize", async () => {
let setToken: SetToken;
let isAllowListed: boolean;
let subjectSetToken: Address;
let subjectCollateralAssets: Address[];
let subjectBorrowAssets: Address[];
let subjectCaller: Account;
const initializeContracts = async () => {
setToken = await setup.createSetToken(
[setup.weth.address, setup.dai.address],
[ether(1), ether(100)],
[aaveLeverageModule.address, debtIssuanceMock.address]
);
await debtIssuanceMock.initialize(setToken.address);
if (isAllowListed) {
// Add SetToken to allow list
await aaveLeverageModule.updateAllowedSetToken(setToken.address, true);
}
};
const initializeSubjectVariables = () => {
subjectSetToken = setToken.address;
subjectCollateralAssets = [setup.weth.address, setup.dai.address];
subjectBorrowAssets = [setup.dai.address, setup.weth.address];
subjectCaller = owner;
};
async function subject(): Promise<any> {
return aaveLeverageModule.connect(subjectCaller.wallet).initialize(
subjectSetToken,
subjectCollateralAssets,
subjectBorrowAssets
);
}
describe("when isAllowListed is true", () => {
before(async () => {
isAllowListed = true;
});
cacheBeforeEach(initializeContracts);
beforeEach(initializeSubjectVariables);
it("should enable the Module on the SetToken", async () => {
await subject();
const isModuleEnabled = await setToken.isInitializedModule(aaveLeverageModule.address);
expect(isModuleEnabled).to.eq(true);
});
it("should set the Aave settings and mappings", async () => {
await subject();
const enabledAssets = await aaveLeverageModule.getEnabledAssets(setToken.address);
const [collateralAssets, borrowAssets] = enabledAssets;
const isWethCollateral = await aaveLeverageModule.collateralAssetEnabled(setToken.address, setup.weth.address);
const isDaiCollateral = await aaveLeverageModule.collateralAssetEnabled(setToken.address, setup.dai.address);
const isDaiBorrow = await aaveLeverageModule.borrowAssetEnabled(setToken.address, setup.dai.address);
const isWethBorrow = await aaveLeverageModule.borrowAssetEnabled(setToken.address, setup.weth.address);
expect(JSON.stringify(collateralAssets)).to.eq(JSON.stringify(subjectCollateralAssets));
expect(JSON.stringify(borrowAssets)).to.eq(JSON.stringify(subjectBorrowAssets));
expect(isWethCollateral).to.be.true;
expect(isDaiCollateral).to.be.true;
expect(isDaiBorrow).to.be.true;
expect(isWethBorrow).to.be.true;
});
it("should register on the debt issuance module", async () => {
await subject();
const isRegistered = await debtIssuanceMock.isRegistered(setToken.address);
expect(isRegistered).to.be.true;
});
describe("when debt issuance module is not added to integration registry", async () => {
beforeEach(async () => {
await setup.integrationRegistry.removeIntegration(aaveLeverageModule.address, "DefaultIssuanceModule");
});
afterEach(async () => {
// Add debt issuance address to integration
await setup.integrationRegistry.addIntegration(
aaveLeverageModule.address,
"DefaultIssuanceModule",
debtIssuanceMock.address
);
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be valid adapter");
});
});
describe("when debt issuance module is not initialized on SetToken", async () => {
beforeEach(async () => {
await setToken.removeModule(debtIssuanceMock.address);
});
afterEach(async () => {
await setToken.addModule(debtIssuanceMock.address);
await debtIssuanceMock.initialize(setToken.address);
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Issuance not initialized");
});
});
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 in pending state", async () => {
beforeEach(async () => {
const newModule = await getRandomAddress();
await setup.controller.addModule(newModule);
const aaveLeverageModuleNotPendingSetToken = await setup.createSetToken(
[setup.weth.address],
[ether(1)],
[newModule]
);
subjectSetToken = aaveLeverageModuleNotPendingSetToken.address;
});
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.weth.address],
[ether(1)],
[aaveLeverageModule.address]
);
subjectSetToken = nonEnabledSetToken.address;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be controller-enabled SetToken");
});
});
});
describe("when isAllowListed is false", async () => {
before(async () => {
isAllowListed = false;
});
cacheBeforeEach(initializeContracts);
beforeEach(initializeSubjectVariables);
describe("when SetToken is not allowlisted", async () => {
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Not allowed SetToken");
});
});
describe("when any Set can initialize this module", async () => {
beforeEach(async () => {
await aaveLeverageModule.updateAnySetAllowed(true);
});
it("should enable the Module on the SetToken", async () => {
await subject();
const isModuleEnabled = await setToken.isInitializedModule(aaveLeverageModule.address);
expect(isModuleEnabled).to.eq(true);
});
});
});
});
describe("#lever", async () => {
let setToken: SetToken;
let isInitialized: boolean;
let destinationTokenQuantity: BigNumber;
let subjectSetToken: Address;
let subjectBorrowAsset: Address;
let subjectCollateralAsset: Address;
let subjectBorrowQuantity: BigNumber;
let subjectMinCollateralQuantity: BigNumber;
let subjectTradeAdapterName: string;
let subjectTradeData: Bytes;
let subjectCaller: Account;
context("when aWETH is collateral asset and borrow positions is 0", async () => {
const initializeContracts = async () => {
setToken = await setup.createSetToken(
[aWETH.address],
[ether(2)],
[aaveLeverageModule.address, debtIssuanceMock.address, setup.issuanceModule.address]
);
await debtIssuanceMock.initialize(setToken.address);
// Add SetToken to allow list
await aaveLeverageModule.updateAllowedSetToken(setToken.address, true);
// Initialize module if set to true
if (isInitialized) {
await aaveLeverageModule.initialize(
setToken.address,
[setup.weth.address, setup.dai.address],
[setup.dai.address, setup.weth.address]
);
}
await setup.issuanceModule.initialize(setToken.address, ADDRESS_ZERO);
// Add Set token as token sender / recipient
oneInchExchangeMockToWeth = oneInchExchangeMockToWeth.connect(owner.wallet);
await oneInchExchangeMockToWeth.addSetTokenAddress(setToken.address);
// Fund One Inch exchange with destinationToken WETH
await setup.weth.transfer(oneInchExchangeMockToWeth.address, ether(10));
// Mint aTokens
await setup.weth.approve(aaveSetup.lendingPool.address, ether(1000));
await aaveSetup.lendingPool.connect(owner.wallet).deposit(setup.weth.address, ether(1000), owner.address, ZERO);
// await setup.dai.approve(aaveSetup.lendingPool.address, ether(10000));
// await aaveSetup.lendingPool.connect(owner.wallet).deposit(setup.dai.address, ether(10000), owner.address, ZERO);
// Approve tokens to issuance module and call issue
await aWETH.approve(setup.issuanceModule.address, ether(1000));
// Issue 1 SetToken. Note: 1inch mock is hardcoded to trade 1000 DAI regardless of Set supply
const issueQuantity = ether(1);
destinationTokenQuantity = ether(1);
await setup.issuanceModule.issue(setToken.address, issueQuantity, owner.address);
};
const initializeSubjectVariables = () => {
subjectSetToken = setToken.address;
subjectBorrowAsset = setup.dai.address;
subjectCollateralAsset = setup.weth.address;
subjectBorrowQuantity = ether(1000);
subjectMinCollateralQuantity = destinationTokenQuantity;
subjectTradeAdapterName = "ONEINCHTOWETH";
subjectTradeData = oneInchExchangeMockToWeth.interface.encodeFunctionData("swap", [
setup.dai.address, // Send token
setup.weth.address, // Receive token
subjectBorrowQuantity, // Send quantity
subjectMinCollateralQuantity, // Min receive quantity
ZERO,
ADDRESS_ZERO,
[ADDRESS_ZERO],
EMPTY_BYTES,
[ZERO],
[ZERO],
]);
subjectCaller = owner;
};
async function subject(): Promise<any> {
return aaveLeverageModule.connect(subjectCaller.wallet).lever(
subjectSetToken,
subjectBorrowAsset,
subjectCollateralAsset,
subjectBorrowQuantity,
subjectMinCollateralQuantity,
subjectTradeAdapterName,
subjectTradeData
);
}
describe("when module is initialized", async () => {
before(async () => {
isInitialized = true;
});
cacheBeforeEach(initializeContracts);
beforeEach(initializeSubjectVariables);
it("should update the collateral position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// cWETH position is increased
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
const expectedFirstPositionUnit = initialPositions[0].unit.add(destinationTokenQuantity);
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2); // added a new borrow position
expect(newFirstPosition.component).to.eq(aWETH.address);
expect(newFirstPosition.positionState).to.eq(0); // Default
expect(newFirstPosition.unit).to.eq(expectedFirstPositionUnit);
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
});
it("should update the borrow position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// cEther position is increased
const currentPositions = await setToken.getPositions();
const newSecondPosition = (await setToken.getPositions())[1];
const expectedSecondPositionUnit = (await variableDebtDAI.balanceOf(setToken.address)).mul(-1);
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newSecondPosition.component).to.eq(setup.dai.address);
expect(newSecondPosition.positionState).to.eq(1); // External
expect(newSecondPosition.unit).to.eq(expectedSecondPositionUnit);
expect(newSecondPosition.module).to.eq(aaveLeverageModule.address);
});
it("should transfer the correct components to the exchange", async () => {
const oldSourceTokenBalance = await setup.dai.balanceOf(oneInchExchangeMockToWeth.address);
await subject();
const totalSourceQuantity = subjectBorrowQuantity;
const expectedSourceTokenBalance = oldSourceTokenBalance.add(totalSourceQuantity);
const newSourceTokenBalance = await setup.dai.balanceOf(oneInchExchangeMockToWeth.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should transfer the correct components from the exchange", async () => {
const oldDestinationTokenBalance = await setup.weth.balanceOf(oneInchExchangeMockToWeth.address);
await subject();
const totalDestinationQuantity = destinationTokenQuantity;
const expectedDestinationTokenBalance = oldDestinationTokenBalance.sub(totalDestinationQuantity);
const newDestinationTokenBalance = await setup.weth.balanceOf(oneInchExchangeMockToWeth.address);
expect(newDestinationTokenBalance).to.eq(expectedDestinationTokenBalance);
});
describe("when the leverage position has been liquidated", async () => {
let ethSeized: BigNumber;
cacheBeforeEach(async () => {
// Lever up
await aaveLeverageModule.connect(subjectCaller.wallet).lever(
subjectSetToken,
subjectBorrowAsset,
subjectCollateralAsset,
subjectBorrowQuantity,
subjectMinCollateralQuantity,
subjectTradeAdapterName,
subjectTradeData
);
// ETH decreases to $250
const liquidationDaiPriceInEth = ether(0.004); // 1/250 = 0.004
await aaveSetup.setAssetPriceInOracle(setup.dai.address, liquidationDaiPriceInEth);
// Seize 1 ETH + liquidation bonus by repaying debt of 250 DAI
ethSeized = ether(1);
const debtToCover = ether(250);
await setup.dai.approve(aaveSetup.lendingPool.address, ether(250));
await aaveSetup.lendingPool.connect(owner.wallet).liquidationCall(
setup.weth.address,
setup.dai.address,
setToken.address,
debtToCover,
true
);
// ETH increases to $1250 to allow more borrow
await aaveSetup.setAssetPriceInOracle(setup.dai.address, ether(0.0008)); // 1/1250 = .0008
subjectBorrowQuantity = ether(1000);
});
it("should transfer the correct components to the exchange", async () => {
const oldSourceTokenBalance = await setup.dai.balanceOf(oneInchExchangeMockToWeth.address);
await subject();
const totalSourceQuantity = subjectBorrowQuantity;
const expectedSourceTokenBalance = oldSourceTokenBalance.add(totalSourceQuantity);
const newSourceTokenBalance = await setup.dai.balanceOf(oneInchExchangeMockToWeth.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should update the collateral position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// aWETH position is increased
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
// Get expected aTokens minted
const newUnits = destinationTokenQuantity;
const aaveLiquidationBonus = (await aaveSetup.protocolDataProvider.getReserveConfigurationData(setup.weth.address)).liquidationBonus;
const liquidatedEth = preciseDiv(preciseMul(ethSeized, aaveLiquidationBonus), BigNumber.from(10000)); // ethSeized * 105%
const expectedPostLiquidationUnit = initialPositions[0].unit.sub(liquidatedEth).add(newUnits);
expect(initialPositions.length).to.eq(2);
expect(currentPositions.length).to.eq(2);
expect(newFirstPosition.component).to.eq(aWETH.address);
expect(newFirstPosition.positionState).to.eq(0); // Default
expect(newFirstPosition.unit).to.eq(expectedPostLiquidationUnit);
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
});
it("should update the borrow position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// cEther position is increased
const currentPositions = await setToken.getPositions();
const newSecondPosition = (await setToken.getPositions())[1];
const expectedSecondPositionUnit = (await variableDebtDAI.balanceOf(setToken.address)).mul(-1);
expect(initialPositions.length).to.eq(2);
expect(currentPositions.length).to.eq(2);
expect(newSecondPosition.component).to.eq(setup.dai.address);
expect(newSecondPosition.positionState).to.eq(1); // External
expect(newSecondPosition.unit).to.eq(expectedSecondPositionUnit);
expect(newSecondPosition.module).to.eq(aaveLeverageModule.address);
});
});
describe("when there is a protocol fee charged", async () => {
let feePercentage: BigNumber;
cacheBeforeEach(async () => {
feePercentage = ether(0.05);
setup.controller = setup.controller.connect(owner.wallet);
await setup.controller.addFee(
aaveLeverageModule.address,
ZERO, // Fee type on trade function denoted as 0
feePercentage // Set fee to 5 bps
);
});
it("should transfer the correct components to the exchange", async () => {
const oldSourceTokenBalance = await setup.dai.balanceOf(oneInchExchangeMockToWeth.address);
await subject();
const totalSourceQuantity = subjectBorrowQuantity;
const expectedSourceTokenBalance = oldSourceTokenBalance.add(totalSourceQuantity);
const newSourceTokenBalance = await setup.dai.balanceOf(oneInchExchangeMockToWeth.address);
expect(newSourceTokenBalance).to.eq(expectedSourceTokenBalance);
});
it("should transfer the correct protocol fee to the protocol", async () => {
const feeRecipient = await setup.controller.feeRecipient();
const oldFeeRecipientBalance = await setup.weth.balanceOf(feeRecipient);
await subject();
const expectedFeeRecipientBalance = oldFeeRecipientBalance.add(preciseMul(feePercentage, destinationTokenQuantity));
const newFeeRecipientBalance = await setup.weth.balanceOf(feeRecipient);
expect(newFeeRecipientBalance).to.eq(expectedFeeRecipientBalance);
});
it("should update the collateral position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// cEther position is increased
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
// Get expected cTokens minted
const unitProtocolFee = feePercentage.mul(destinationTokenQuantity).div(ether(1));
const newUnits = destinationTokenQuantity.sub(unitProtocolFee);
const expectedFirstPositionUnit = initialPositions[0].unit.add(newUnits);
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newFirstPosition.component).to.eq(aWETH.address);
expect(newFirstPosition.positionState).to.eq(0); // Default
expect(newFirstPosition.unit).to.eq(expectedFirstPositionUnit);
expect(newFirstPosition.module).to.eq(ADDRESS_ZERO);
});
it("should update the borrow position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// cEther position is increased
const currentPositions = await setToken.getPositions();
const newSecondPosition = (await setToken.getPositions())[1];
const expectedSecondPositionUnit = (await variableDebtDAI.balanceOf(setToken.address)).mul(-1);
expect(initialPositions.length).to.eq(1);
expect(currentPositions.length).to.eq(2);
expect(newSecondPosition.component).to.eq(setup.dai.address);
expect(newSecondPosition.positionState).to.eq(1); // External
expect(newSecondPosition.unit).to.eq(expectedSecondPositionUnit);
expect(newSecondPosition.module).to.eq(aaveLeverageModule.address);
});
it("should emit the correct LeverageIncreased event", async () => {
const totalBorrowQuantity = subjectBorrowQuantity;
const totalCollateralQuantity = destinationTokenQuantity;
const totalProtocolFee = feePercentage.mul(totalCollateralQuantity).div(ether(1));
await expect(subject()).to.emit(aaveLeverageModule, "LeverageIncreased").withArgs(
setToken.address,
subjectBorrowAsset,
subjectCollateralAsset,
oneInchExchangeAdapterToWeth.address,
totalBorrowQuantity,
totalCollateralQuantity.sub(totalProtocolFee),
totalProtocolFee
);
});
});
describe("when slippage is greater than allowed", async () => {
cacheBeforeEach(async () => {
// Add Set token as token sender / recipient
oneInchExchangeMockWithSlippage = oneInchExchangeMockWithSlippage.connect(owner.wallet);
await oneInchExchangeMockWithSlippage.addSetTokenAddress(setToken.address);
// Fund One Inch exchange with destinationToken WETH
await setup.weth.transfer(oneInchExchangeMockWithSlippage.address, ether(10));
// Set to other mock exchange adapter with slippage
subjectTradeAdapterName = "ONEINCHSLIPPAGE";
subjectTradeData = oneInchExchangeMockWithSlippage.interface.encodeFunctionData("swap", [
setup.dai.address, // Send token
setup.weth.address, // Receive token
subjectBorrowQuantity, // Send quantity
subjectMinCollateralQuantity, // Min receive quantity
ZERO,
ADDRESS_ZERO,
[ADDRESS_ZERO],
EMPTY_BYTES,
[ZERO],
[ZERO],
]);
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Slippage too high");
});
});
describe("when the exchange is not valid", async () => {
beforeEach(async () => {
subjectTradeAdapterName = "UNISWAP";
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Must be valid adapter");
});
});
describe("when collateral asset is not enabled", async () => {
beforeEach(async () => {
subjectCollateralAsset = setup.wbtc.address;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Collateral not enabled");
});
});
describe("when borrow asset is not enabled", async () => {
beforeEach(async () => {
subjectBorrowAsset = await getRandomAddress();
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Borrow not enabled");
});
});
describe("when borrow asset is same as collateral asset", async () => {
beforeEach(async () => {
subjectBorrowAsset = setup.weth.address;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Collateral and borrow asset must be different");
});
});
describe("when quantity of token to sell is 0", async () => {
beforeEach(async () => {
subjectBorrowQuantity = ZERO;
});
it("should revert", async () => {
await expect(subject()).to.be.revertedWith("Quantity is 0");
});
});
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)],
[aaveLeverageModule.address],
owner.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 DAI is borrow asset, and is a default position", async () => {
before(async () => {
isInitialized = true;
});
cacheBeforeEach(async () => {
setToken = await setup.createSetToken(
[aWETH.address, setup.dai.address],
[ether(2), ether(1)],
[aaveLeverageModule.address, debtIssuanceMock.address, setup.issuanceModule.address]
);
await debtIssuanceMock.initialize(setToken.address);
// Add SetToken to allow list
await aaveLeverageModule.updateAllowedSetToken(setToken.address, true);
// Initialize module if set to true
if (isInitialized) {
await aaveLeverageModule.initialize(
setToken.address,
[setup.weth.address, setup.dai.address],
[setup.dai.address, setup.weth.address]
);
}
await setup.issuanceModule.initialize(setToken.address, ADDRESS_ZERO);
// Add Set token as token sender / recipient
oneInchExchangeMockToWeth = oneInchExchangeMockToWeth.connect(owner.wallet);
await oneInchExchangeMockToWeth.addSetTokenAddress(setToken.address);
// Fund One Inch exchange with destinationToken WETH
await setup.weth.transfer(oneInchExchangeMockToWeth.address, ether(10));
// Mint aTokens
await setup.weth.approve(aaveSetup.lendingPool.address, ether(1000));
await aaveSetup.lendingPool.connect(owner.wallet).deposit(setup.weth.address, ether(1000), owner.address, ZERO);
await setup.dai.approve(aaveSetup.lendingPool.address, ether(10000));
await aaveSetup.lendingPool.connect(owner.wallet).deposit(setup.dai.address, ether(10000), owner.address, ZERO);
// Approve tokens to issuance module and call issue
await aWETH.approve(setup.issuanceModule.address, ether(1000));
await aDAI.approve(setup.issuanceModule.address, ether(10000));
// Issue 1 SetToken. Note: 1inch mock is hardcoded to trade 1000 DAI regardless of Set supply
const issueQuantity = ether(1);
destinationTokenQuantity = ether(1);
await setup.issuanceModule.issue(setToken.address, issueQuantity, owner.address);
});
beforeEach(() => {
subjectSetToken = setToken.address;
subjectBorrowAsset = setup.dai.address;
subjectCollateralAsset = setup.weth.address;
subjectBorrowQuantity = ether(1000);
subjectMinCollateralQuantity = destinationTokenQuantity;
subjectTradeAdapterName = "ONEINCHTOWETH";
subjectTradeData = oneInchExchangeMockToWeth.interface.encodeFunctionData("swap", [
setup.dai.address, // Send token
setup.weth.address, // Receive token
subjectBorrowQuantity, // Send quantity
subjectMinCollateralQuantity, // Min receive quantity
ZERO,
ADDRESS_ZERO,
[ADDRESS_ZERO],
EMPTY_BYTES,
[ZERO],
[ZERO],
]);
subjectCaller = owner;
});
async function subject(): Promise<any> {
return aaveLeverageModule.connect(subjectCaller.wallet).lever(
subjectSetToken,
subjectBorrowAsset,
subjectCollateralAsset,
subjectBorrowQuantity,
subjectMinCollateralQuantity,
subjectTradeAdapterName,
subjectTradeData
);
}
it("should update the collateral position on the SetToken correctly", async () => {
const initialPositions = await setToken.getPositions();
await subject();
// cEther position is increased
const currentPositions = await setToken.getPositions();
const newFirstPosition = (await setToken.getPositions())[0];
const newSecondPosition = (await setToken.getPositions())[1];