-
Notifications
You must be signed in to change notification settings - Fork 6
/
Exchange.sol
1030 lines (914 loc) · 38.2 KB
/
Exchange.sol
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: MIT
pragma solidity ^0.8.9;
pragma abicoder v2;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {NftOracle} from "./NftOracle.sol";
import "hardhat/console.sol";
// @title Nex Exchange smart contract
contract Exchange is Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
NftOracle public nftOracle;
AggregatorV3Interface public priceFeed;
address public usdc;
bytes32 public latestRequestId; // latest oracle request id (Chainlink)
bytes32 public specId; //bytes32 jobId
uint256 public payment; //link amount for call oracle in wei 10000000000000000
address public assetAddress; //nft address
string public pricingAsset; // ETH or USD
uint256 public insuranceFunds;
uint8 public discountRate = 20; //20%
uint8 public saveLevelMargin = 60; //60%
uint8 public maintenanceMargin = 50; //50%
uint8 public AutoCloseMargin = 40; //40%
uint8 public swapFee = 10; //=> 10/10000 = 0.1%
uint256 public latestFeeUpdate;
address[] liquidateList;
uint256 public vBaycPoolSize;
uint256 public vUsdPoolSize;
address[] public activeUsers;
mapping(address => mapping(address => uint256)) public collateral; //collateral[tokenaddress][useraddress]
mapping(address => int256) public virtualCollateral; //funding reward of each user
mapping(address => int256) public uservUsdBalance; // virtual usd balance of each user;
mapping(address => int256) public uservBaycBalance; // virtual nft balance of each user;
event NewOracle(address oracle);
event Deposit(address token, address user, uint256 amount, uint256 balance);
event Withdraw(address token, address user, uint256 amount, uint256 balance);
constructor(
address _nftOracleAddress,
bytes32 _specId,
uint256 _payment,
address _assetAddress,
string memory _pricingAsset,
address _priceFeed,
address _usdc
) {
nftOracle = NftOracle(_nftOracleAddress);
// nftOracle.getFloorPrice(_specId, _payment, _assetAddress, _pricingAsset);
// latestRequestId = requestId;
priceFeed = AggregatorV3Interface(_priceFeed);
specId = _specId;
payment = _payment;
assetAddress = _assetAddress;
pricingAsset = _pricingAsset;
usdc = _usdc;
}
//request oracle price on nftOracle contract
function requestPrice() public onlyOwner {
nftOracle.getFloorPrice(specId, payment, assetAddress, pricingAsset);
}
//get nft Price in ETH
function showPriceETH() public view returns(uint){
return nftOracle.price()*1e4;
}
//get nft price in USD
function showPriceUSD() public view returns(uint){
uint price = nftOracle.price()*1e4;
int ethPrice = getEthUsdPrice()*1e10;
return price*uint(ethPrice)/1e18;
}
//get eth/usd price
function getEthUsdPrice() public view returns (int) {
(
/*uint80 roundID*/,
int price,
/*uint startedAt*/,
/*uint timeStamp*/,
/*uint80 answeredInRound*/
) = priceFeed.latestRoundData();
return price;
}
//check is user exist in activeUsers array
function doesUserExist(address _user) public view returns (bool) {
for (uint256 i; i < activeUsers.length; i++) {
if (activeUsers[i] == _user) {
return true;
}
}
return false;
}
//add user to the active user list (first check if its not)
function _addActiveUser(address _user) internal {
bool isExist = doesUserExist(_user);
if (isExist == false) {
activeUsers.push(_user);
}
}
//remove user from active users list
function _removeActiveUser(address _user) internal {
bool isExist = doesUserExist(_user);
if (isExist == true) {
for (uint256 i; i < activeUsers.length; i++) {
if (activeUsers[i] == _user) {
delete activeUsers[i];
}
}
}
}
//return all active users in one array
function getAllActiveUsers() public view returns (address[] memory) {
return activeUsers;
}
//create the pool
//for this time owner can do it
function initialVirtualPool(uint256 _assetSize) public onlyOwner {
uint oraclePrice = showPriceUSD();
vBaycPoolSize = _assetSize;
vUsdPoolSize = _assetSize*oraclePrice/1e18;
}
function changeAssetAddress(address _newAddress) public onlyOwner {
assetAddress = _newAddress;
}
//Notice: newFee should be between 1 to 500 (0.01% - 5%)
function setSwapFee(uint8 _newFee) public onlyOwner {
uint256 distance = block.timestamp - latestFeeUpdate;
require(distance / 60 / 60 > 12, "You should wait at least 12 hours after latest update");
require(_newFee <= 500 && _newFee >= 1, "newFee should be between 1 to 500");
swapFee = _newFee;
latestFeeUpdate = block.timestamp;
}
//deposit collateral
function depositCollateral(uint256 _amount) public {
SafeERC20.safeTransferFrom(IERC20(usdc), msg.sender, address(this), _amount);
collateral[usdc][msg.sender] = collateral[usdc][msg.sender].add(_amount);
emit Deposit(usdc, msg.sender, _amount, collateral[usdc][msg.sender]);
}
//withdraw collateral
//befor that the function check user margin
function withdrawCollateral(uint256 _amount) public {
//check new margin
uint256 totalPositionNotional = getPositionNotional(msg.sender);
uint256 totalAccountValue = getAccountValue(msg.sender);
if (totalPositionNotional > 0) {
uint256 newAccountValue = totalAccountValue - _amount;
uint256 newMargin = (100 * newAccountValue) / totalPositionNotional;
require(
newMargin > 60,
"You cannot withdraw because your margin rate is the lower than saveMargin level"
);
}
//check user has enough collateral
require(
collateral[usdc][msg.sender] >= _amount,
"Desire amount is more than collateral balance"
);
//transfer tokens to the user
SafeERC20.safeTransfer(IERC20(usdc), msg.sender, _amount);
collateral[usdc][msg.sender] = collateral[usdc][msg.sender].sub(_amount);
emit Withdraw(usdc, msg.sender, _amount, collateral[usdc][msg.sender]);
}
//give the user funding reward when position will be closed
function _realizevirtualCollateral(address _user, int256 _amount) internal {
require(_amount <= absoluteInt(virtualCollateral[_user]), "out of vitrual collateral balance");
if (virtualCollateral[_user] > 0) {
collateral[usdc][_user] += uint256(_amount);
virtualCollateral[_user] -= _amount;
} else if (virtualCollateral[_user] < 0) {
collateral[usdc][_user] -= uint256(_amount);
virtualCollateral[_user] += _amount;
}
}
//get output Bayc by usd input amount if we want to buy(long)
//how much Bayc we will get by paying usd for long
function getLongBaycAmountOut(uint256 _vUsdAmount) public view returns (uint256) {
uint256 k = vBaycPoolSize * vUsdPoolSize;
uint256 newvUsdPoolSize = vUsdPoolSize + _vUsdAmount;
uint256 newvBaycPoolSize = k / newvUsdPoolSize;
uint256 userBayc = vBaycPoolSize - newvBaycPoolSize;
return userBayc;
}
//get output usd amount by Bayc input amount if we want to buy(long)
function getLongVusdAmountOut(uint256 _vBaycAmount) public view returns (uint256) {
uint256 k = vBaycPoolSize * vUsdPoolSize;
uint256 newvBaycPoolSize = vBaycPoolSize - _vBaycAmount;
uint256 newvUsdPoolSize = k / newvBaycPoolSize;
uint256 uservUsd = newvUsdPoolSize - vUsdPoolSize;
return uservUsd;
}
//get output Bayc by usd input amount if we want to sell(short)
function getShortBaycAmountOut(uint256 _vUsdAmount) public view returns (uint256) {
uint256 k = vBaycPoolSize * vUsdPoolSize;
uint256 newvUsdPoolSize = vUsdPoolSize - _vUsdAmount;
uint256 newvBaycPoolSize = k / newvUsdPoolSize;
uint256 userBayc = newvBaycPoolSize - vBaycPoolSize;
return userBayc;
}
//get output usd by Bayc input amount if we want to sell(short)
function getShortVusdAmountOut(uint256 _vBaycAmount) public view returns (uint256) {
uint256 k = vBaycPoolSize * vUsdPoolSize;
uint256 newvBaycPoolSize = vBaycPoolSize + _vBaycAmount;
uint256 newvUsdPoolSize = k / newvBaycPoolSize;
uint256 uservUsd = vUsdPoolSize - newvUsdPoolSize;
return uservUsd;
}
//I use int for negative/positve numbers for user bayc and usd balance(wich might be negative)
//so for some point we need to convert them to uint so they should be positive
//f.e positive(-1)=1
function positive(int256 _amount) public view returns (uint256) {
if (_amount < 0) {
int256 posAmount = -(_amount);
return uint256(posAmount);
} else {
return uint256(_amount);
}
}
function oraclePrice() public view returns(uint256){
uint oraclePrice = showPriceUSD();
return oraclePrice;
}
function getCurrentExchangePrice() public view returns(uint256){
return 1e18*vUsdPoolSize/vBaycPoolSize;
}
function openLongPosition(uint256 _usdAmount) public {
//calculate the new pool size and user bayc amount
uint256 k = vBaycPoolSize * vUsdPoolSize;
uint256 newvUsdPoolSize = vUsdPoolSize + _usdAmount;
uint256 newvBaycPoolSize = k / newvUsdPoolSize;
bool isInTheRightRange = isPriceIntheRightRange(newvBaycPoolSize, newvUsdPoolSize);
require(
isInTheRightRange == true,
"You can't move the price more than 10% far from the oracle price"
);
//first we run liquidation functions
_liquidateUsers(newvBaycPoolSize, newvUsdPoolSize);
_partialLiquidateUsers(newvBaycPoolSize, newvUsdPoolSize);
uint256 userBayc = vBaycPoolSize - newvBaycPoolSize;
//update bayc and usd balance of user
uservBaycBalance[msg.sender] += int256(userBayc);
uservUsdBalance[msg.sender] -= int256(_usdAmount);
//add user to the active user list
_addActiveUser(msg.sender);
//trade fee
uint256 fee = (_usdAmount * swapFee) / 10000;
collateral[usdc][msg.sender] -= fee;
address owner = owner();
SafeERC20.safeTransfer(IERC20(usdc), owner, fee);
//update pool
vBaycPoolSize = newvBaycPoolSize;
vUsdPoolSize = newvUsdPoolSize;
}
function openShortPosition(uint256 _usdAmount) public {
//calculate the new pool size and user bayc amount
uint256 k = vBaycPoolSize * vUsdPoolSize;
uint256 newvUsdPoolSize = vUsdPoolSize - _usdAmount;
uint256 newvBaycPoolSize = k / newvUsdPoolSize;
bool isInTheRightRange = isPriceIntheRightRange(newvBaycPoolSize, newvUsdPoolSize);
require(
isInTheRightRange == true,
"You can't move the price more than 10% far from the oracle price"
);
//first we run liquidation functions
_partialLiquidateUsers(newvBaycPoolSize, newvUsdPoolSize);
_liquidateUsers(newvBaycPoolSize, newvUsdPoolSize);
k = vBaycPoolSize * vUsdPoolSize;
newvUsdPoolSize = vUsdPoolSize - _usdAmount;
newvBaycPoolSize = k / newvUsdPoolSize;
uint256 userBayc = newvBaycPoolSize - vBaycPoolSize;
//update bayc and usd balance of user
uservBaycBalance[msg.sender] -= int256(userBayc);
uservUsdBalance[msg.sender] += int256(_usdAmount);
//add user to the active user list
_addActiveUser(msg.sender);
//trade fee
uint256 fee = (_usdAmount * swapFee) / 10000;
collateral[usdc][msg.sender] -= fee;
address owner = owner();
SafeERC20.safeTransfer(IERC20(usdc), owner, fee);
//update pool
vBaycPoolSize = newvBaycPoolSize;
vUsdPoolSize = newvUsdPoolSize;
}
function _closeLongPosition(address _user, uint256 _assetSize) internal {
require(
_assetSize <= positive(uservBaycBalance[_user]),
"You dont have enough asset size to close the long position"
);
uint256 k;
//first we run liquidation functions
k = vBaycPoolSize * vUsdPoolSize;
uint256 vBaycNewPoolSize = vBaycPoolSize + _assetSize;
uint256 vUsdNewPoolSize = k / vBaycNewPoolSize;
_partialLiquidateUsers(vBaycNewPoolSize, vUsdNewPoolSize);
_liquidateUsers(vBaycNewPoolSize, vUsdNewPoolSize);
//get the output usd of closing position
//f.e 1Bayc -> 2000$
uint256 usdBaycValue = getShortVusdAmountOut(_assetSize);
int256 userPartialvUsdBalance = (uservUsdBalance[_user] * int256(_assetSize)) /
uservBaycBalance[_user];
//increase or decrease the user pnl for this function
if (usdBaycValue > uint256(positive(userPartialvUsdBalance))) {
uint256 pnl = usdBaycValue - uint256(positive(userPartialvUsdBalance));
// collateral[usdc][_user] += pnl;
collateral[usdc][_user] += pnl;
} else if (usdBaycValue < uint256(positive(userPartialvUsdBalance))) {
uint256 pnl = uint256(positive(userPartialvUsdBalance) - usdBaycValue);
collateral[usdc][_user] -= pnl;
}
//realize funding reward of user;
int256 realizeVirtualCollAmount = (virtualCollateral[_user] * int256(_assetSize)) /
uservBaycBalance[_user];
_realizevirtualCollateral(_user, absoluteInt(realizeVirtualCollAmount));
//update user balance
uservBaycBalance[_user] -= int256(_assetSize);
uservUsdBalance[_user] += absoluteInt(userPartialvUsdBalance);
// if user has not vbalance so he is not active
if (uservBaycBalance[_user] == 0 && uservUsdBalance[_user] == 0) {
_removeActiveUser(_user);
}
//trade fee
uint256 fee = (usdBaycValue * swapFee) / 10000;
collateral[usdc][_user] -= fee;
address owner = owner();
SafeERC20.safeTransfer(IERC20(usdc), owner, fee);
//update the pool
k = vBaycPoolSize * vUsdPoolSize;
vBaycPoolSize += _assetSize;
vUsdPoolSize = k / vBaycPoolSize;
}
function _closeShortPosition(address _user, uint256 _assetSize) internal {
require(
_assetSize <= positive(uservBaycBalance[_user]),
"You dont have enough asset size to close the short position"
);
uint256 k;
//first we run liquidation functions
k = vBaycPoolSize * vUsdPoolSize;
uint256 vBaycNewPoolSize = vBaycPoolSize - _assetSize;
uint256 vUsdNewPoolSize = k / vBaycNewPoolSize;
_partialLiquidateUsers(vBaycNewPoolSize, vUsdNewPoolSize);
_liquidateUsers(vBaycNewPoolSize, vUsdNewPoolSize);
//get the output usd of closing position
uint256 usdBaycValue = getLongVusdAmountOut(_assetSize);
int256 userPartialvUsdBalance = (uservUsdBalance[_user] * int256(_assetSize)) /
uservBaycBalance[_user];
//increase or decrease pnl of the user
if (usdBaycValue > uint256(positive(userPartialvUsdBalance))) {
uint256 pnl = usdBaycValue - uint256(positive(userPartialvUsdBalance));
collateral[usdc][_user] -= pnl;
}
if (usdBaycValue < uint256(positive(userPartialvUsdBalance))) {
uint256 pnl = uint256(positive(userPartialvUsdBalance) - usdBaycValue);
collateral[usdc][_user] += pnl;
}
//realize funding reward of user;
int256 realizeVirtualCollAmount = (virtualCollateral[_user] * int256(_assetSize)) /
uservBaycBalance[_user];
_realizevirtualCollateral(_user, absoluteInt(realizeVirtualCollAmount));
//update user balance
uservBaycBalance[_user] += int256(_assetSize);
uservUsdBalance[_user] -= absoluteInt(userPartialvUsdBalance);
// if user has not vbalance so he is not active
if (uservBaycBalance[_user] == 0 && uservUsdBalance[_user] == 0) {
_removeActiveUser(_user);
}
//trade fee
uint256 fee = (usdBaycValue * swapFee) / 10000;
collateral[usdc][_user] -= fee;
address owner = owner();
SafeERC20.safeTransfer(IERC20(usdc), owner, fee);
//update pool
k = vBaycPoolSize * vUsdPoolSize;
vBaycPoolSize -= _assetSize;
vUsdPoolSize = k / vBaycPoolSize;
}
function closePositionComplete() public {
uint assetSize = positive(uservBaycBalance[msg.sender]);
closePosition(assetSize);
}
function closePosition(uint256 _assetSize) public {
require(
_assetSize <= positive(uservBaycBalance[msg.sender]),
"You dont have enough asset size to close the all positions"
);
//if user has positive vBayc balance so he/she has longPosition
//if user has negative vBayc balance so he/she has shortPosition
if (uservBaycBalance[msg.sender] > 0) {
_closeLongPosition(msg.sender, _assetSize);
} else if (uservBaycBalance[msg.sender] < 0) {
_closeShortPosition(msg.sender, _assetSize);
}
}
//return the pnl of user
/*
user vBayc balance = 2Bayc
user vUsd balance = -3000
currnent 2 vBayc value = 4000
user pnl = 4000 - positive(-3000) = 1000$
*/
function getPNL(address _user) public view returns (int256) {
if (uservBaycBalance[_user] > 0) {
uint256 currentBaycValue = getShortVusdAmountOut(uint256(uservBaycBalance[_user]));
int256 pnl = int256(currentBaycValue) + (uservUsdBalance[_user]);
return pnl;
} else if (uservBaycBalance[_user] < 0) {
uint256 currentBaycValue = getLongVusdAmountOut(positive(uservBaycBalance[_user]));
int256 pnl = uservUsdBalance[_user] - int256(currentBaycValue);
return pnl;
}
}
//get user pnl by new pool size(new price);
function _getNewPNL(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (int256) {
if (uservBaycBalance[_user] > 0) {
uint256 k = _vBaycNewPoolSize * _vUsdNewPoolSize;
uint256 newvBaycPoolSize = _vBaycNewPoolSize + uint256(uservBaycBalance[_user]);
uint256 newvUsdPoolSize = k / newvBaycPoolSize;
uint256 currentBaycValue = _vUsdNewPoolSize - newvUsdPoolSize;
int256 pnl = int256(currentBaycValue) + (uservUsdBalance[_user]);
return pnl;
} else if (uservBaycBalance[_user] < 0) {
uint256 k = _vBaycNewPoolSize * _vUsdNewPoolSize;
uint256 newvBaycPoolSize = _vBaycNewPoolSize - positive(uservBaycBalance[_user]);
uint256 newvUsdPoolSize = k / newvBaycPoolSize;
uint256 currentBaycValue = newvUsdPoolSize - _vUsdNewPoolSize;
int256 pnl = uservUsdBalance[_user] - int256(currentBaycValue);
return pnl;
}
}
//account value = collateral +- pnl
function getAccountValue(address _user) public view returns (uint256) {
uint256 collateralValue = collateral[usdc][_user];
int256 pnl = getPNL(_user);
int256 fundingReward = virtualCollateral[_user];
int256 accountValue = int256(collateralValue) + pnl + fundingReward;
return uint256(accountValue);
}
//get new account value according to the new pool size (new price)
function _getNewAccountValue(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (uint256) {
uint256 collateralValue = collateral[usdc][_user];
int256 pnl = _getNewPNL(_user, _vBaycNewPoolSize, _vUsdNewPoolSize);
int256 fundingReward = virtualCollateral[_user];
int256 accountValue = int256(collateralValue) + pnl + fundingReward;
// int256 accountValue = int256(collateralValue);
return uint256(accountValue);
}
//get total position value of each user
function getPositionNotional(address _user) public view returns (uint256) {
if (uservBaycBalance[_user] > 0) {
uint256 positionNotionalValue = getShortVusdAmountOut(uint256(uservBaycBalance[_user]));
return positionNotionalValue;
} else if (uservBaycBalance[_user] < 0) {
uint256 positionNotionalValue = getLongVusdAmountOut(positive(uservBaycBalance[_user]));
return positionNotionalValue;
} else {
return 0;
}
}
//get new position notional value according to the new pool size (new price)
function _getNewPositionNotional(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (uint256) {
if (uservBaycBalance[_user] > 0) {
uint256 k = _vBaycNewPoolSize * _vUsdNewPoolSize;
uint256 newvBaycPoolSize = _vBaycNewPoolSize + uint256(uservBaycBalance[_user]);
uint256 newvUsdPoolSize = k / newvBaycPoolSize;
uint256 positionNotionalValue = _vUsdNewPoolSize - newvUsdPoolSize;
return positionNotionalValue;
} else if (uservBaycBalance[_user] < 0) {
uint256 k = _vBaycNewPoolSize * _vUsdNewPoolSize;
uint256 newvBaycPoolSize = _vBaycNewPoolSize - positive(uservBaycBalance[_user]);
uint256 newvUsdPoolSize = k / newvBaycPoolSize;
uint256 positionNotionalValue = newvUsdPoolSize - _vUsdNewPoolSize;
return positionNotionalValue;
} else {
return 0;
}
}
function userMargin(address _user) public view returns (uint256) {
uint256 accountValue = getAccountValue(_user);
uint256 positionNotional = getPositionNotional(_user);
if (accountValue > 0 && positionNotional > 0) {
uint256 margin = (100 * accountValue) / positionNotional;
return margin;
}
}
//get the new margin of user according to the new pool size (new price)
function _userNewMargin(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (uint256) {
uint256 accountValue = _getNewAccountValue(_user, _vBaycNewPoolSize, _vUsdNewPoolSize);
uint256 positionNotional = _getNewPositionNotional(_user, _vBaycNewPoolSize, _vUsdNewPoolSize);
if (accountValue > 0 && positionNotional > 0) {
uint256 margin = (100 * accountValue) / positionNotional;
return margin;
}else{
return 0;
}
}
function isHardLiquidateable(address _user) public view returns (bool) {
uint256 userMargin = userMargin(_user);
if (userMargin > 0 && userMargin <= 40) {
return true;
} else {
return false;
}
}
//ckeck that is user can be liquidated according to the new price
function _isHardLiquidateable(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (bool) {
uint256 userMargin = _userNewMargin(_user, _vBaycNewPoolSize, _vUsdNewPoolSize);
if (userMargin > 0 && userMargin <= 40) {
return true;
} else {
return false;
}
}
function isPartialLiquidateable(address _user) public view returns (bool) {
uint256 userMargin = userMargin(_user);
if (40 <= userMargin && userMargin <= 50) {
return true;
} else {
return false;
}
}
//ckeck that is user can be partialy liquidated according to the new price
function _isPartialLiquidateable(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (bool) {
uint256 userMargin = _userNewMargin(_user, _vBaycNewPoolSize, _vUsdNewPoolSize);
if (40 <= userMargin && userMargin <= 50) {
return true;
} else {
return false;
}
}
function hardLiquidate(address _user) public {
_hardLiquidate(_user, vBaycPoolSize, vUsdPoolSize);
}
//this function is called if user should be liquidated by new price
function _hardLiquidate(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) public {
require(
_isHardLiquidateable(_user, _vBaycNewPoolSize, _vUsdNewPoolSize),
"user can not be liquidate"
);
if (uservBaycBalance[_user] > 0) {
// _closeLongPosition(_user, uint256(uservBaycBalance[_user]));
uint256 _assetSize = uint256(uservBaycBalance[_user]);
uint256 usdBaycValue = getShortVusdAmountOut(_assetSize);
//increase or decrease the user pnl for this function
if (usdBaycValue > uint256(positive(uservUsdBalance[_user]))) {
uint256 pnl = usdBaycValue - uint256(positive(uservUsdBalance[_user]));
collateral[usdc][_user] += pnl;
} else if (usdBaycValue < uint256(positive(uservUsdBalance[_user]))) {
uint256 pnl = uint256(positive(uservUsdBalance[_user]) - usdBaycValue);
collateral[usdc][_user] -= pnl;
}
//realize funding reward of user;
int256 realizeVirtualCollAmount = (virtualCollateral[_user] * int256(_assetSize)) /
uservBaycBalance[_user];
_realizevirtualCollateral(_user, absoluteInt(realizeVirtualCollAmount));
//update user balance
uservBaycBalance[_user] -= int256(_assetSize);
uservUsdBalance[_user] += absoluteInt(uservUsdBalance[_user]);
// if user has not vbalance so he is not active
if (uservBaycBalance[_user] == 0 && uservUsdBalance[_user] == 0) {
_removeActiveUser(_user);
}
//update the pool
uint256 k = vBaycPoolSize * vUsdPoolSize;
vBaycPoolSize += _assetSize;
vUsdPoolSize = k / vBaycPoolSize;
} else if (uservBaycBalance[_user] < 0) {
uint256 _assetSize = uint256(positive(uservBaycBalance[_user]));
uint256 usdBaycValue = getShortVusdAmountOut(_assetSize);
//increase or decrease the user pnl for this function
if (usdBaycValue > uint256(uservUsdBalance[_user])) {
uint256 pnl = usdBaycValue - uint256(positive(uservUsdBalance[_user]));
collateral[usdc][_user] -= pnl;
} else if (usdBaycValue < uint256(uservUsdBalance[_user])) {
uint256 pnl = uint256(positive(uservUsdBalance[_user]) - usdBaycValue);
collateral[usdc][_user] += pnl;
}
//realize funding reward of user;
int256 realizeVirtualCollAmount = (virtualCollateral[_user] * int256(_assetSize)) /
uservBaycBalance[_user];
_realizevirtualCollateral(_user, absoluteInt(realizeVirtualCollAmount));
//update user balance
uservBaycBalance[_user] += int256(_assetSize);
uservUsdBalance[_user] -= uservUsdBalance[_user];
// if user has not vbalance so he is not active
if (uservBaycBalance[_user] == 0 && uservUsdBalance[_user] == 0) {
_removeActiveUser(_user);
}
//update the pool
uint256 k = vBaycPoolSize * vUsdPoolSize;
vBaycPoolSize += _assetSize;
vUsdPoolSize = k / vBaycPoolSize;
}
uint256 collateralValue = collateral[usdc][_user];
uint256 discountAmount = (discountRate * collateralValue) / 100;
collateral[usdc][_user] -= discountAmount;
insuranceFunds += discountAmount;
}
//calculate liquidation amount to turn back the user margin to the save level(60%)
function calculatePartialLiquidateValue(address _user) public view returns (uint256 x) {
uint256 totalAccountValue = getAccountValue(_user);
uint256 totalPositionNotional = getPositionNotional(_user);
uint256 numerator = (totalPositionNotional * saveLevelMargin) / 100 - totalAccountValue;
uint256 denominator = saveLevelMargin / 100 - discountRate / 100;
x = numerator / denominator;
}
//calculate liquidation amount to turn back the user margin to the save level(60%) according to the new price
function _calculatePartialLiquidateValue(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal view returns (uint256) {
uint256 totalAccountValue = _getNewAccountValue(_user, _vBaycNewPoolSize, _vUsdNewPoolSize);
uint256 totalPositionNotional = _getNewPositionNotional(
_user,
_vBaycNewPoolSize,
_vUsdNewPoolSize
);
uint256 numerator = totalPositionNotional*saveLevelMargin/100 > totalAccountValue ? totalPositionNotional*saveLevelMargin/100 - totalAccountValue : totalAccountValue - totalPositionNotional*saveLevelMargin/100;
uint256 denominator = saveLevelMargin - discountRate;
uint x = numerator*100/denominator;
return x;
}
function partialLiquidate(address _user) public {
require(isPartialLiquidateable(_user), "user can not be partially liquidated");
uint256 liquidateAmount = calculatePartialLiquidateValue(_user);
if (uservBaycBalance[_user] > 0) {
_closeLongPosition(_user, liquidateAmount);
} else if (uservBaycBalance[_user] < 0) {
_closeShortPosition(_user, liquidateAmount);
}
uint256 collateralValue = collateral[usdc][_user];
uint256 discountAmount = (collateralValue * discountRate) / 100;
collateral[usdc][_user] -= discountAmount;
insuranceFunds += discountAmount;
}
//Liquidate user partialy according to the new price
function _partialLiquidate(
address _user,
uint256 _vBaycNewPoolSize,
uint256 _vUsdNewPoolSize
) internal {
require(
_isPartialLiquidateable(_user, _vBaycNewPoolSize, _vUsdNewPoolSize),
"user can not be partially liquidated"
);
uint256 liquidateAmount = _calculatePartialLiquidateValue(
_user,
_vBaycNewPoolSize,
_vUsdNewPoolSize
);
uint baycLiquidateAmount = liquidateAmount*vBaycPoolSize/vUsdPoolSize;
// return BaycLiquidateAmount;
if (uservBaycBalance[_user] > 0) {
// _closeLongPosition(_user, baycLiquidateAmount);
//get the output usd of closing position
uint256 usdBaycValue = getShortVusdAmountOut(baycLiquidateAmount);
int256 userPartialvUsdBalance = (uservUsdBalance[_user] * int256(baycLiquidateAmount)) /
uservBaycBalance[_user];
//increase or decrease the user pnl for this function
if (usdBaycValue > (positive(userPartialvUsdBalance))) {
uint256 pnl = usdBaycValue - (positive(userPartialvUsdBalance));
collateral[usdc][_user] += pnl;
} else if (usdBaycValue < (positive(userPartialvUsdBalance))) {
uint256 pnl = (positive(userPartialvUsdBalance) - usdBaycValue);
collateral[usdc][_user] -= pnl;
// collateral[usdc][_user] -= 100;
}
//realize funding reward of user;
int256 realizeVirtualCollAmount = (virtualCollateral[_user] * int256(baycLiquidateAmount)) /
uservBaycBalance[_user];
_realizevirtualCollateral(_user, absoluteInt(realizeVirtualCollAmount));
//update user balance
uservBaycBalance[_user] -= int256(baycLiquidateAmount);
uservUsdBalance[_user] += absoluteInt(userPartialvUsdBalance);
// if user has not vbalance so he is not active
if (uservBaycBalance[_user] == 0 && uservUsdBalance[_user] == 0) {
_removeActiveUser(_user);
}
//update the pool
uint256 k = vBaycPoolSize * vUsdPoolSize;
vBaycPoolSize += baycLiquidateAmount;
vUsdPoolSize = k / vBaycPoolSize;
} else if (uservBaycBalance[_user] < 0) {
//get the output usd of closing position
uint256 usdBaycValue = getLongVusdAmountOut(baycLiquidateAmount);
int256 userPartialvUsdBalance = (uservUsdBalance[_user] * int256(baycLiquidateAmount)) /
uservBaycBalance[_user];
//increase or decrease pnl of the user
if (usdBaycValue > uint256(positive(userPartialvUsdBalance))) {
uint256 pnl = usdBaycValue - uint256(positive(userPartialvUsdBalance));
collateral[usdc][_user] -= pnl;
}
if (usdBaycValue < (positive(userPartialvUsdBalance))) {
uint256 pnl = (positive(userPartialvUsdBalance) - usdBaycValue);
collateral[usdc][_user] += pnl;
}
//realize funding reward of user;
int256 realizeVirtualCollAmount = (virtualCollateral[_user] * int256(baycLiquidateAmount)) /
uservBaycBalance[_user];
_realizevirtualCollateral(_user, absoluteInt(realizeVirtualCollAmount));
//update user balance
uservBaycBalance[_user] += int256(baycLiquidateAmount);
uservUsdBalance[_user] -= absoluteInt(userPartialvUsdBalance);
// if user has not vbalance so he is not active
if (uservBaycBalance[_user] == 0 && uservUsdBalance[_user] == 0) {
_removeActiveUser(_user);
}
//update pool
uint256 k2 = vBaycPoolSize * vUsdPoolSize;
vBaycPoolSize -= baycLiquidateAmount;
vUsdPoolSize = k2 / vBaycPoolSize;
}
uint256 collateralValue = collateral[usdc][_user];
uint256 discountAmount = (collateralValue * discountRate) / 100;
collateral[usdc][_user] -= discountAmount;
insuranceFunds += discountAmount;
}
//any one can call this function (admin, user, server or bot) to liquidate liquidateable users
function liquidateUsers() public {
for (uint256 i = 0; i < activeUsers.length; i++) {
if(activeUsers[i] != address(0)){
bool isLiquidateable = isHardLiquidateable(activeUsers[i]);
if (isLiquidateable == true) {
hardLiquidate(activeUsers[i]);
}
}
}
}
//liquidate users according to the new price (is used only in trade trade functions)
function _liquidateUsers(uint256 _vBaycNewPoolSize, uint256 _vUsdNewPoolSize) internal {
for (uint256 i = 0; i < activeUsers.length; i++) {
if(activeUsers[i] != address(0)){
bool isLiquidateable = _isHardLiquidateable(
activeUsers[i],
_vBaycNewPoolSize,
_vUsdNewPoolSize
);
if (isLiquidateable == true) {
_hardLiquidate(activeUsers[i], _vBaycNewPoolSize, _vUsdNewPoolSize);
}
}
}
}
function partialLiquidateUsers() public {
for (uint256 i = 0; i < activeUsers.length; i++) {
if(activeUsers[i] != address(0)){
bool isPartialLiquidateable = isPartialLiquidateable(activeUsers[i]);
if (isPartialLiquidateable == true) {
partialLiquidate(activeUsers[i]);
}
}
}
}
//liquidate users partialy according to the new price (is used only in trade trade functions)
function _partialLiquidateUsers(uint256 _vBaycNewPoolSize, uint256 _vUsdNewPoolSize) internal {
for (uint256 i = 0; i < activeUsers.length; i++) {
if(activeUsers[i] != address(0)){
bool isPartialLiquidateable = _isPartialLiquidateable(
activeUsers[i],
_vBaycNewPoolSize,
_vUsdNewPoolSize
);
if (isPartialLiquidateable == true) {
_partialLiquidate(activeUsers[i], _vBaycNewPoolSize, _vUsdNewPoolSize);
}
}
}
}
function getAllLongvBaycBalance() public view returns (int256) {
int256 allLongBaycBalance;
for (uint256 i; i < activeUsers.length; i++) {
address user = activeUsers[i];
int256 vBaycBalance = uservBaycBalance[user];
if (vBaycBalance > 0) {
allLongBaycBalance += vBaycBalance;
}
}
return allLongBaycBalance;
}
function getAllShortvBaycBalance() public view returns (int256) {
int256 allShortBaycBalance;
for (uint256 i; i < activeUsers.length; i++) {
address user = activeUsers[i];
int256 vBaycBalance = uservBaycBalance[user];
if (vBaycBalance < 0) {
allShortBaycBalance += vBaycBalance;
}
}
return allShortBaycBalance;
}
function setFundingRate() public onlyOwner {
uint256 currentPrice = vUsdPoolSize*1e18/vBaycPoolSize;
uint256 oraclePrice = showPriceUSD();
//first the contract check actual vBayc positions balance of users
int256 allLongvBaycBalance = getAllLongvBaycBalance();
int256 allShortBaycBalance = getAllShortvBaycBalance();
//check if we dont have one side(long or short balance = 0) this funding action will not run
if (allLongvBaycBalance > 0 && allShortBaycBalance < 0) {
if (currentPrice > oraclePrice) {
int256 minOpenInterest = (
absoluteInt(allLongvBaycBalance) > absoluteInt(allShortBaycBalance)
? absoluteInt(allShortBaycBalance)
: absoluteInt(allLongvBaycBalance)
);
uint difference = currentPrice - oraclePrice;
uint256 fundingFee = (uint256(minOpenInterest) * difference) / 24e18;
for (uint256 i = 0; i < activeUsers.length; i++) {
address user = activeUsers[i];
if (uservBaycBalance[user] > 0) {
//change vitraul collateral of user
uint256 userFundingFee = (fundingFee * uint256(uservBaycBalance[user])) /
uint256(allLongvBaycBalance);
virtualCollateral[user] -= int256(userFundingFee);
} else if (uservBaycBalance[user] < 0) {
//change vitraul collateral of user
uint256 userFundingFee = (fundingFee * positive(uservBaycBalance[user]))/positive(allShortBaycBalance);
virtualCollateral[user] += int256(userFundingFee);
}
}
} else if (currentPrice < oraclePrice) {
int256 minOpenInterest = (
absoluteInt(allLongvBaycBalance) > absoluteInt(allShortBaycBalance)
? absoluteInt(allShortBaycBalance)
: absoluteInt(allLongvBaycBalance)
);
uint difference = oraclePrice - currentPrice;
uint256 fundingFee = (uint256(minOpenInterest)*difference)/24e18;
for (uint256 i = 0; i < activeUsers.length; i++) {
address user = activeUsers[i];
if (uservBaycBalance[user] > 0) {
//change vitraul collateral of user
uint256 userFundingFee = (fundingFee * uint256(uservBaycBalance[user])) /
uint256(allLongvBaycBalance);
virtualCollateral[user] += int(userFundingFee);
} else if (uservBaycBalance[user] < 0) {
//change vitraul collateral of user
uint256 userFundingFee = (fundingFee * positive(uservBaycBalance[user])) /
positive(allShortBaycBalance);
virtualCollateral[user] -= int(userFundingFee);
}
}
}
}
}
//return positive int
function absoluteInt(int256 _value) public view returns (int256) {
if (_value < 0) {
return -(_value);
} else {
return _value;
}
}
//return false if new price go further than the oracle price
function isPriceIntheRightRange(uint256 _vBaycNewPoolSize, uint256 _vUsdNewPoolSize)
public
view
returns (bool)
{
uint256 currentPrice = 1e18*vUsdPoolSize / vBaycPoolSize;
uint256 oraclePrice = showPriceUSD();