-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBucket.test.js
3202 lines (2797 loc) · 147 KB
/
Bucket.test.js
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
// SPDX-License-Identifier: BUSL-1.1
const { expect } = require("chai");
const {
run,
network,
ethers: {
provider,
getContract,
getContractAt,
// getContractFactory,
getSigners,
getNamedSigners,
utils: { parseEther, parseUnits, defaultAbiCoder },
constants: { MaxUint256, One, Zero, AddressZero, NegativeOne },
BigNumber,
getContractFactory,
},
deployments: { fixture },
} = require("hardhat");
const { BigNumber: BN } = require("bignumber.js");
const { getAmountsOut, addLiquidity, checkIsDexSupported, swapExactTokensForTokens, getSingleMegaRoute } = require("./utils/dexOperations");
const { parseArguments } = require("./utils/eventValidation");
const { getAdminSigners, getImpersonateSigner } = require("./utils/hardhatUtils");
const { addressFromEvent } = require("./utils/addressFromEvent");
const { encodeFunctionData } = require("../tasks/utils/encodeFunctionData");
const { getConfigByName } = require("../config/configUtils");
const {
rayMul,
rayDiv,
calculateCompoundInterest,
wadMul,
wadDiv,
calculateLinearInterest,
calculateMaxAssetLeverage,
} = require("./utils/math");
const { MAX_TOKEN_DECIMALITY, WAD, FeeRateType, BAR_CALC_PARAMS_DECODE, RAY, USD_DECIMALS, USD_MULTIPLIER } = require("./utils/constants");
const { FLASH_LOAN_MANAGER_ROLE } = require("../Constants");
const { getPoolAddressesProvider } = require("@aave/deploy-v3");
const {
deployMockPToken,
deployMockDebtToken,
deployMockPositionManager,
deployMockPriceOracle,
deployMockPrimexDNS,
deployMockReserve,
deployMockAccessControl,
deployMockERC20,
deployMockInterestRateStrategy,
deployMockWhiteBlackList,
deployMockPtokensFactory,
deployMockDebtTokensFactory,
} = require("./utils/waffleMocks");
const {
setupUsdOraclesForToken,
setupUsdOraclesForTokens,
getEncodedChainlinkRouteViaUsd,
getEncodedChainlinkRouteToUsd,
setOraclePrice,
} = require("./utils/oracleUtils");
const { barCalcParams: defaultBarCalcParams } = require("./utils/defaultBarCalcParams");
const {
PrimexDNSconfig: { feeRates },
} = getConfigByName("generalConfig.json");
const feeBuffer = "1000200000000000000"; // 1.0002
const withdrawalFeeRate = "5000000000000000"; // 0.005 - 0.5%
const reserveRate = "100000000000000000"; // 0.1 - 10%
const estimatedBar = "100000000000000000000000000"; // 0.1 in ray
const estimatedLar = "70000000000000000000000000"; // 0.07 in ray
let maintenanceBuffer, securityBuffer, oracleTolerableLimitAB, oracleTolerableLimitBA;
process.env.TEST = true;
describe("Bucket", function () {
let pTestTokenA,
reserve,
testTokenA,
decimalsA,
bucket,
pairPriceDrop,
positionManager,
priceOracle,
bucketExtension,
ErrorsLibrary,
testTokenB,
decimalsB,
traderBalanceVault,
PrimexDNS,
BucketsFactory,
dex;
let testTokenX, testTokenY, testTokenZ;
let deployer, lender, caller, trader;
let depositAmount;
let mockRegistry,
mockPToken,
mockPrimexDns,
mockDebtToken,
mockPositionManager,
mockInterestRateStrategy,
mockWhiteBlackList,
mockPtokensFactory,
mockDebtTokensFactory;
let LiquidityMiningRewardDistributor;
let PriceInETH;
let BigTimelockAdmin, MediumTimelockAdmin, SmallTimelockAdmin;
let barCalcParams, interestRateStrategy;
let multiplierA, multiplierB, snapshotId;
// let multiplierA;
before(async function () {
await fixture(["Test"]);
await run("deploy:Aave");
({ deployer, lender, caller, trader } = await getNamedSigners());
testTokenA = await getContract("TestTokenA");
decimalsA = await testTokenA.decimals();
testTokenB = await getContract("TestTokenB");
decimalsB = await testTokenB.decimals();
traderBalanceVault = await getContract("TraderBalanceVault");
BucketsFactory = await getContract("BucketsFactoryV2");
PrimexDNS = await getContract("PrimexDNS");
ErrorsLibrary = await getContract("Errors");
LiquidityMiningRewardDistributor = await getContract("LiquidityMiningRewardDistributor");
positionManager = await getContract("PositionManager");
priceOracle = await getContract("PriceOracle");
interestRateStrategy = await getContract("InterestRateStrategy");
bucketExtension = await getContract("BucketExtension");
barCalcParams = defaultAbiCoder.encode(BAR_CALC_PARAMS_DECODE, [Object.values(defaultBarCalcParams)]);
({ BigTimelockAdmin, MediumTimelockAdmin, SmallTimelockAdmin } = await getAdminSigners());
const { payload } = await encodeFunctionData(
"setMaxPositionSize",
[testTokenA.address, testTokenB.address, 0, MaxUint256],
"PositionManagerExtension",
);
await positionManager.setProtocolParamsByAdmin(payload);
const bucketAddress = (await PrimexDNS.buckets("bucket1")).bucketAddress;
bucket = await getContractAt("Bucket", bucketAddress);
const pTestTokenAddress = await bucket.pToken();
const reserveAddress = await bucket.reserve();
pTestTokenA = await getContractAt("PToken", pTestTokenAddress);
reserve = await getContractAt("Reserve", reserveAddress);
await run("deploy:ERC20Mock", {
name: "TestTokenX",
symbol: "TTX",
decimals: "18",
initialAccounts: JSON.stringify([lender.address, deployer.address]),
initialBalances: JSON.stringify([parseEther("100").toString(), parseEther("100").toString()]),
});
await run("deploy:ERC20Mock", {
name: "TestTokenY",
symbol: "TTY",
decimals: "18",
initialAccounts: JSON.stringify([lender.address]),
initialBalances: JSON.stringify([parseEther("100").toString()]),
});
await run("deploy:ERC20Mock", {
name: "TestTokenZ",
symbol: "TTZ",
decimals: "18",
initialAccounts: JSON.stringify([lender.address]),
initialBalances: JSON.stringify([parseEther("100").toString()]),
});
testTokenX = await getContract("TestTokenX");
testTokenY = await getContract("TestTokenY");
testTokenZ = await getContract("TestTokenZ");
multiplierA = BigNumber.from("10").pow(MAX_TOKEN_DECIMALITY.sub(decimalsA));
multiplierB = BigNumber.from("10").pow(MAX_TOKEN_DECIMALITY.sub(decimalsB));
await testTokenA.connect(lender).approve(pTestTokenA.address, MaxUint256);
dex = process.env.DEX || "uniswap";
checkIsDexSupported(dex);
await addLiquidity({ dex: dex, from: "lender", tokenA: testTokenA, tokenB: testTokenB, tokenC: testTokenX });
depositAmount = parseUnits("50", decimalsA);
await testTokenA.mint(trader.address, parseUnits("100", decimalsA));
await testTokenA.connect(trader).approve(traderBalanceVault.address, depositAmount);
await traderBalanceVault.connect(trader).deposit(testTokenA.address, depositAmount);
await testTokenA.connect(lender).approve(bucket.address, MaxUint256);
PriceInETH = parseUnits("0.3", USD_DECIMALS); // 1 tta=0.3 ETH
await setupUsdOraclesForTokens(testTokenA, await priceOracle.eth(), PriceInETH);
await setupUsdOraclesForTokens(testTokenX, await priceOracle.eth(), PriceInETH);
await setupUsdOraclesForTokens(testTokenY, await priceOracle.eth(), PriceInETH);
await setupUsdOraclesForTokens(testTokenZ, await priceOracle.eth(), PriceInETH);
await setupUsdOraclesForToken(testTokenB, parseUnits("1", USD_DECIMALS));
});
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
describe("Initialization", function () {
let bucketName;
let mockReserve;
let assets;
let feeBuffer;
let reserveRate;
let bucketInitParams;
let testTokenBAssets;
let snapshotId;
let bucketsFactory, bucketsFactoryContractFactory, bucketImplementation;
let mockErc20;
before(async function () {
bucketName = "Bucket";
testTokenBAssets = await getContract("TestTokenB");
assets = [testTokenBAssets.address];
feeBuffer = parseEther("1.0002");
reserveRate = 0;
mockErc20 = await deployMockERC20(deployer);
mockReserve = await deployMockReserve(deployer);
mockPToken = await deployMockPToken(deployer);
mockDebtToken = await deployMockDebtToken(deployer);
mockPositionManager = await deployMockPositionManager(deployer);
mockPrimexDns = await deployMockPrimexDNS(deployer);
mockRegistry = await deployMockAccessControl(deployer);
mockInterestRateStrategy = await deployMockInterestRateStrategy(deployer);
mockWhiteBlackList = await deployMockWhiteBlackList(deployer);
mockPtokensFactory = await deployMockPtokensFactory(deployer);
mockDebtTokensFactory = await deployMockDebtTokensFactory(deployer);
bucketImplementation = await getContract("Bucket");
bucketsFactoryContractFactory = await getContractFactory("BucketsFactory");
});
beforeEach(async function () {
mockPToken = await deployMockPToken(deployer);
mockDebtToken = await deployMockDebtToken(deployer);
await mockPtokensFactory.mock.createPToken.returns(mockPToken.address);
await mockDebtTokensFactory.mock.createDebtToken.returns(mockDebtToken.address);
bucketsFactory = await bucketsFactoryContractFactory.deploy(
mockRegistry.address,
mockPtokensFactory.address,
mockDebtTokensFactory.address,
bucketImplementation.address,
);
await bucketsFactory.deployed();
bucketInitParams = {
nameBucket: bucketName,
positionManager: mockPositionManager.address,
priceOracle: priceOracle.address,
dns: mockPrimexDns.address,
reserve: mockReserve.address,
whiteBlackList: mockWhiteBlackList.address,
assets: assets,
underlyingAsset: testTokenA.address,
feeBuffer: feeBuffer.toString(),
withdrawalFeeRate: withdrawalFeeRate.toString(),
reserveRate: reserveRate.toString(),
liquidityMiningRewardDistributor: LiquidityMiningRewardDistributor.address,
liquidityMiningAmount: 1,
liquidityMiningDeadline: MaxUint256.div(2),
stabilizationDuration: 1,
interestRateStrategy: interestRateStrategy.address,
maxAmountPerUser: MaxUint256,
isReinvestToAaveEnabled: false,
estimatedBar: estimatedBar,
estimatedLar: estimatedLar,
barCalcParams: barCalcParams,
maxTotalDeposit: MaxUint256,
};
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
it("Should deploy bucket with liquidity mining is off and check initial params", async function () {
bucketInitParams.liquidityMiningAmount = "0";
const tx = await bucketsFactory.createBucket(bucketInitParams);
const txReceipt = await tx.wait();
const bucketAddress = addressFromEvent("BucketCreated", txReceipt);
const bucket = await getContractAt("Bucket", bucketAddress);
const LiquidityMiningParams = {
liquidityMiningRewardDistributor: AddressZero,
isBucketLaunched: true,
accumulatingAmount: 0,
deadlineTimestamp: 0,
stabilizationDuration: 0,
stabilizationEndTimestamp: 0,
maxAmountPerUser: 0,
maxDuration: 0,
maxStabilizationEndTimestamp: 0,
};
parseArguments(LiquidityMiningParams, await bucket.getLiquidityMiningParams());
});
it("Should deploy bucket with liquidity mining is on and check initial params", async function () {
const tx = await bucketsFactory.createBucket(bucketInitParams);
const txReceipt = await tx.wait();
const bucketAddress = addressFromEvent("BucketCreated", txReceipt);
const bucket = await getContractAt("Bucket", bucketAddress);
const blockNumber = txReceipt.blockNumber;
const timestamp = (await provider.getBlock(blockNumber)).timestamp;
const maxStabilizationEndTimestamp = bucketInitParams.liquidityMiningDeadline.add(bucketInitParams.stabilizationDuration);
const LiquidityMiningParams = {
liquidityMiningRewardDistributor: bucketInitParams.liquidityMiningRewardDistributor,
isBucketLaunched: false,
accumulatingAmount: bucketInitParams.liquidityMiningAmount,
deadlineTimestamp: bucketInitParams.liquidityMiningDeadline,
stabilizationDuration: bucketInitParams.stabilizationDuration,
stabilizationEndTimestamp: 0,
maxAmountPerUser: MaxUint256,
maxDuration: maxStabilizationEndTimestamp.sub(timestamp),
maxStabilizationEndTimestamp: maxStabilizationEndTimestamp,
};
parseArguments(LiquidityMiningParams, await bucket.getLiquidityMiningParams());
});
it("Should deploy bucket with initial bar calculation params", async function () {
const tx = await bucketsFactory.createBucket(bucketInitParams);
const txReceipt = await tx.wait();
const bucketAddress = addressFromEvent("BucketCreated", txReceipt);
parseArguments(defaultBarCalcParams, await interestRateStrategy.getBarCalculationParams(bucketAddress));
});
it("Should deploy bucket with initial maxTotalDeposit value", async function () {
const tx = await bucketsFactory.createBucket(bucketInitParams);
const txReceipt = await tx.wait();
const bucketAddress = addressFromEvent("BucketCreated", txReceipt);
const bucket = await getContractAt("Bucket", bucketAddress);
const realMaxTotalDeposit = await bucket.maxTotalDeposit();
expect(bucketInitParams.maxTotalDeposit).to.be.equal(realMaxTotalDeposit);
});
it("Should revert when withdrawalFeeRate is greater than 10%", async function () {
bucketInitParams.withdrawalFeeRate = parseEther("0.11");
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"WITHDRAW_RATE_IS_MORE_10_PERCENT",
);
});
it("Should revert when feeBuffer is equal or less than one or more than WAD + WAD / 100", async function () {
bucketInitParams.feeBuffer = parseEther("1");
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "INVALID_FEE_BUFFER");
bucketInitParams.feeBuffer = parseEther("0.9");
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "INVALID_FEE_BUFFER");
bucketInitParams.feeBuffer = parseEther("1").add(BigNumber.from(WAD.toString()).div("100"));
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "INVALID_FEE_BUFFER");
});
it("Should revert when reserveRate is equal or greater than one", async function () {
bucketInitParams.reserveRate = parseEther("1");
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"RESERVE_RATE_SHOULD_BE_LESS_THAN_1",
);
bucketInitParams.reserveRate = parseEther("1.1");
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"RESERVE_RATE_SHOULD_BE_LESS_THAN_1",
);
});
it("Should revert when maxTotalDeposit is zero", async function () {
bucketInitParams.maxTotalDeposit = 0;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "MAX_TOTAL_DEPOSIT_IS_ZERO");
});
it("Should revert when liquidityMiningRewardDistributor address is not supported", async function () {
bucketInitParams.liquidityMiningRewardDistributor = positionManager.address;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"INCORRECT_LIQUIDITY_MINING_PARAMS",
);
});
it("Should revert when liquidityMiningAmount isn't 0 and liquidityMiningDeadline is 0", async function () {
bucketInitParams.liquidityMiningDeadline = 0;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"INCORRECT_LIQUIDITY_MINING_PARAMS",
);
});
it("Should revert when liquidityMiningAmount isn't 0 and maxAmountPerUser is 0", async function () {
bucketInitParams.maxAmountPerUser = 0;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"INCORRECT_LIQUIDITY_MINING_PARAMS",
);
});
it("Should revert when dns address not supported", async function () {
await mockPrimexDns.mock.supportsInterface.returns(false);
bucketInitParams.dns = mockPrimexDns.address;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
it("Should revert when positionManager address not supported", async function () {
await mockPositionManager.mock.supportsInterface.returns(false);
bucketInitParams.positionManager = mockPositionManager.address;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
it("Should revert if Reserve address does not support IReserve", async function () {
await mockReserve.mock.supportsInterface.returns(false);
bucketInitParams.reserve = mockReserve.address;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
it("Should revert if InterestRateStrategy address does not support IInterestRateStrategy", async function () {
await mockInterestRateStrategy.mock.supportsInterface.returns(false);
bucketInitParams.interestRateStrategy = mockInterestRateStrategy.address;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
// todo: Should revert if priceOracle address does not support IPriceOracle
// todo: Should revert if whiteBlackList address does not support IWhiteBlackList
it("Should revert when asset address is zero", async function () {
const wrongParam = [AddressZero];
bucketInitParams.assets = wrongParam;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"CAN_NOT_ADD_WITH_ZERO_ADDRESS",
);
});
it("Should revert when decimals of borrowed asset exceeds the max value", async function () {
await mockErc20.mock.decimals.returns(19);
bucketInitParams.underlyingAsset = mockErc20.address;
await expect(bucketsFactory.createBucket(bucketInitParams)).to.be.revertedWithCustomError(
ErrorsLibrary,
"ASSET_DECIMALS_EXCEEDS_MAX_VALUE",
);
});
it("Should set withdrawalFeeRate during deploy", async function () {
const tx = await bucketsFactory.createBucket(bucketInitParams);
const txReceipt = await tx.wait();
const bucketAddress = addressFromEvent("BucketCreated", txReceipt);
const bucket = await getContractAt("Bucket", bucketAddress);
const withdrawalFeeRateFromBucket = await bucket.withdrawalFeeRate();
expect(withdrawalFeeRateFromBucket).to.equal(withdrawalFeeRate);
});
it("Should set the correct values of estimated Bar and Lar during deploy bucket with liquidity mining", async function () {
const tx = await bucketsFactory.createBucket(bucketInitParams);
const txReceipt = await tx.wait();
const bucketAddress = addressFromEvent("BucketCreated", txReceipt);
const bucket = await getContractAt("Bucket", bucketAddress);
expect(await bucket.estimatedBar()).to.equal(estimatedBar);
expect(await bucket.estimatedLar()).to.equal(estimatedLar);
});
});
describe("Set functions", function () {
let snapshotId;
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
it("Should revert if not BIG_TIMELOCK_ADMIN call setBucketExtension", async function () {
await expect(bucket.connect(caller).setBucketExtension(bucketExtension.address)).to.be.revertedWithCustomError(
ErrorsLibrary,
"FORBIDDEN",
);
});
it("Should revert setBucketExtension when bucketExtension address not supported", async function () {
await expect(bucket.connect(deployer).setBucketExtension(priceOracle.address)).to.be.revertedWithCustomError(
ErrorsLibrary,
"ADDRESS_NOT_SUPPORTED",
);
});
it("Should set new bucketExtension", async function () {
await expect(bucket.connect(deployer).setBucketExtension(bucketExtension.address))
.to.emit(bucket, "ChangedBucketExtension")
.withArgs(bucketExtension.address);
});
it("Should revert if not MEDIUM_TIMELOCK_ADMIN call setBarCalculationParams", async function () {
await expect(bucket.connect(caller).setBarCalculationParams([])).to.be.revertedWithCustomError(ErrorsLibrary, "FORBIDDEN");
});
it("Should set BarCalculationParams and emit BarCalculationParamsChanged event", async function () {
const paramsInBytes = defaultAbiCoder.encode(BAR_CALC_PARAMS_DECODE, [Object.values(defaultBarCalcParams)]);
await expect(bucket.connect(deployer).setBarCalculationParams(paramsInBytes))
.to.emit(interestRateStrategy, "BarCalculationParamsChanged")
.withArgs(
bucket.address,
defaultBarCalcParams.urOptimal,
defaultBarCalcParams.k0,
defaultBarCalcParams.k1,
defaultBarCalcParams.b0,
defaultBarCalcParams.b1,
)
.to.emit(bucket, "BarCalculationParamsChanged")
.withArgs(paramsInBytes);
});
it("Should revert if not BIG_TIMELOCK_ADMIN call setReserveRate", async function () {
await expect(bucket.connect(caller).setReserveRate(parseEther("0.1"))).to.be.revertedWithCustomError(ErrorsLibrary, "FORBIDDEN");
});
it("Should revert setReserveRate if reserveRate is equal or greater than one", async function () {
await expect(bucket.connect(BigTimelockAdmin).setReserveRate(parseEther("1"))).to.be.revertedWithCustomError(
ErrorsLibrary,
"RESERVE_RATE_SHOULD_BE_LESS_THAN_1",
);
await expect(bucket.connect(BigTimelockAdmin).setReserveRate(parseEther("1.1"))).to.be.revertedWithCustomError(
ErrorsLibrary,
"RESERVE_RATE_SHOULD_BE_LESS_THAN_1",
);
});
it("Should be: new reserve Rate set successfully", async function () {
await bucket.connect(BigTimelockAdmin).setReserveRate(parseEther("0.1"));
expect(await bucket.reserveRate()).to.be.equal(parseEther("0.1"));
});
it("Should emit ReserveRateChanged when reserve rate is changed", async function () {
const newReserveRate = parseEther("1").div(2);
await expect(bucket.setReserveRate(newReserveRate)).to.emit(bucket, "ReserveRateChanged").withArgs(newReserveRate);
});
it("Should revert if not MEDIUM_TIMELOCK_ADMIN call setFeeBuffer", async function () {
await expect(bucket.connect(caller).setFeeBuffer(parseEther("1.01"))).to.be.revertedWithCustomError(ErrorsLibrary, "FORBIDDEN");
});
it("Should revert setFeeBuffer if feeBuffer is equal or less than one", async function () {
await expect(bucket.connect(MediumTimelockAdmin).setFeeBuffer(parseEther("1"))).to.be.revertedWithCustomError(
ErrorsLibrary,
"INVALID_FEE_BUFFER",
);
await expect(bucket.connect(MediumTimelockAdmin).setFeeBuffer(parseEther("0.9"))).to.be.revertedWithCustomError(
ErrorsLibrary,
"INVALID_FEE_BUFFER",
);
await expect(
bucket.connect(MediumTimelockAdmin).setFeeBuffer(parseEther("1").add(BigNumber.from(WAD.toString()).div("100"))),
).to.be.revertedWithCustomError(ErrorsLibrary, "INVALID_FEE_BUFFER");
});
it("Should be: new fee buffer set successfully", async function () {
await bucket.connect(MediumTimelockAdmin).setFeeBuffer(parseEther("1.0099"));
expect(await bucket.feeBuffer()).to.be.equal(parseEther("1.0099"));
});
it("Should revert setMaxTotalDeposit if maxTotalDeposit is zero", async function () {
await expect(bucket.connect(MediumTimelockAdmin).setMaxTotalDeposit(0)).to.be.revertedWithCustomError(
ErrorsLibrary,
"MAX_TOTAL_DEPOSIT_IS_ZERO",
);
});
it("Should set maxTotal deposit successfully and emit event", async function () {
// todo: create 2 separate tests / chech emit and set maxTotalDeposit
const newMaxTotalDeposit = parseEther("1");
await expect(bucket.connect(MediumTimelockAdmin).setMaxTotalDeposit(newMaxTotalDeposit))
.to.emit(bucket, "MaxTotalDepositChanged")
.withArgs(newMaxTotalDeposit);
expect(await bucket.maxTotalDeposit()).to.be.equal(newMaxTotalDeposit);
});
it("Should revert if not MEDIUM_TIMELOCK_ADMIN call setMaxTotalDeposit", async function () {
await expect(bucket.connect(caller).setMaxTotalDeposit(parseEther("1"))).to.be.revertedWithCustomError(ErrorsLibrary, "FORBIDDEN");
});
it("Should revert if not BIG_TIMELOCK_ADMIN call setWithdrawalFee", async function () {
await expect(bucket.connect(caller).setWithdrawalFee(5)).to.be.revertedWithCustomError(ErrorsLibrary, "FORBIDDEN");
});
it("Should revert if new withdrawalFeeRate more or equal WAD/10 (10 percent)", async function () {
// todo: fix wad x2,need to set WAD/10
await expect(bucket.setWithdrawalFee(WAD)).to.be.revertedWithCustomError(ErrorsLibrary, "WITHDRAW_RATE_IS_MORE_10_PERCENT");
await expect(bucket.setWithdrawalFee(WAD)).to.be.revertedWithCustomError(ErrorsLibrary, "WITHDRAW_RATE_IS_MORE_10_PERCENT");
});
it("Should set new withdrawalFeeRate", async function () {
const newWithdrawalFeeRate = BigNumber.from(withdrawalFeeRate).mul(2);
await bucket.connect(BigTimelockAdmin).setWithdrawalFee(newWithdrawalFeeRate);
const withdrawalFeeRateFromBucket = await bucket.withdrawalFeeRate();
expect(withdrawalFeeRateFromBucket).to.equal(newWithdrawalFeeRate);
});
it("Should emit WithdrawalFeeChanged when withdrawal fee is changed", async function () {
const newWithdrawalFeeRate = BigNumber.from(withdrawalFeeRate).mul(2);
await expect(bucket.setWithdrawalFee(newWithdrawalFeeRate)).to.emit(bucket, "WithdrawalFeeChanged").withArgs(newWithdrawalFeeRate);
});
it("Should emit FeeBufferChanged when fee buffer is changed", async function () {
const newFeeBuffer = parseEther("1.001");
await expect(bucket.setFeeBuffer(newFeeBuffer)).to.emit(bucket, "FeeBufferChanged").withArgs(newFeeBuffer);
});
it("Should revert if not MEDIUM_TIMELOCK_ADMIN call setInterestRateStrategy", async function () {
await expect(bucket.connect(caller).setInterestRateStrategy(deployer.address));
});
it("Should set a new InterestRateStrategy address if it supports IInterestRateStrategy", async function () {
const newInterestRateStrategy = await deployMockInterestRateStrategy(deployer);
expect(await bucket.connect(MediumTimelockAdmin).setInterestRateStrategy(newInterestRateStrategy.address));
});
it("Should emit InterestRateStrategyChanged when interestRateStrategy is changed", async function () {
const newInterestRateStrategy = await deployMockInterestRateStrategy(deployer);
await expect(bucket.setInterestRateStrategy(newInterestRateStrategy.address))
.to.emit(bucket, "InterestRateStrategyChanged")
.withArgs(newInterestRateStrategy.address);
});
it("Should revert if new InterestRateStrategy address does not support IInterestRateStrategy", async function () {
const newInterestRateStrategy = await deployMockInterestRateStrategy(deployer);
await newInterestRateStrategy.mock.supportsInterface.returns(false);
await expect(bucket.setInterestRateStrategy(newInterestRateStrategy.address)).to.be.revertedWithCustomError(
ErrorsLibrary,
"ADDRESS_NOT_SUPPORTED",
);
});
});
describe("View functions", function () {
let snapshotId;
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
it("Should returns the correct status when the bucket is inactive", async function () {
await PrimexDNS.freezeBucket(await bucket.name());
expect(await bucket.isActive()).to.be.equal(false);
expect(await bucket.isDelisted()).to.be.equal(false);
expect(await bucket.isDeprecated()).to.be.equal(false);
expect(await bucket.isWithdrawAfterDelistingAvailable()).to.be.equal(false);
});
it("Should returns the correct status when the bucket is active", async function () {
expect(await bucket.isActive()).to.be.equal(true);
expect(await bucket.isDelisted()).to.be.equal(false);
expect(await bucket.isDeprecated()).to.be.equal(false);
expect(await bucket.isWithdrawAfterDelistingAvailable()).to.be.equal(false);
});
it("Should returns the correct status when the bucket is deprecated", async function () {
await PrimexDNS.deprecateBucket(await bucket.name());
expect(await bucket.isActive()).to.be.equal(false);
expect(await bucket.isDelisted()).to.be.equal(false);
expect(await bucket.isDeprecated()).to.be.equal(true);
expect(await bucket.isWithdrawAfterDelistingAvailable()).to.be.equal(false);
});
it("Should returns the correct status when the current timestamp > delisting deadline", async function () {
await PrimexDNS.deprecateBucket(await bucket.name());
await network.provider.send("evm_increaseTime", [(await PrimexDNS.delistingDelay()).add("1").toNumber()]);
await network.provider.send("evm_mine");
expect(await bucket.isActive()).to.be.equal(false);
expect(await bucket.isDelisted()).to.be.equal(true);
expect(await bucket.isDeprecated()).to.be.equal(true);
expect(await bucket.isWithdrawAfterDelistingAvailable()).to.be.equal(false);
});
it("Should returns the correct status when the current timestamp > admin deadline", async function () {
await PrimexDNS.deprecateBucket(await bucket.name());
await network.provider.send("evm_increaseTime", [
(
await PrimexDNS.delistingDelay()
)
.add(await PrimexDNS.adminWithdrawalDelay())
.add("1")
.toNumber(),
]);
await network.provider.send("evm_mine");
expect(await bucket.isActive()).to.be.equal(false);
expect(await bucket.isDelisted()).to.be.equal(true);
expect(await bucket.isDeprecated()).to.be.equal(true);
expect(await bucket.isWithdrawAfterDelistingAvailable()).to.be.equal(true);
});
});
describe("receiveDeposit", function () {
let snapshotId;
let maxTotalDeposit, pTokenSupply;
before(async function () {
maxTotalDeposit = parseEther("35");
pTokenSupply = await pTestTokenA.totalSupply();
});
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
it("Should receiveDeposit if deposit does not exceed maxTotalDeposit", async function () {
await bucket.setMaxTotalDeposit(maxTotalDeposit);
const depositAmount = maxTotalDeposit.sub(1);
const bucketSigner = await getImpersonateSigner(bucket);
expect(pTokenSupply.add(depositAmount)).to.be.lt(maxTotalDeposit);
await expect(bucket.connect(bucketSigner).receiveDeposit(deployer.address, depositAmount, 0, await bucket.name())).to.emit(
bucket,
"Deposit",
);
});
// todo: add receiveDeposit for deposit to launched bucket
// todo: add receiveDeposit for deposit to LMbucket
it("Should revert receiveDeposit if DEPOSIT_EXCEEDS_MAX_TOTAL_DEPOSIT", async function () {
await bucket.setMaxTotalDeposit(maxTotalDeposit);
const depositAmount = maxTotalDeposit.add(1);
expect(pTokenSupply.add(depositAmount)).to.be.gt(maxTotalDeposit);
await expect(bucket.receiveDeposit(deployer.address, depositAmount, 0, await bucket.name())).to.be.revertedWithCustomError(
ErrorsLibrary,
"DEPOSIT_EXCEEDS_MAX_TOTAL_DEPOSIT",
);
});
// todo: add check for this error "_require(dns.getBucketAddress(_bucketFrom) == msg.sender, Errors.FORBIDDEN.selector);"
// todo: Should revert receiveDeposit if it's called not by bucket in system)
//
it("Should revert receiveDeposit if bucket isn't, check FORBIDDEN error", async function () {
await bucket.setMaxTotalDeposit(maxTotalDeposit);
const depositAmount = maxTotalDeposit.sub(1);
const bucketSigner = await getImpersonateSigner(bucket);
expect(pTokenSupply.add(depositAmount)).to.be.lt(maxTotalDeposit);
await expect(bucket.connect(bucketSigner).receiveDeposit(deployer.address, depositAmount, 0, await bucket.name())).to.emit(
bucket,
"Deposit",
);
});
});
describe("withdrawAfterDelisting", function () {
let snapshotId;
let deposit;
before(async function () {
deposit = parseUnits("100", decimalsA);
});
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
it("Should revert if not BIG_TIMELOCK_ADMIN call withdrawAfterDelisting", async function () {
await expect(bucket.connect(caller).withdrawAfterDelisting(deposit)).to.be.revertedWithCustomError(ErrorsLibrary, "FORBIDDEN");
});
it("Should revert withdrawAfterDelisting when the bucket status is not time after delisting", async function () {
await expect(bucket.withdrawAfterDelisting(deposit)).to.be.revertedWithCustomError(ErrorsLibrary, "WITHDRAWAL_NOT_ALLOWED");
});
it("Should withdrawAfterDelisting to treasury", async function () {
await bucket.connect(lender)["deposit(address,uint256,bool)"](lender.address, deposit, true);
await PrimexDNS.deprecateBucket(await bucket.name());
await network.provider.send("evm_increaseTime", [
(
await PrimexDNS.delistingDelay()
)
.add(await PrimexDNS.adminWithdrawalDelay())
.add("1")
.toNumber(),
]);
const treasury = await getContract("Treasury");
await expect(() => bucket.connect(BigTimelockAdmin).withdrawAfterDelisting(deposit)).to.changeTokenBalances(
testTokenA,
[bucket, treasury.address],
[deposit.mul(NegativeOne), deposit],
);
});
});
describe("Integration tests LiquidityMining in bucket and LiquidityMiningRewardDistributor", function () {
let snapshotId, snapshotIdBase;
let pmx,
pmxRewardAmount,
liquidityMiningDeadline,
stabilizationDuration,
liquidityMiningAmount,
maxStabilizationEndTimestamp,
maxDuration,
bucket,
mockWhiteBlackList,
pTestTokenA;
before(async function () {
mockWhiteBlackList = await deployMockWhiteBlackList(deployer);
snapshotIdBase = await network.provider.request({
method: "evm_snapshot",
params: [],
});
pmx = await getContract("EPMXToken");
const currentTimestamp = (await provider.getBlock("latest")).timestamp + 100;
await network.provider.send("evm_setNextBlockTimestamp", [currentTimestamp]);
liquidityMiningDeadline = currentTimestamp + 24 * 60 * 60;
stabilizationDuration = 60 * 60;
liquidityMiningAmount = parseUnits("100", decimalsA);
maxStabilizationEndTimestamp = liquidityMiningDeadline + stabilizationDuration;
maxDuration = maxStabilizationEndTimestamp - currentTimestamp;
pmxRewardAmount = parseUnits("100", await pmx.decimals());
const { newBucket: newBucketAddress } = await run("deploy:Bucket", {
nameBucket: "BucketWithLiquidityMining",
assets: `["${testTokenB.address}"]`,
pairPriceDrops: "[\"100000000000000000\"]",
feeBuffer: "1000100000000000000", // 1.0001
withdrawalFeeRate: "5000000000000000", // 0.005 - 0.5%
reserveRate: "100000000000000000", // 0.1 - 10%,
underlyingAsset: testTokenA.address,
whiteBlackList: mockWhiteBlackList.address,
liquidityMiningRewardDistributor: LiquidityMiningRewardDistributor.address,
liquidityMiningAmount: liquidityMiningAmount.toString(),
liquidityMiningDeadline: liquidityMiningDeadline.toString(),
maxAmountPerUser: MaxUint256.toString(),
stabilizationDuration: stabilizationDuration.toString(), // 1 hour
estimatedBar: estimatedBar,
estimatedLar: estimatedLar,
pmxRewardAmount: pmxRewardAmount.toString(),
barCalcParams: JSON.stringify(defaultBarCalcParams),
maxTotalDeposit: MaxUint256.toString(),
});
bucket = await getContractAt("Bucket", newBucketAddress);
pTestTokenA = await getContractAt("PToken", await bucket.pToken());
});
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
snapshotId = await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
after(async function () {
await network.provider.request({
method: "evm_revert",
params: [snapshotIdBase],
});
});
it("Should revert openPosition while bucket is not launched", async function () {
const assetRoutes = await getSingleMegaRoute([testTokenA.address, testTokenB.address], dex);
await expect(
openPosition(testTokenA, traderBalanceVault, bucket, positionManager, dex, testTokenB, assetRoutes),
).to.be.revertedWithCustomError(ErrorsLibrary, "BUCKET_IS_NOT_LAUNCHED");
});
it("Should revert receiveDeposit if it's called not by bucket in system", async function () {
await expect(bucket.receiveDeposit(deployer.address, 100, 0, await bucket.name())).to.be.revertedWithCustomError(
ErrorsLibrary,
"FORBIDDEN",
);
});
it("Should openPosition when bucket is launched", async function () {
await testTokenA.connect(lender).approve(bucket.address, liquidityMiningAmount);
await bucket.connect(lender)["deposit(address,uint256,bool)"](lender.address, liquidityMiningAmount, true);
const assetRoutes = await getSingleMegaRoute([testTokenA.address, testTokenB.address], dex);
await openPosition(testTokenA, traderBalanceVault, bucket, positionManager, dex, testTokenB, assetRoutes);
});
it("Should emit BucketLaunched event when bucket is launched", async function () {
await testTokenA.connect(lender).approve(bucket.address, liquidityMiningAmount);
await expect(bucket.connect(lender)["deposit(address,uint256,bool)"](lender.address, liquidityMiningAmount, true)).to.emit(
bucket,
"BucketLaunched",
);
});
it("claimReward should transfer pmx on balance in TraderBalanceVault", async function () {
const data = [
{ account: deployer, deposit: liquidityMiningAmount.mul(2).div(5) },
{ account: lender, deposit: liquidityMiningAmount.mul(4).div(5) },
];
for (let i = 0; i < data.length; i++) {
await testTokenA.mint(data[i].account.address, data[i].deposit);
await testTokenA.connect(data[i].account).approve(bucket.address, data[i].deposit);
await bucket.connect(data[i].account)["deposit(address,uint256,bool)"](data[i].account.address, data[i].deposit, true);
}
const timestamp = (await provider.getBlock("latest")).timestamp;
await network.provider.send("evm_setNextBlockTimestamp", [timestamp + stabilizationDuration + 100]);
const bucketName = await bucket.name();
for (let i = 0; i < data.length; i++) {
const { rewardsInPMX } = await LiquidityMiningRewardDistributor.getLenderInfo(bucketName, data[i].account.address, timestamp);
const claimReward = await LiquidityMiningRewardDistributor.connect(data[i].account).claimReward(bucketName);
const { availableBalance } = await traderBalanceVault.balances(data[i].account.address, pmx.address);
await expect(claimReward).to.changeTokenBalances(
pmx,
[LiquidityMiningRewardDistributor, traderBalanceVault],
[rewardsInPMX.minReward.mul(NegativeOne), rewardsInPMX.minReward],
);
expect(availableBalance).to.equal(rewardsInPMX.minReward);
}
});
it("withdrawPmxByAdmin should transfer pmx", async function () {
const data = [
{ account: deployer, deposit: liquidityMiningAmount.mul(2).div(5) },
{ account: lender, deposit: liquidityMiningAmount.mul(4).div(5) },
];
for (let i = 0; i < data.length; i++) {
await testTokenA.mint(data[i].account.address, data[i].deposit);
await testTokenA.connect(data[i].account).approve(bucket.address, data[i].deposit);
await bucket.connect(data[i].account)["deposit(address,uint256,bool)"](data[i].account.address, data[i].deposit, true);
}
const timestamp = (await provider.getBlock("latest")).timestamp;
await network.provider.send("evm_setNextBlockTimestamp", [timestamp + stabilizationDuration + 100]);
const bucketName = await bucket.name();
const { rewardsInPMX } = await LiquidityMiningRewardDistributor.getLenderInfo(
bucketName,
data[0].account.address,
(
await provider.getBlock("latest")
).timestamp,
);
await LiquidityMiningRewardDistributor.connect(data[0].account).claimReward(bucketName);
await PrimexDNS.deprecateBucket(bucketName);
await network.provider.send("evm_increaseTime", [
(
await PrimexDNS.delistingDelay()
)
.add(await PrimexDNS.adminWithdrawalDelay())