-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPrimexLens.test.js
1699 lines (1556 loc) · 71.2 KB
/
PrimexLens.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,
BigNumber,
getContract,
getContractAt,
getContractFactory,
getNamedSigners,
utils: { parseEther, parseUnits, defaultAbiCoder },
constants: { MaxUint256, AddressZero },
},
deployments: { fixture },
} = require("hardhat");
const { wadDiv, rayDiv, wadMul, rayMul } = require("./utils/math");
const {
WAD,
MAX_TOKEN_DECIMALITY,
LIMIT_PRICE_CM_TYPE,
TAKE_PROFIT_STOP_LOSS_CM_TYPE,
USD_DECIMALS,
USD_MULTIPLIER,
UpdatePullOracle,
} = require("./utils/constants");
const { getAmountsOut, addLiquidity, swapExactTokensForTokens, checkIsDexSupported, getSingleMegaRoute } = require("./utils/dexOperations");
const { parseArguments } = require("./utils/eventValidation");
const { getLimitPriceParams, getTakeProfitStopLossParams, getCondition } = require("./utils/conditionParams");
const { barCalcParams } = require("./utils/defaultBarCalcParams");
const { deployMockInterestRateStrategy, deployMockWhiteBlackList } = require("./utils/waffleMocks");
const { encodeFunctionData } = require("../tasks/utils/encodeFunctionData");
const { getConfigByName } = require("../config/configUtils");
const {
PrimexDNSconfig: { feeRates },
} = getConfigByName("generalConfig.json");
const {
setupUsdOraclesForToken,
setupUsdOraclesForTokens,
getEncodedChainlinkRouteViaUsd,
getEncodedChainlinkRouteToUsd,
setOraclePrice,
getExchangeRateByRoutes,
} = require("./utils/oracleUtils");
process.env.TEST = true;
async function getTokenMetadata(tokenAddress, trader) {
const token = await getContractAt("@openzeppelin/contracts/token/ERC20/ERC20.sol:ERC20", tokenAddress);
const tokenMetadata = {
tokenAddress: tokenAddress,
symbol: await token.symbol(),
name: await token.name(),
decimals: await token.decimals(),
balance: trader ? await token.balanceOf(trader.address) : 0,
};
return tokenMetadata;
}
async function getBucketMetaData(bucketAddress, trader) {
const bucket = await getContractAt("Bucket", bucketAddress);
const DebtToken = await getContractAt("DebtToken", await bucket.debtToken());
const PToken = await getContractAt("PToken", await bucket.pToken());
const priceOracle = await getContract("PriceOracle");
const demand = await DebtToken.totalSupply();
const availableLiquidity = await bucket.availableLiquidity();
const supportedTokens = [];
const assetsCount = (await bucket.getAllowedAssets()).length;
for (let i = 0; i < assetsCount; i++) {
const asset = (await bucket.getAllowedAssets())[i];
let assetParams = await bucket.allowedAssets(asset);
assetParams = {
index: assetParams.index,
isSupported: assetParams.isSupported,
pairPriceDrop: await priceOracle.pairPriceDrops(asset, await bucket.borrowedAsset()),
maxLeverage: await bucket["maxAssetLeverage(address,uint256)"](asset, parseEther(feeRates.MarginPositionClosedByKeeper)),
};
const supportedToken = { asset: await getTokenMetadata(asset, trader), properties: assetParams };
supportedTokens.push(supportedToken);
}
const LMparams = await bucket.getLiquidityMiningParams();
const liquidityMiningRewardDistributor = await LMparams.liquidityMiningRewardDistributor;
const lenderInfo = {
amountInMining: 0,
currentPercent: 0,
rewardsInPMX: [0, 0, 0],
};
const lmBucketInfo = {
pmxAmount: 0,
withdrawnRewards: 0,
totalPoints: 0,
};
const interestRateStrategy = await getContractAt("InterestRateStrategy", await bucket.interestRateStrategy());
const barCalcParams = await interestRateStrategy.getBarCalculationParams(bucket.address);
const bucketMetaData = {
bucketAddress: bucketAddress,
name: "bucket1",
asset: await getTokenMetadata(await bucket.borrowedAsset(), trader),
BAR: await bucket.bar(),
LAR: await bucket.lar(),
supply: demand.add(availableLiquidity),
demand: demand,
availableLiquidity: availableLiquidity,
utilizationRatio: rayDiv(demand.toString(), demand.add(availableLiquidity).toString()).toString(),
supportedAssets: supportedTokens,
pToken: await getTokenMetadata(PToken.address, trader),
debtToken: await getTokenMetadata(DebtToken.address, trader),
feeBuffer: await bucket.feeBuffer(),
withdrawalFeeRate: await bucket.withdrawalFeeRate(),
miningParams: LMparams,
lenderInfo:
liquidityMiningRewardDistributor !== AddressZero
? await liquidityMiningRewardDistributor.getLenderInfo("bucket1", trader.address)
: lenderInfo,
lmBucketInfo:
liquidityMiningRewardDistributor !== AddressZero ? await liquidityMiningRewardDistributor.getBucketInfo("bucket1") : lmBucketInfo,
estimatedBar: await bucket.estimatedBar(),
estimatedLar: await bucket.estimatedLar(),
isDeprecated: await bucket.isDeprecated(),
isDelisted: await bucket.isDelisted(),
barCalcParams: barCalcParams,
maxTotalDeposit: await bucket.maxTotalDeposit(),
};
return bucketMetaData;
}
describe("PrimexLens", function () {
let positionManager,
priceOracle,
limitOrderManager,
traderBalanceVault,
bucket,
PrimexLens,
PrimexDNS,
snapshotId,
depositAmountA,
depositAmountB,
depositAmountX,
depositAmountAFromB,
depositAmountAFromX,
firstAssetRoutes,
depositInThirdAssetRoutes,
ErrorsLibrary,
primexPricingLibrary,
primexPricingLibraryMock;
let trader, lender, deployer;
let dex, dex2;
let testTokenA, decimalsA, testTokenB, decimalsB, testTokenX, decimalsX, PMXToken;
let borrowedAmount0, borrowedAmount1, borrowedAmount2;
let positionDebt0, positionDebt1, positionDebt2;
let positionAmount0, positionAmount1, positionAmount2;
let positionsStopLoss, positionsTakeProfit;
let dexExchangeRateTtaTtb;
let multiplierA, multiplierB;
let emptyBucketMetaData;
const timestamps = [];
before(async function () {
await fixture(["Test"]);
({ deployer, trader, lender } = await getNamedSigners());
positionManager = await getContract("PositionManager");
priceOracle = await getContract("PriceOracle");
limitOrderManager = await getContract("LimitOrderManager");
traderBalanceVault = await getContract("TraderBalanceVault");
testTokenA = await getContract("TestTokenA");
decimalsA = await testTokenA.decimals();
testTokenB = await getContract("TestTokenB");
decimalsB = await testTokenB.decimals();
PMXToken = await getContract("EPMXToken");
PrimexDNS = await getContract("PrimexDNS");
PrimexLens = await getContract("PrimexLens");
ErrorsLibrary = await getContract("Errors");
primexPricingLibrary = await getContract("PrimexPricingLibrary");
const PrimexPricingLibraryMockFactory = await getContractFactory("PrimexPricingLibraryMock", {
libraries: {
PrimexPricingLibrary: primexPricingLibrary.address,
},
});
primexPricingLibraryMock = await PrimexPricingLibraryMockFactory.deploy();
await primexPricingLibraryMock.deployed();
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);
await run("deploy:ERC20Mock", {
name: "TestTokenX",
symbol: "TTX",
decimals: "18",
initialAccounts: JSON.stringify([lender.address]),
initialBalances: JSON.stringify([parseEther("100").toString()]),
});
testTokenX = await getContract("TestTokenX");
decimalsX = await testTokenX.decimals();
multiplierB = BigNumber.from("10").pow(MAX_TOKEN_DECIMALITY.sub(decimalsB));
multiplierA = BigNumber.from("10").pow(MAX_TOKEN_DECIMALITY.sub(decimalsA));
const multiplierX = BigNumber.from("10").pow(MAX_TOKEN_DECIMALITY.sub(decimalsX));
const tokenMetadata = {
tokenAddress: AddressZero,
symbol: "",
name: "",
decimals: 0,
balance: 0,
};
const miningParams = {
liquidityMiningRewardDistributor: AddressZero,
isBucketLaunched: false,
accumulatingAmount: 0,
deadlineTimestamp: 0,
stabilizationDuration: 0,
stabilizationEndTimestamp: 0,
maxAmountPerUser: 0,
maxDuration: 0,
maxStabilizationEndTimestamp: 0,
};
const lenderInfo = {
amountInMining: 0,
currentPercent: 0,
rewardsInPMX: [0, 0, 0],
};
const lmBucketInfo = {
pmxAmount: 0,
withdrawnRewards: 0,
totalPoints: 0,
};
const emptyBarCalcParams = {
urOptimal: 0,
k0: 0,
k1: 0,
b0: 0,
b1: 0,
};
emptyBucketMetaData = {
bucketAddress: AddressZero,
name: "",
asset: tokenMetadata,
BAR: 0,
LAR: 0,
supply: 0,
demand: 0,
availableLiquidity: 0,
utilizationRatio: 0,
supportedAssets: [],
pToken: tokenMetadata,
debtToken: tokenMetadata,
feeBuffer: 0,
withdrawalFeeRate: 0,
miningParams: miningParams,
lenderInfo: lenderInfo,
lmBucketInfo: lmBucketInfo,
estimatedBar: 0,
estimatedLar: 0,
isDeprecated: false,
isDelisted: false,
barCalcParams: emptyBarCalcParams,
maxTotalDeposit: 0,
};
if (process.env.DEX && process.env.DEX !== "uniswap") {
dex = process.env.DEX;
dex2 = "uniswap";
} else {
dex = "uniswap";
dex2 = "sushiswap";
}
firstAssetRoutes = await getSingleMegaRoute([testTokenA.address, testTokenB.address], dex);
depositInThirdAssetRoutes = await getSingleMegaRoute([testTokenX.address, testTokenB.address], dex);
checkIsDexSupported(dex);
await addLiquidity({ dex: dex, from: "lender", tokenA: testTokenA, tokenB: testTokenB });
await addLiquidity({ dex: dex2, from: "lender", tokenA: testTokenA, tokenB: testTokenB });
await addLiquidity({ dex: dex, from: "lender", tokenA: testTokenA, tokenB: testTokenX });
await addLiquidity({ dex: dex, from: "lender", tokenA: testTokenB, tokenB: testTokenX });
await addLiquidity({ dex: dex2, from: "lender", tokenA: testTokenA, tokenB: testTokenX });
await testTokenA.mint(trader.address, parseUnits("1000", decimalsA));
await testTokenB.mint(trader.address, parseUnits("1000", decimalsB));
await testTokenX.mint(trader.address, parseUnits("1000", decimalsX));
const ttaPriceInETH = parseUnits("0.3", USD_DECIMALS); // 1 tta=0.3 ETH
await setupUsdOraclesForTokens(testTokenA, await priceOracle.eth(), ttaPriceInETH);
await setupUsdOraclesForTokens(testTokenX, await priceOracle.eth(), ttaPriceInETH);
await setupUsdOraclesForToken(testTokenB, parseUnits("1", USD_DECIMALS));
const lenderAmountA = parseUnits("1000", decimalsA);
await testTokenA.connect(lender).approve(bucket.address, MaxUint256);
await bucket.connect(lender)["deposit(address,uint256,bool)"](lender.address, lenderAmountA, true);
depositAmountA = parseUnits("15", decimalsA);
depositAmountB = parseUnits("15", decimalsB);
depositAmountX = parseUnits("15", decimalsX);
const borrowedAmount = parseUnits("25", decimalsA);
borrowedAmount0 = borrowedAmount.div(5);
borrowedAmount1 = borrowedAmount.div(5).mul(2);
borrowedAmount2 = borrowedAmount.div(5).mul(3);
positionsStopLoss = [parseEther("1").toString(), parseEther("2").toString(), parseEther("3").toString()];
positionsTakeProfit = [parseEther("6").toString(), parseEther("5").toString(), parseEther("4").toString()];
const amountOutMin = 0;
const deadline = new Date().getTime() + 600;
const takeDepositFromWallet = false;
const swapSize = depositAmountA.add(borrowedAmount0);
const swap = swapSize.mul(multiplierA);
const amountBOut = await getAmountsOut(dex, swapSize, [testTokenA.address, testTokenB.address]);
const amountBinWAD = amountBOut.mul(multiplierB);
const exchRate = wadDiv(amountBinWAD.toString(), swap.toString()).toString();
const price = BigNumber.from(exchRate).div(USD_MULTIPLIER);
await setOraclePrice(testTokenA, testTokenB, price);
const { payload: payload1 } = await encodeFunctionData(
"setDefaultOracleTolerableLimit",
[parseEther("0.01")],
"PositionManagerExtension",
);
await positionManager.setProtocolParamsByAdmin(payload1);
const { payload: payload2 } = await encodeFunctionData("setMaintenanceBuffer", [parseEther("0.01")], "PositionManagerExtension");
await positionManager.setProtocolParamsByAdmin(payload2);
/// ////////////// POSITION 1 ////////////////
// open first position
await testTokenA.connect(trader).approve(traderBalanceVault.address, depositAmountA);
await traderBalanceVault.connect(trader).deposit(testTokenA.address, depositAmountA);
await positionManager.connect(trader).openPosition({
marginParams: {
bucket: "bucket1",
borrowedAmount: borrowedAmount0,
depositInThirdAssetMegaRoutes: [],
},
firstAssetMegaRoutes: firstAssetRoutes,
depositAsset: testTokenA.address,
depositAmount: depositAmountA,
positionAsset: testTokenB.address,
amountOutMin: amountOutMin,
deadline: deadline,
takeDepositFromWallet: takeDepositFromWallet,
closeConditions: [
getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[0], positionsStopLoss[0])),
],
firstAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
thirdAssetOracleData: [],
depositSoldAssetOracleData: [],
positionUsdOracleData: getEncodedChainlinkRouteToUsd(),
nativePositionAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
pmxPositionAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
nativeSoldAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenA),
pullOracleData: [],
pullOracleTypes: [],
});
timestamps.push((await provider.getBlock("latest")).timestamp);
/// ////////////// POSITION 2 ////////////////
const amountBOut1 = await getAmountsOut(dex, borrowedAmount1, [testTokenA.address, testTokenB.address]);
const amountBinWAD1 = amountBOut1.mul(multiplierB);
const exchRate1 = wadDiv(amountBinWAD1.toString(), borrowedAmount1.mul(multiplierA).toString()).toString();
const price1 = BigNumber.from(exchRate1).div(USD_MULTIPLIER);
await setOraclePrice(testTokenA, testTokenB, price1);
depositAmountAFromB = await primexPricingLibraryMock.callStatic.getOracleAmountsOut(
testTokenB.address,
testTokenA.address,
depositAmountB,
priceOracle.address,
getEncodedChainlinkRouteViaUsd(testTokenA),
);
// open second position
await testTokenB.connect(trader).approve(traderBalanceVault.address, depositAmountB);
await traderBalanceVault.connect(trader).deposit(testTokenB.address, depositAmountB);
await positionManager.connect(trader).openPosition({
marginParams: {
bucket: "bucket1",
borrowedAmount: borrowedAmount1,
depositInThirdAssetMegaRoutes: [],
},
firstAssetMegaRoutes: firstAssetRoutes,
depositAsset: testTokenB.address,
depositAmount: depositAmountB,
positionAsset: testTokenB.address,
amountOutMin: amountOutMin,
deadline: deadline,
takeDepositFromWallet: takeDepositFromWallet,
closeConditions: [
getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[1], positionsStopLoss[1])),
],
firstAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
thirdAssetOracleData: [],
depositSoldAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenA),
positionUsdOracleData: getEncodedChainlinkRouteToUsd(),
nativePositionAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
pmxPositionAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
nativeSoldAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenA),
pullOracleData: [],
pullOracleTypes: [],
});
timestamps.push((await provider.getBlock("latest")).timestamp);
/// ////////////// POSITION 3 ////////////////
const amountBOut2 = await getAmountsOut(dex, borrowedAmount2, [testTokenA.address, testTokenB.address]);
const amountBinWAD2 = amountBOut2.mul(multiplierB);
const exchRate2 = wadDiv(amountBinWAD2.toString(), borrowedAmount2.mul(multiplierA).toString()).toString();
const price2 = BigNumber.from(exchRate2).div(USD_MULTIPLIER);
await setOraclePrice(testTokenA, testTokenB, price2);
const depositAmountAXFromDex = await getAmountsOut(dex, depositAmountX, [testTokenX.address, testTokenA.address]);
const amountAFromX = depositAmountAXFromDex.mul(multiplierA);
const amountX = depositAmountX.mul(multiplierX);
const exchangeXArate = wadDiv(amountX.toString(), amountAFromX.toString()).toString();
const priceXA = BigNumber.from(exchangeXArate).div(USD_MULTIPLIER);
await setOraclePrice(testTokenA, testTokenX, priceXA);
depositAmountAFromX = await primexPricingLibraryMock.callStatic.getOracleAmountsOut(
testTokenX.address,
testTokenA.address,
depositAmountX,
priceOracle.address,
getEncodedChainlinkRouteViaUsd(testTokenA),
);
// open third position
await testTokenX.connect(trader).approve(traderBalanceVault.address, depositAmountX);
await traderBalanceVault.connect(trader).deposit(testTokenX.address, depositAmountX);
await positionManager.connect(trader).openPosition({
marginParams: {
bucket: "bucket1",
borrowedAmount: borrowedAmount2,
depositInThirdAssetMegaRoutes: depositInThirdAssetRoutes,
},
firstAssetMegaRoutes: firstAssetRoutes,
depositAsset: testTokenX.address,
depositAmount: depositAmountX,
positionAsset: testTokenB.address,
amountOutMin: amountOutMin,
deadline: deadline,
takeDepositFromWallet: takeDepositFromWallet,
closeConditions: [
getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[2], positionsStopLoss[2])),
],
firstAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
thirdAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
depositSoldAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenA),
positionUsdOracleData: getEncodedChainlinkRouteToUsd(),
nativePositionAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
pmxPositionAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenB),
nativeSoldAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenA),
pullOracleData: [],
pullOracleTypes: [],
});
timestamps.push((await provider.getBlock("latest")).timestamp);
const { positionsData } = await PrimexLens.getArrayOpenPositionDataByTrader(positionManager.address, trader.address, 0, 10);
positionAmount0 = positionsData[0].positionSize;
positionAmount1 = positionsData[1].positionSize;
positionAmount2 = positionsData[2].positionSize;
const amount0Out2 = await getAmountsOut(dex, positionAmount2, [testTokenB.address, testTokenA.address]);
const amountA = amount0Out2.mul(multiplierA);
const amountB = positionAmount2.mul(multiplierB);
dexExchangeRateTtaTtb = wadDiv(amountB.toString(), amountA.toString()).toString();
const priceTtaTtb = BigNumber.from(dexExchangeRateTtaTtb).div(USD_MULTIPLIER);
await setOraclePrice(testTokenA, testTokenB, priceTtaTtb);
await swapExactTokensForTokens({
dex: dex2,
amountIn: parseUnits("70", decimalsA).toString(),
path: [testTokenA.address, testTokenB.address],
});
positionDebt0 = await positionManager.getPositionDebt(0);
positionDebt1 = await positionManager.getPositionDebt(1);
positionDebt2 = await positionManager.getPositionDebt(2);
});
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
describe("constructor", function () {
let snapshotId, lensFactory;
before(async function () {
const primexPricingLibrary = await getContract("PrimexPricingLibrary");
lensFactory = await getContractFactory("PrimexLens", {
libraries: {
PrimexPricingLibrary: primexPricingLibrary.address,
},
});
});
beforeEach(async function () {
snapshotId = await network.provider.request({
method: "evm_snapshot",
params: [],
});
});
afterEach(async function () {
await network.provider.request({
method: "evm_revert",
params: [snapshotId],
});
});
it("Should deploy", async function () {
const takeProfitStopLossCondition = await getContract("TakeProfitStopLossCCM");
expect(await lensFactory.deploy(takeProfitStopLossCondition.address));
});
it("Should revert deploy when takeProfitStopLossCCM address not supported", async function () {
await expect(lensFactory.deploy(traderBalanceVault.address)).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
});
describe("getArrayOpenPositionDataByTrader", function () {
let cursor, count;
let expectedValues;
before(async function () {
// Since the quickswapv3 has a dynamic fee system the amount0Out from the Quoter may differ from the actual amountOut in swap in separate transactions
if (dex === "quickswapv3") this.skip();
const extraParams = defaultAbiCoder.encode(["address"], [testTokenA.address]);
expectedValues = [
[
{
id: 0,
bucket: await getBucketMetaData(bucket.address, trader),
pair: [await getTokenMetadata(testTokenA.address, trader), await getTokenMetadata(testTokenB.address, trader)],
positionSize: positionAmount0,
liquidationPrice: await PrimexLens["getLiquidationPrice(address,uint256)"](positionManager.address, 0),
stopLossPrice: positionsStopLoss[0],
takeProfitPrice: positionsTakeProfit[0],
debt: positionDebt0,
depositAmount: depositAmountA,
createdAt: timestamps[0],
extraParams: extraParams
},
{
id: 1,
bucket: await getBucketMetaData(bucket.address, trader),
pair: [await getTokenMetadata(testTokenA.address, trader), await getTokenMetadata(testTokenB.address, trader)],
positionSize: positionAmount1,
liquidationPrice: await PrimexLens["getLiquidationPrice(address,uint256)"](positionManager.address, 1),
stopLossPrice: positionsStopLoss[1],
takeProfitPrice: positionsTakeProfit[1],
debt: positionDebt1,
depositAmount: depositAmountAFromB,
createdAt: timestamps[1],
extraParams: extraParams
},
{
id: 2,
bucket: await getBucketMetaData(bucket.address, trader),
pair: [await getTokenMetadata(testTokenA.address, trader), await getTokenMetadata(testTokenB.address, trader)],
positionSize: positionAmount2,
liquidationPrice: await PrimexLens["getLiquidationPrice(address,uint256)"](positionManager.address, 2),
stopLossPrice: positionsStopLoss[2],
takeProfitPrice: positionsTakeProfit[2],
debt: positionDebt2,
depositAmount: depositAmountAFromX,
createdAt: timestamps[2],
extraParams: extraParams
},
],
0,
];
});
it("should return empty data if position by trader does not exist, cursor greater or equal position length", async function () {
cursor = 3;
count = 10;
parseArguments(
[[], 0],
await PrimexLens.callStatic.getArrayOpenPositionDataByTrader(positionManager.address, trader.address, cursor, count),
);
});
it("should return all positions data by trader, cursor plus count greater than positions length", async function () {
cursor = 0;
count = 10;
parseArguments(
expectedValues,
await PrimexLens.callStatic.getArrayOpenPositionDataByTrader(positionManager.address, trader.address, cursor, count),
);
});
it("should return correct positions data by trader and new cursor when cursor plus count less than positions length ", async function () {
cursor = 1;
count = 1;
const expectedNewCursor = cursor + count;
expectedValues[1] = expectedNewCursor;
expectedValues[0].splice(2, 1);
expectedValues[0].splice(0, 1);
const result = await PrimexLens.callStatic.getArrayOpenPositionDataByTrader(positionManager.address, trader.address, cursor, count);
const newCursor = result[1].toNumber();
expect(newCursor).to.equal(expectedNewCursor);
parseArguments(
expectedValues,
await PrimexLens.callStatic.getArrayOpenPositionDataByTrader(positionManager.address, trader.address, cursor, count),
);
});
it("should revert if positionManager address is not correct", async function () {
cursor = 0;
count = 2;
const DexAdapter = await getContract("DexAdapter");
await expect(
PrimexLens.callStatic.getArrayOpenPositionDataByTrader(DexAdapter.address, trader.address, cursor, count),
).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
});
describe("getArrayOpenPositionDataByBucket", function () {
let cursor, count;
let expectedValues;
before(async function () {
// Since the quickswapv3 has a dynamic fee system the amount0Out from the Quoter may differ from the actual amountOut in swap in separate transactions
if (dex === "quickswapv3") this.skip();
const extraParams = defaultAbiCoder.encode(["address"], [testTokenA.address]);
expectedValues = [
[
{
id: 0,
bucket: await getBucketMetaData(bucket.address, trader),
pair: [await getTokenMetadata(testTokenA.address, trader), await getTokenMetadata(testTokenB.address, trader)],
positionSize: positionAmount0,
liquidationPrice: await PrimexLens["getLiquidationPrice(address,uint256)"](positionManager.address, 0),
stopLossPrice: positionsStopLoss[0],
takeProfitPrice: positionsTakeProfit[0],
debt: positionDebt0,
depositAmount: depositAmountA,
createdAt: timestamps[0],
extraParams: extraParams
},
{
id: 1,
bucket: await getBucketMetaData(bucket.address, trader),
pair: [await getTokenMetadata(testTokenA.address, trader), await getTokenMetadata(testTokenB.address, trader)],
positionSize: positionAmount1,
liquidationPrice: await PrimexLens["getLiquidationPrice(address,uint256)"](positionManager.address, 1),
stopLossPrice: positionsStopLoss[1],
takeProfitPrice: positionsTakeProfit[1],
debt: positionDebt1,
depositAmount: depositAmountAFromB,
createdAt: timestamps[1],
extraParams: extraParams
},
{
id: 2,
bucket: await getBucketMetaData(bucket.address, trader),
pair: [await getTokenMetadata(testTokenA.address, trader), await getTokenMetadata(testTokenB.address, trader)],
positionSize: positionAmount2,
liquidationPrice: await PrimexLens["getLiquidationPrice(address,uint256)"](positionManager.address, 2),
stopLossPrice: positionsStopLoss[2],
takeProfitPrice: positionsTakeProfit[2],
debt: positionDebt2,
depositAmount: depositAmountAFromX,
createdAt: timestamps[2],
extraParams: extraParams
},
],
0,
];
});
it("should return empty data if position by bucket does not exist, cursor greater or equal position length", async function () {
cursor = 3;
count = 10;
parseArguments(
[[], 0],
await PrimexLens.callStatic.getArrayOpenPositionDataByBucket(positionManager.address, bucket.address, cursor, count),
);
});
it("should return all positions data by bucket, cursor plus count greater than positions length", async function () {
cursor = 0;
count = 10;
parseArguments(
expectedValues,
await PrimexLens.callStatic.getArrayOpenPositionDataByBucket(positionManager.address, bucket.address, cursor, count),
);
});
it("should return correct positions data by bucket and new cursor when cursor plus count less than positions length ", async function () {
cursor = 1;
count = 1;
const expectedNewCursor = cursor + count;
expectedValues[1] = expectedNewCursor;
expectedValues[0].splice(2, 1);
expectedValues[0].splice(0, 1);
const result = await PrimexLens.callStatic.getArrayOpenPositionDataByBucket(positionManager.address, bucket.address, cursor, count);
const newCursor = result[1].toNumber();
expect(newCursor).to.equal(expectedNewCursor);
parseArguments(
expectedValues,
await PrimexLens.callStatic.getArrayOpenPositionDataByBucket(positionManager.address, bucket.address, cursor, count),
);
});
it("should revert if positionManager address is not correct", async function () {
cursor = 0;
count = 2;
const DexAdapter = await getContract("DexAdapter");
await expect(
PrimexLens.callStatic.getArrayOpenPositionDataByBucket(DexAdapter.address, bucket.address, cursor, count),
).to.be.revertedWithCustomError(ErrorsLibrary, "ADDRESS_NOT_SUPPORTED");
});
});
describe("getOpenPositionsWithConditions", function () {
let positionIds, cursor, count;
let position0, position1, position2;
before(async function () {
const openBorrowIndex = (await positionManager.getPosition(0)).openBorrowIndex;
const openBorrowIndex1 = (await positionManager.getPosition(1)).openBorrowIndex;
const openBorrowIndex2 = (await positionManager.getPosition(2)).openBorrowIndex;
const scaledDebtAmount0 = rayDiv(borrowedAmount0.toString(), openBorrowIndex.toString()).toString();
const scaledDebtAmount1 = rayDiv(borrowedAmount1.toString(), openBorrowIndex1.toString()).toString();
const scaledDebtAmount2 = rayDiv(borrowedAmount2.toString(), openBorrowIndex2.toString()).toString();
const extraParams = defaultAbiCoder.encode(["address"], [testTokenA.address]);
position0 = [
BigNumber.from("0"),
scaledDebtAmount0,
bucket.address,
testTokenA.address,
depositAmountA,
testTokenB.address,
positionAmount0,
trader.address,
openBorrowIndex,
timestamps[0],
timestamps[0],
extraParams,
];
position1 = [
BigNumber.from("1"),
scaledDebtAmount1,
bucket.address,
testTokenA.address,
depositAmountAFromB,
testTokenB.address,
positionAmount1,
trader.address,
openBorrowIndex1,
timestamps[1],
timestamps[1],
extraParams,
];
position2 = [
BigNumber.from("2"),
scaledDebtAmount2,
bucket.address,
testTokenA.address,
depositAmountAFromX,
testTokenB.address,
positionAmount2,
trader.address,
openBorrowIndex2,
timestamps[2],
timestamps[2],
extraParams,
];
});
it("should return empty data if position does not exist, cursor greater or equal position length", async function () {
cursor = 3;
count = 10;
const expectedValues = [[], 0];
parseArguments(expectedValues, await PrimexLens.getOpenPositionsWithConditions(positionManager.address, cursor, count));
});
it("should return all positions data, cursor plus count greater than position length", async function () {
cursor = 0;
count = 10;
const expectedValues = [
[
[
position0,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[0], positionsStopLoss[0]))],
],
[
position1,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[1], positionsStopLoss[1]))],
],
[
position2,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[2], positionsStopLoss[2]))],
],
],
0,
];
parseArguments(expectedValues, await PrimexLens.callStatic.getOpenPositionsWithConditions(positionManager.address, cursor, count));
});
it("should return correct conditions data if a position is closed", async function () {
positionIds = [0, 1];
cursor = 0;
count = 2;
const expectedValues = [
[
[
position0,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[0], positionsStopLoss[0]))],
],
[
position1,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[1], positionsStopLoss[1]))],
],
],
2,
];
parseArguments(expectedValues, await PrimexLens.callStatic.getOpenPositionsWithConditions(positionManager.address, cursor, count));
const assetRoutes = await getSingleMegaRoute([testTokenB.address, testTokenA.address], dex);
await positionManager
.connect(trader)
.closePosition(
positionIds[0],
trader.address,
assetRoutes,
0,
getEncodedChainlinkRouteViaUsd(testTokenA),
getEncodedChainlinkRouteViaUsd(testTokenB),
getEncodedChainlinkRouteViaUsd(testTokenB),
[],
[],
);
const expectedValues1 = [
[
[
position2,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[2], positionsStopLoss[2]))],
],
[
position1,
[getCondition(TAKE_PROFIT_STOP_LOSS_CM_TYPE, getTakeProfitStopLossParams(positionsTakeProfit[1], positionsStopLoss[1]))],
],
],
0,
];
parseArguments(expectedValues1, await PrimexLens.callStatic.getOpenPositionsWithConditions(positionManager.address, cursor, count));
});
it("should revert if positionManager address is not correct", async function () {
cursor = 0;
count = 2;
const DexAdapter = await getContract("DexAdapter");
await expect(PrimexLens.getOpenPositionsWithConditions(DexAdapter.address, cursor, count)).to.be.revertedWithCustomError(
ErrorsLibrary,
"ADDRESS_NOT_SUPPORTED",
);
});
});
describe("getLimitOrdersWithConditions", function () {
let cursor, count;
let order0, order1;
let conditionsOrder0, conditionsOrder1;
before(async function () {
// create first order
const depositAmount = parseUnits("15", decimalsA);
const deadline = new Date().getTime() + 600;
const takeDepositFromWallet = true;
const leverage = parseEther("5");
multiplierA = BigNumber.from("10").pow(MAX_TOKEN_DECIMALITY.sub(decimalsA));
await testTokenA.connect(trader).approve(limitOrderManager.address, depositAmount);
conditionsOrder0 = [getCondition(LIMIT_PRICE_CM_TYPE, getLimitPriceParams(leverage.div(multiplierA)))];
await limitOrderManager.connect(trader).createLimitOrder({
bucket: "bucket1",
depositAsset: testTokenA.address,
depositAmount: depositAmount,
positionAsset: testTokenB.address,
deadline: deadline,
takeDepositFromWallet: takeDepositFromWallet,
leverage: leverage,
shouldOpenPosition: true,
openConditions: conditionsOrder0,
closeConditions: [],
isProtocolFeeInPmx: true,
nativeDepositAssetOracleData: getEncodedChainlinkRouteViaUsd(testTokenA),
pullOracleData: [],
pullOracleTypes: [],
});
const createdAt0 = (await provider.getBlock("latest")).timestamp;
// create second order
const exchangeRate = parseUnits("1", decimalsA);
conditionsOrder1 = [getCondition(LIMIT_PRICE_CM_TYPE, getLimitPriceParams(exchangeRate))];
await testTokenA.connect(trader).approve(limitOrderManager.address, depositAmount);
await limitOrderManager.connect(trader).createLimitOrder({
bucket: "bucket1",
depositAsset: testTokenA.address,
depositAmount: depositAmount,
positionAsset: testTokenB.address,
deadline: deadline,
takeDepositFromWallet: takeDepositFromWallet,
leverage: leverage,
shouldOpenPosition: true,
openConditions: conditionsOrder1,
closeConditions: [],
isProtocolFeeInPmx: true,
nativeDepositAssetOracleData: await getEncodedChainlinkRouteViaUsd(testTokenA),
pullOracleData: [],
pullOracleTypes: [],
});
const createdAt1 = (await provider.getBlock("latest")).timestamp;
order0 = [
bucket.address,
testTokenB.address,
testTokenA.address,
depositAmount,
PMXToken.address,
0,
trader.address,
deadline,
1,
leverage,
true,
createdAt0,
createdAt0,
"0x",
];
order1 = [
bucket.address,
testTokenB.address,
testTokenA.address,
depositAmount,
PMXToken.address,
0,
trader.address,
deadline,
2,
leverage,
true,
createdAt1,
createdAt1,
"0x",
];
});
it("should return empty data if order does not exist, cursor greater or equal orders length", async function () {
cursor = 3;
count = 10;
parseArguments([[], 0], await PrimexLens.callStatic.getLimitOrdersWithConditions(limitOrderManager.address, cursor, count));
});
it("should return all orders data, cursor plus count greater or equal orders length", async function () {
cursor = 0;
count = 2;
const expectedValues = [
[
[order0, conditionsOrder0],
[order1, conditionsOrder1],
],
0,
];
parseArguments(expectedValues, await PrimexLens.callStatic.getLimitOrdersWithConditions(limitOrderManager.address, cursor, count));
});
it("should return correct conditions data if a order is closed", async function () {
cursor = 0;
count = 2;
const expectedValues = [
[