-
Notifications
You must be signed in to change notification settings - Fork 13
/
Trading.sol
1053 lines (991 loc) · 37.7 KB
/
Trading.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: Unlicense
pragma solidity ^0.8.0;
import "./utils/MetaContext.sol";
import "./interfaces/ITrading.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IPairsContract.sol";
import "./interfaces/IReferrals.sol";
import "./interfaces/IPosition.sol";
import "./interfaces/IGovNFT.sol";
import "./interfaces/IStableVault.sol";
import "./utils/TradingLibrary.sol";
interface ITradingExtension {
function getVerifiedPrice(
uint _asset,
PriceData calldata _priceData,
bytes calldata _signature,
uint _withSpreadIsLong
) external returns(uint256 _price, uint256 _spread);
function getRef(
address _trader
) external pure returns(address);
function _setReferral(
bytes32 _referral,
address _trader
) external;
function validateTrade(uint _asset, address _tigAsset, uint _margin, uint _leverage) external view;
function isPaused() external view returns(bool);
function minPos(address) external view returns(uint);
function modifyLongOi(
uint _asset,
address _tigAsset,
bool _onOpen,
uint _size
) external;
function modifyShortOi(
uint _asset,
address _tigAsset,
bool _onOpen,
uint _size
) external;
function paused() external returns(bool);
function _limitClose(
uint _id,
bool _tp,
PriceData calldata _priceData,
bytes calldata _signature
) external returns(uint _limitPrice, address _tigAsset);
function _checkGas() external view;
function _closePosition(
uint _id,
uint _price,
uint _percent
) external returns (IPosition.Trade memory _trade, uint256 _positionSize, int256 _payout);
}
interface IStable is IERC20 {
function burnFrom(address account, uint amount) external;
function mintFor(address account, uint amount) external;
}
interface ExtendedIERC20 is IERC20 {
function decimals() external view returns (uint);
}
interface ERC20Permit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
contract Trading is MetaContext, ITrading {
error LimitNotSet(); //7
error NotLiquidatable();
error TradingPaused();
error BadDeposit();
error BadWithdraw();
error ValueNotEqualToMargin();
error BadLeverage();
error NotMargin();
error NotAllowedPair();
error BelowMinPositionSize();
error BadClosePercent();
error NoPrice();
error LiqThreshold();
uint constant private DIVISION_CONSTANT = 1e10; // 100%
uint private constant liqPercent = 9e9; // 90%
struct Fees {
uint daoFees;
uint burnFees;
uint referralFees;
uint botFees;
}
Fees public openFees = Fees(
0,
0,
0,
0
);
Fees public closeFees = Fees(
0,
0,
0,
0
);
uint public limitOrderPriceRange = 1e8; // 1%
uint public maxWinPercent;
uint public vaultFundingPercent;
IPairsContract private pairsContract;
IPosition private position;
IGovNFT private gov;
ITradingExtension private tradingExtension;
struct Delay {
uint delay; // Block number where delay ends
bool actionType; // True for open, False for close
}
mapping(uint => Delay) public blockDelayPassed; // id => Delay
uint public blockDelay;
mapping(uint => uint) public limitDelay; // id => block.timestamp
mapping(address => bool) public allowedVault;
struct Proxy {
address proxy;
uint256 time;
}
mapping(address => Proxy) public proxyApprovals;
constructor(
address _position,
address _gov,
address _pairsContract
)
{
position = IPosition(_position);
gov = IGovNFT(_gov);
pairsContract = IPairsContract(_pairsContract);
}
// ===== END-USER FUNCTIONS =====
/**
* @param _tradeInfo Trade info
* @param _priceData verifiable off-chain price data
* @param _signature node signature
* @param _permitData data and signature needed for token approval
* @param _trader address the trade is initiated for
*/
function initiateMarketOrder(
TradeInfo calldata _tradeInfo,
PriceData calldata _priceData,
bytes calldata _signature,
ERC20PermitData calldata _permitData,
address _trader
)
external
{
_validateProxy(_trader);
_checkDelay(position.getCount(), true);
_checkVault(_tradeInfo.stableVault, _tradeInfo.marginAsset);
address _tigAsset = IStableVault(_tradeInfo.stableVault).stable();
tradingExtension.validateTrade(_tradeInfo.asset, _tigAsset, _tradeInfo.margin, _tradeInfo.leverage);
tradingExtension._setReferral(_tradeInfo.referral, _trader);
uint256 _marginAfterFees = _tradeInfo.margin - _handleOpenFees(_tradeInfo.asset, _tradeInfo.margin*_tradeInfo.leverage/1e18, _trader, _tigAsset, false);
uint256 _positionSize = _marginAfterFees * _tradeInfo.leverage / 1e18;
_handleDeposit(_tigAsset, _tradeInfo.marginAsset, _tradeInfo.margin, _tradeInfo.stableVault, _permitData, _trader);
uint256 _isLong = _tradeInfo.direction ? 1 : 2;
(uint256 _price,) = tradingExtension.getVerifiedPrice(_tradeInfo.asset, _priceData, _signature, _isLong);
IPosition.MintTrade memory _mintTrade = IPosition.MintTrade(
_trader,
_marginAfterFees,
_tradeInfo.leverage,
_tradeInfo.asset,
_tradeInfo.direction,
_price,
_tradeInfo.tpPrice,
_tradeInfo.slPrice,
0,
_tigAsset
);
_checkSl(_tradeInfo.slPrice, _tradeInfo.direction, _price);
unchecked {
if (_tradeInfo.direction) {
tradingExtension.modifyLongOi(_tradeInfo.asset, _tigAsset, true, _positionSize);
} else {
tradingExtension.modifyShortOi(_tradeInfo.asset, _tigAsset, true, _positionSize);
}
}
_updateFunding(_tradeInfo.asset, _tigAsset);
position.mint(
_mintTrade
);
unchecked {
emit PositionOpened(_tradeInfo, 0, _price, position.getCount()-1, _trader, _marginAfterFees);
}
}
/**
* @dev initiate closing position
* @param _id id of the position NFT
* @param _percent percent of the position being closed in BP
* @param _priceData verifiable off-chain price data
* @param _signature node signature
* @param _stableVault StableVault address
* @param _outputToken Token received upon closing trade
* @param _trader address the trade is initiated for
*/
function initiateCloseOrder(
uint _id,
uint _percent,
PriceData calldata _priceData,
bytes calldata _signature,
address _stableVault,
address _outputToken,
address _trader
)
external
{
_validateProxy(_trader);
_checkDelay(_id, false);
_checkOwner(_id, _trader);
_checkVault(_stableVault, _outputToken);
IPosition.Trade memory _trade = position.trades(_id);
if (_trade.orderType != 0) revert("4"); //IsLimit
(uint256 _price,) = tradingExtension.getVerifiedPrice(_trade.asset, _priceData, _signature, 0);
if (_percent > DIVISION_CONSTANT || _percent == 0) revert BadClosePercent();
_closePosition(_id, _percent, _price, _stableVault, _outputToken, false);
}
/**
* @param _id position id
* @param _addMargin margin amount used to add to the position
* @param _priceData verifiable off-chain price data
* @param _signature node signature
* @param _stableVault StableVault address
* @param _marginAsset Token being used to add to the position
* @param _permitData data and signature needed for token approval
* @param _trader address the trade is initiated for
*/
function addToPosition(
uint _id,
uint _addMargin,
PriceData calldata _priceData,
bytes calldata _signature,
address _stableVault,
address _marginAsset,
ERC20PermitData calldata _permitData,
address _trader
)
external
{
_validateProxy(_trader);
_checkOwner(_id, _trader);
_checkDelay(_id, true);
IPosition.Trade memory _trade = position.trades(_id);
tradingExtension.validateTrade(_trade.asset, _trade.tigAsset, _trade.margin + _addMargin, _trade.leverage);
_checkVault(_stableVault, _marginAsset);
if (_trade.orderType != 0) revert("4"); //IsLimit
uint _fee = _handleOpenFees(_trade.asset, _addMargin*_trade.leverage/1e18, _trader, _trade.tigAsset, false);
_handleDeposit(
_trade.tigAsset,
_marginAsset,
_addMargin - _fee,
_stableVault,
_permitData,
_trader
);
position.setAccInterest(_id);
unchecked {
(uint256 _price,) = tradingExtension.getVerifiedPrice(_trade.asset, _priceData, _signature, _trade.direction ? 1 : 2);
uint _positionSize = (_addMargin - _fee) * _trade.leverage / 1e18;
if (_trade.direction) {
tradingExtension.modifyLongOi(_trade.asset, _trade.tigAsset, true, _positionSize);
} else {
tradingExtension.modifyShortOi(_trade.asset, _trade.tigAsset, true, _positionSize);
}
_updateFunding(_trade.asset, _trade.tigAsset);
_addMargin -= _fee;
uint _newMargin = _trade.margin + _addMargin;
uint _newPrice = _trade.price*_trade.margin/_newMargin + _price*_addMargin/_newMargin;
position.addToPosition(
_trade.id,
_newMargin,
_newPrice
);
emit AddToPosition(_trade.id, _newMargin, _newPrice, _trade.trader);
}
}
/**
* @param _tradeInfo Trade info
* @param _orderType type of limit order used to open the position
* @param _price limit price
* @param _permitData data and signature needed for token approval
* @param _trader address the trade is initiated for
*/
function initiateLimitOrder(
TradeInfo calldata _tradeInfo,
uint256 _orderType, // 1 limit, 2 stop
uint256 _price,
ERC20PermitData calldata _permitData,
address _trader
)
external
{
_validateProxy(_trader);
address _tigAsset = IStableVault(_tradeInfo.stableVault).stable();
tradingExtension.validateTrade(_tradeInfo.asset, _tigAsset, _tradeInfo.margin, _tradeInfo.leverage);
_checkVault(_tradeInfo.stableVault, _tradeInfo.marginAsset);
if (_orderType == 0) revert("5");
if (_price == 0) revert NoPrice();
tradingExtension._setReferral(_tradeInfo.referral, _trader);
_handleDeposit(_tigAsset, _tradeInfo.marginAsset, _tradeInfo.margin, _tradeInfo.stableVault, _permitData, _trader);
_checkSl(_tradeInfo.slPrice, _tradeInfo.direction, _price);
uint256 _id = position.getCount();
position.mint(
IPosition.MintTrade(
_trader,
_tradeInfo.margin,
_tradeInfo.leverage,
_tradeInfo.asset,
_tradeInfo.direction,
_price,
_tradeInfo.tpPrice,
_tradeInfo.slPrice,
_orderType,
_tigAsset
)
);
limitDelay[_id] = block.timestamp + 4;
emit PositionOpened(_tradeInfo, _orderType, _price, _id, _trader, _tradeInfo.margin);
}
/**
* @param _id position ID
* @param _trader address the trade is initiated for
*/
function cancelLimitOrder(
uint256 _id,
address _trader
)
external
{
_validateProxy(_trader);
_checkOwner(_id, _trader);
IPosition.Trade memory _trade = position.trades(_id);
if (_trade.orderType == 0) revert();
IStable(_trade.tigAsset).mintFor(_trader, _trade.margin);
position.burn(_id);
emit LimitCancelled(_id, _trader);
}
/**
* @param _id position id
* @param _marginAsset Token being used to add to the position
* @param _stableVault StableVault address
* @param _addMargin margin amount being added to the position
* @param _permitData data and signature needed for token approval
* @param _trader address the trade is initiated for
*/
function addMargin(
uint256 _id,
address _marginAsset,
address _stableVault,
uint256 _addMargin,
ERC20PermitData calldata _permitData,
address _trader
)
external
{
_validateProxy(_trader);
_checkOwner(_id, _trader);
_checkVault(_stableVault, _marginAsset);
IPosition.Trade memory _trade = position.trades(_id);
if (_trade.orderType != 0) revert(); //IsLimit
IPairsContract.Asset memory asset = pairsContract.idToAsset(_trade.asset);
_handleDeposit(_trade.tigAsset, _marginAsset, _addMargin, _stableVault, _permitData, _trader);
unchecked {
uint256 _newMargin = _trade.margin + _addMargin;
uint256 _newLeverage = _trade.margin * _trade.leverage / _newMargin;
if (_newLeverage < asset.minLeverage) revert("!lev");
position.modifyMargin(_id, _newMargin, _newLeverage);
emit MarginModified(_id, _newMargin, _newLeverage, true, _trader);
}
}
/**
* @param _id position id
* @param _stableVault StableVault address
* @param _outputToken token the trader will receive
* @param _removeMargin margin amount being removed from the position
* @param _priceData verifiable off-chain price data
* @param _signature node signature
* @param _trader address the trade is initiated for
*/
function removeMargin(
uint256 _id,
address _stableVault,
address _outputToken,
uint256 _removeMargin,
PriceData calldata _priceData,
bytes calldata _signature,
address _trader
)
external
{
_validateProxy(_trader);
_checkOwner(_id, _trader);
_checkVault(_stableVault, _outputToken);
IPosition.Trade memory _trade = position.trades(_id);
if (_trade.orderType != 0) revert(); //IsLimit
IPairsContract.Asset memory asset = pairsContract.idToAsset(_trade.asset);
uint256 _newMargin = _trade.margin - _removeMargin;
uint256 _newLeverage = _trade.margin * _trade.leverage / _newMargin;
if (_newLeverage > asset.maxLeverage) revert("!lev");
(uint _assetPrice,) = tradingExtension.getVerifiedPrice(_trade.asset, _priceData, _signature, 0);
(,int256 _payout) = TradingLibrary.pnl(_trade.direction, _assetPrice, _trade.price, _newMargin, _newLeverage, _trade.accInterest);
unchecked {
if (_payout <= int256(_newMargin*(DIVISION_CONSTANT-liqPercent)/DIVISION_CONSTANT)) revert LiqThreshold();
}
position.modifyMargin(_trade.id, _newMargin, _newLeverage);
_handleWithdraw(_trade, _stableVault, _outputToken, _removeMargin);
emit MarginModified(_trade.id, _newMargin, _newLeverage, false, _trader);
}
/**
* @param _type true for TP, false for SL
* @param _id position id
* @param _limitPrice TP/SL trigger price
* @param _priceData verifiable off-chain price data
* @param _signature node signature
* @param _trader address the trade is initiated for
*/
function updateTpSl(
bool _type,
uint _id,
uint _limitPrice,
PriceData calldata _priceData,
bytes calldata _signature,
address _trader
)
external
{
_validateProxy(_trader);
_checkOwner(_id, _trader);
IPosition.Trade memory _trade = position.trades(_id);
if (_trade.orderType != 0) revert("4"); //IsLimit
if (_type) {
position.modifyTp(_id, _limitPrice);
} else {
(uint256 _price,) = tradingExtension.getVerifiedPrice(_trade.asset, _priceData, _signature, 0);
_checkSl(_limitPrice, _trade.direction, _price);
position.modifySl(_id, _limitPrice);
}
emit UpdateTPSL(_id, _type, _limitPrice, _trader);
}
/**
* @param _id position id
* @param _priceData verifiable off-chain price data
* @param _signature node signature
*/
function executeLimitOrder(
uint _id,
PriceData calldata _priceData,
bytes calldata _signature
)
external
{
unchecked {
_checkDelay(_id, true);
tradingExtension._checkGas();
if (tradingExtension.paused()) revert TradingPaused();
require(block.timestamp >= limitDelay[_id]);
IPosition.Trade memory trade = position.trades(_id);
uint _fee = _handleOpenFees(trade.asset, trade.margin*trade.leverage/1e18, trade.trader, trade.tigAsset, true);
(uint256 _price, uint256 _spread) = tradingExtension.getVerifiedPrice(trade.asset, _priceData, _signature, 0);
if (trade.orderType == 0) revert("5");
if (_price > trade.price+trade.price*limitOrderPriceRange/DIVISION_CONSTANT || _price < trade.price-trade.price*limitOrderPriceRange/DIVISION_CONSTANT) revert("6"); //LimitNotMet
if (trade.direction && trade.orderType == 1) {
if (trade.price < _price) revert("6"); //LimitNotMet
} else if (!trade.direction && trade.orderType == 1) {
if (trade.price > _price) revert("6"); //LimitNotMet
} else if (!trade.direction && trade.orderType == 2) {
if (trade.price < _price) revert("6"); //LimitNotMet
trade.price = _price;
} else {
if (trade.price > _price) revert("6"); //LimitNotMet
trade.price = _price;
}
if(trade.direction) {
trade.price += trade.price * _spread / DIVISION_CONSTANT;
} else {
trade.price -= trade.price * _spread / DIVISION_CONSTANT;
}
if (trade.direction) {
tradingExtension.modifyLongOi(trade.asset, trade.tigAsset, true, trade.margin*trade.leverage/1e18);
} else {
tradingExtension.modifyShortOi(trade.asset, trade.tigAsset, true, trade.margin*trade.leverage/1e18);
}
_updateFunding(trade.asset, trade.tigAsset);
position.executeLimitOrder(_id, trade.price, trade.margin - _fee);
emit LimitOrderExecuted(trade.asset, trade.direction, trade.price, trade.leverage, trade.margin - _fee, _id, trade.trader, _msgSender());
}
}
/**
* @notice liquidate position
* @param _id id of the position NFT
* @param _priceData verifiable off-chain data
* @param _signature node signature
*/
function liquidatePosition(
uint _id,
PriceData calldata _priceData,
bytes calldata _signature
)
external
{
unchecked {
tradingExtension._checkGas();
IPosition.Trade memory _trade = position.trades(_id);
if (_trade.orderType != 0) revert("4"); //IsLimit
(uint256 _price,) = tradingExtension.getVerifiedPrice(_trade.asset, _priceData, _signature, 0);
(uint256 _positionSizeAfterPrice, int256 _payout) = TradingLibrary.pnl(_trade.direction, _price, _trade.price, _trade.margin, _trade.leverage, _trade.accInterest);
uint256 _positionSize = _trade.margin*_trade.leverage/1e18;
if (_payout > int256(_trade.margin*(DIVISION_CONSTANT-liqPercent)/DIVISION_CONSTANT)) revert NotLiquidatable();
if (_trade.direction) {
tradingExtension.modifyLongOi(_trade.asset, _trade.tigAsset, false, _positionSize);
} else {
tradingExtension.modifyShortOi(_trade.asset, _trade.tigAsset, false, _positionSize);
}
_updateFunding(_trade.asset, _trade.tigAsset);
_handleCloseFees(_trade.asset, type(uint).max, _trade.tigAsset, _positionSizeAfterPrice, _trade.trader, true);
position.burn(_id);
emit PositionLiquidated(_id, _trade.trader, _msgSender());
}
}
/**
* @dev close position at a pre-set price
* @param _id id of the position NFT
* @param _tp true if take profit
* @param _priceData verifiable off-chain price data
* @param _signature node signature
*/
function limitClose(
uint _id,
bool _tp,
PriceData calldata _priceData,
bytes calldata _signature
)
external
{
_checkDelay(_id, false);
(uint _limitPrice, address _tigAsset) = tradingExtension._limitClose(_id, _tp, _priceData, _signature);
_closePosition(_id, DIVISION_CONSTANT, _limitPrice, address(0), _tigAsset, true);
}
/**
* @notice Trader can approve a proxy wallet address for it to trade on its behalf. Can also provide proxy wallet with gas.
* @param _proxy proxy wallet address
* @param _timestamp end timestamp of approval period
*/
function approveProxy(address _proxy, uint256 _timestamp) external payable {
proxyApprovals[_msgSender()] = Proxy(
_proxy,
_timestamp
);
payable(_proxy).transfer(msg.value);
}
// ===== INTERNAL FUNCTIONS =====
/**
* @dev close the initiated position.
* @param _id id of the position NFT
* @param _percent percent of the position being closed
* @param _price pair price
* @param _stableVault StableVault address
* @param _outputToken Token that trader will receive
* @param _isBot false if closed via market order
*/
function _closePosition(
uint _id,
uint _percent,
uint _price,
address _stableVault,
address _outputToken,
bool _isBot
)
internal
{
(IPosition.Trade memory _trade, uint256 _positionSize, int256 _payout) = tradingExtension._closePosition(_id, _price, _percent);
position.setAccInterest(_id);
_updateFunding(_trade.asset, _trade.tigAsset);
if (_percent < DIVISION_CONSTANT) {
if ((_trade.margin*_trade.leverage*(DIVISION_CONSTANT-_percent)/DIVISION_CONSTANT)/1e18 < tradingExtension.minPos(_trade.tigAsset)) revert("!size");
position.reducePosition(_id, _percent);
} else {
position.burn(_id);
}
uint256 _toMint;
if (_payout > 0) {
unchecked {
_toMint = _handleCloseFees(_trade.asset, uint256(_payout)*_percent/DIVISION_CONSTANT, _trade.tigAsset, _positionSize*_percent/DIVISION_CONSTANT, _trade.trader, _isBot);
if (maxWinPercent > 0 && _toMint > _trade.margin*maxWinPercent/DIVISION_CONSTANT) {
_toMint = _trade.margin*maxWinPercent/DIVISION_CONSTANT;
}
}
_handleWithdraw(_trade, _stableVault, _outputToken, _toMint);
}
emit PositionClosed(_id, _price, _percent, _toMint, _trade.trader, _isBot ? _msgSender() : _trade.trader);
}
/**
* @dev handle stablevault deposits for different trading functions
* @param _tigAsset tigAsset token address
* @param _marginAsset token being deposited into stablevault
* @param _margin amount being deposited
* @param _stableVault StableVault address
* @param _permitData Data for approval via permit
* @param _trader Trader address to take tokens from
*/
function _handleDeposit(address _tigAsset, address _marginAsset, uint256 _margin, address _stableVault, ERC20PermitData calldata _permitData, address _trader) internal {
IStable tigAsset = IStable(_tigAsset);
if (_tigAsset != _marginAsset) {
if (_permitData.usePermit) {
ERC20Permit(_marginAsset).permit(_trader, address(this), _permitData.amount, _permitData.deadline, _permitData.v, _permitData.r, _permitData.s);
}
uint256 _balBefore = tigAsset.balanceOf(address(this));
uint _marginDecMultiplier = 10**(18-ExtendedIERC20(_marginAsset).decimals());
IERC20(_marginAsset).transferFrom(_trader, address(this), _margin/_marginDecMultiplier);
IERC20(_marginAsset).approve(_stableVault, type(uint).max);
IStableVault(_stableVault).deposit(_marginAsset, _margin/_marginDecMultiplier);
if (tigAsset.balanceOf(address(this)) != _balBefore + _margin) revert BadDeposit();
tigAsset.burnFrom(address(this), tigAsset.balanceOf(address(this)));
} else {
tigAsset.burnFrom(_trader, _margin);
}
}
/**
* @dev handle stablevault withdrawals for different trading functions
* @param _trade Position info
* @param _stableVault StableVault address
* @param _outputToken Output token address
* @param _toMint Amount of tigAsset minted to be used for withdrawal
*/
function _handleWithdraw(IPosition.Trade memory _trade, address _stableVault, address _outputToken, uint _toMint) internal {
IStable(_trade.tigAsset).mintFor(address(this), _toMint);
if (_outputToken == _trade.tigAsset) {
IERC20(_outputToken).transfer(_trade.trader, _toMint);
} else {
uint256 _balBefore = IERC20(_outputToken).balanceOf(address(this));
IStableVault(_stableVault).withdraw(_outputToken, _toMint);
if (IERC20(_outputToken).balanceOf(address(this)) != _balBefore + _toMint/(10**(18-ExtendedIERC20(_outputToken).decimals()))) revert BadWithdraw();
IERC20(_outputToken).transfer(_trade.trader, IERC20(_outputToken).balanceOf(address(this)) - _balBefore);
}
}
/**
* @dev handle fees distribution for opening
* @param _asset asset id
* @param _positionSize position size
* @param _trader trader address
* @param _tigAsset tigAsset address
* @param _isBot false if opened via market order
* @return _feePaid total fees paid during opening
*/
function _handleOpenFees(
uint _asset,
uint _positionSize,
address _trader,
address _tigAsset,
bool _isBot
)
internal
returns (uint _feePaid)
{
IPairsContract.Asset memory asset = pairsContract.idToAsset(_asset);
Fees memory _fees = openFees;
unchecked {
_fees.daoFees = _fees.daoFees * asset.feeMultiplier / DIVISION_CONSTANT;
_fees.burnFees = _fees.burnFees * asset.feeMultiplier / DIVISION_CONSTANT;
_fees.referralFees = _fees.referralFees * asset.feeMultiplier / DIVISION_CONSTANT;
_fees.botFees = _fees.botFees * asset.feeMultiplier / DIVISION_CONSTANT;
}
address _referrer = tradingExtension.getRef(_trader); //referrals.getReferral(referrals.getReferred(_trader));
if (_referrer != address(0)) {
unchecked {
IStable(_tigAsset).mintFor(
_referrer,
_positionSize
* _fees.referralFees // get referral fee%
/ DIVISION_CONSTANT // divide by 100%
);
}
_fees.daoFees = _fees.daoFees - _fees.referralFees*2;
}
if (_isBot) {
unchecked {
IStable(_tigAsset).mintFor(
_msgSender(),
_positionSize
* _fees.botFees // get bot fee%
/ DIVISION_CONSTANT // divide by 100%
);
}
_fees.daoFees = _fees.daoFees - _fees.botFees;
} else {
_fees.botFees = 0;
}
unchecked {
uint _daoFeesPaid = _positionSize * _fees.daoFees / DIVISION_CONSTANT;
_feePaid =
_positionSize
* (_fees.burnFees + _fees.botFees) // get total fee%
/ DIVISION_CONSTANT // divide by 100%
+ _daoFeesPaid;
emit FeesDistributed(
_tigAsset,
_daoFeesPaid,
_positionSize * _fees.burnFees / DIVISION_CONSTANT,
_referrer != address(0) ? _positionSize * _fees.referralFees / DIVISION_CONSTANT : 0,
_positionSize * _fees.botFees / DIVISION_CONSTANT,
_referrer
);
IStable(_tigAsset).mintFor(address(this), _daoFeesPaid);
}
gov.distribute(_tigAsset, IStable(_tigAsset).balanceOf(address(this)));
}
/**
* @dev handle fees distribution for closing
* @param _asset asset id
* @param _payout payout to trader before fees
* @param _tigAsset margin asset
* @param _positionSize position size
* @param _trader trader address
* @param _isBot false if closed via market order
* @return payout_ payout to trader after fees
*/
function _handleCloseFees(
uint _asset,
uint _payout,
address _tigAsset,
uint _positionSize,
address _trader,
bool _isBot
)
internal
returns (uint payout_)
{
IPairsContract.Asset memory asset = pairsContract.idToAsset(_asset);
Fees memory _fees = closeFees;
uint _daoFeesPaid;
uint _burnFeesPaid;
uint _referralFeesPaid;
unchecked {
_daoFeesPaid = (_positionSize*_fees.daoFees/DIVISION_CONSTANT)*asset.feeMultiplier/DIVISION_CONSTANT;
_burnFeesPaid = (_positionSize*_fees.burnFees/DIVISION_CONSTANT)*asset.feeMultiplier/DIVISION_CONSTANT;
}
uint _botFeesPaid;
address _referrer = tradingExtension.getRef(_trader);//referrals.getReferral(referrals.getReferred(_trader));
if (_referrer != address(0)) {
unchecked {
_referralFeesPaid = (_positionSize*_fees.referralFees/DIVISION_CONSTANT)*asset.feeMultiplier/DIVISION_CONSTANT;
}
IStable(_tigAsset).mintFor(
_referrer,
_referralFeesPaid
);
_daoFeesPaid = _daoFeesPaid-_referralFeesPaid*2;
}
if (_isBot) {
unchecked {
_botFeesPaid = (_positionSize*_fees.botFees/DIVISION_CONSTANT)*asset.feeMultiplier/DIVISION_CONSTANT;
IStable(_tigAsset).mintFor(
_msgSender(),
_botFeesPaid
);
}
_daoFeesPaid = _daoFeesPaid - _botFeesPaid;
}
emit FeesDistributed(_tigAsset, _daoFeesPaid, _burnFeesPaid, _referralFeesPaid, _botFeesPaid, _referrer);
payout_ = _payout - _daoFeesPaid - _burnFeesPaid - _botFeesPaid;
IStable(_tigAsset).mintFor(address(this), _daoFeesPaid);
IStable(_tigAsset).approve(address(gov), type(uint).max);
gov.distribute(_tigAsset, _daoFeesPaid);
return payout_;
}
/**
* @dev update funding rates after open interest changes
* @param _asset asset id
* @param _tigAsset tigAsset used for OI
*/
function _updateFunding(uint256 _asset, address _tigAsset) internal {
position.updateFunding(
_asset,
_tigAsset,
pairsContract.idToOi(_asset, _tigAsset).longOi,
pairsContract.idToOi(_asset, _tigAsset).shortOi,
pairsContract.idToAsset(_asset).baseFundingRate,
vaultFundingPercent
);
}
/**
* @dev check that SL price is valid compared to market price
* @param _sl SL price
* @param _direction long/short
* @param _price market price
*/
function _checkSl(uint _sl, bool _direction, uint _price) internal pure {
if (_direction) {
if (_sl > _price) revert("3"); //BadStopLoss
} else {
if (_sl < _price && _sl != 0) revert("3"); //BadStopLoss
}
}
/**
* @dev check that trader address owns the position
* @param _id position id
* @param _trader trader address
*/
function _checkOwner(uint _id, address _trader) internal view {
if (position.ownerOf(_id) != _trader) revert("2"); //NotPositionOwner
}
/**
* @notice Check that sufficient time has passed between opening and closing
* @dev This is to prevent profitable opening and closing in the same tx with two different prices in the "valid signature pool".
* @param _id position id
* @param _type true for opening, false for closing
*/
function _checkDelay(uint _id, bool _type) internal {
unchecked {
Delay memory _delay = blockDelayPassed[_id];
if (_delay.actionType == _type) {
blockDelayPassed[_id].delay = block.number + blockDelay;
} else {
if (block.number < _delay.delay) revert("0"); //Wait
blockDelayPassed[_id].delay = block.number + blockDelay;
blockDelayPassed[_id].actionType = _type;
}
}
}
/**
* @dev Check that the stablevault input is whitelisted and the margin asset is whitelisted in the vault
* @param _stableVault StableVault address
* @param _token Margin asset token address
*/
function _checkVault(address _stableVault, address _token) internal view {
require(allowedVault[_stableVault], "Unapproved stablevault");
require(_token == IStableVault(_stableVault).stable() || IStableVault(_stableVault).allowed(_token), "Token not approved in vault");
}
/**
* @dev Check that the trader has approved the proxy address to trade for it
* @param _trader Trader address
*/
function _validateProxy(address _trader) internal view {
if (_trader != _msgSender()) {
Proxy memory _proxy = proxyApprovals[_trader];
require(_proxy.proxy == _msgSender() && _proxy.time >= block.timestamp, "Proxy not approved");
}
}
// ===== GOVERNANCE-ONLY =====
/**
* @dev Sets block delay between opening and closing
* @notice In blocks not seconds
* @param _blockDelay delay amount
*/
function setBlockDelay(
uint _blockDelay
)
external
onlyOwner
{
blockDelay = _blockDelay;
}
/**
* @dev Whitelists a stablevault contract address
* @param _stableVault StableVault address
* @param _bool true if allowed
*/
function setAllowedVault(
address _stableVault,
bool _bool
)
external
onlyOwner
{
allowedVault[_stableVault] = _bool;
}
/**
* @dev Sets max payout % compared to margin
* @param _maxWinPercent payout %
*/
function setMaxWinPercent(
uint _maxWinPercent
)
external
onlyOwner
{
maxWinPercent = _maxWinPercent;
}
/**
* @dev Sets executable price range for limit orders
* @param _range price range in %
*/
function setLimitOrderPriceRange(uint _range) external onlyOwner {
limitOrderPriceRange = _range;
}
/**
* @dev Sets the fees for the trading protocol
* @param _open True if open fees are being set
* @param _daoFees Fees distributed to the DAO
* @param _burnFees Fees which get burned
* @param _referralFees Fees given to referrers
* @param _botFees Fees given to bots that execute limit orders
* @param _percent Percent of earned funding fees going to StableVault
*/
function setFees(bool _open, uint _daoFees, uint _burnFees, uint _referralFees, uint _botFees, uint _percent) external onlyOwner {
unchecked {
require(_daoFees >= _botFees+_referralFees*2);
if (_open) {
openFees.daoFees = _daoFees;
openFees.burnFees = _burnFees;
openFees.referralFees = _referralFees;
openFees.botFees = _botFees;
} else {
closeFees.daoFees = _daoFees;
closeFees.burnFees = _burnFees;
closeFees.referralFees = _referralFees;
closeFees.botFees = _botFees;
}
require(_percent <= DIVISION_CONSTANT);
vaultFundingPercent = _percent;
}
}
/**
* @dev Sets the extension contract address for trading
* @param _ext extension contract address
*/
function setTradingExtension(
address _ext
) external onlyOwner() {
tradingExtension = ITradingExtension(_ext);
}
// ===== EVENTS =====
event PositionOpened(
TradeInfo _tradeInfo,
uint _orderType,
uint _price,
uint _id,
address _trader,
uint _marginAfterFees
);
event PositionClosed(
uint _id,
uint _closePrice,
uint _percent,
uint _payout,
address _trader,
address _executor
);