-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathMargin_flat.sol
executable file
·1261 lines (1001 loc) · 44.4 KB
/
Margin_flat.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
// File: contracts/libraries/ChainAdapter.sol
pragma solidity ^0.8.0;
interface IArbSys {
function arbBlockNumber() external view returns (uint256);
}
library ChainAdapter {
address constant arbSys = address(100);
function blockNumber() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
if (chainId == 421611 || chainId == 42161) { // Arbitrum Testnet || Arbitrum Mainnet
return IArbSys(arbSys).arbBlockNumber();
} else {
return block.number;
}
}
}
// File: contracts/libraries/SignedMath.sol
pragma solidity ^0.8.0;
library SignedMath {
function abs(int256 x) internal pure returns (uint256) {
if (x < 0) {
return uint256(0 - x);
}
return uint256(x);
}
function addU(int256 x, uint256 y) internal pure returns (int256) {
require(y <= uint256(type(int256).max), "overflow");
return x + int256(y);
}
function subU(int256 x, uint256 y) internal pure returns (int256) {
require(y <= uint256(type(int256).max), "overflow");
return x - int256(y);
}
function mulU(int256 x, uint256 y) internal pure returns (int256) {
require(y <= uint256(type(int256).max), "overflow");
return x * int256(y);
}
function divU(int256 x, uint256 y) internal pure returns (int256) {
require(y <= uint256(type(int256).max), "overflow");
return x / int256(y);
}
}
// File: contracts/utils/Reentrant.sol
pragma solidity ^0.8.0;
abstract contract Reentrant {
bool private entered;
modifier nonReentrant() {
require(entered == false, "Reentrant: reentrant call");
entered = true;
_;
entered = false;
}
}
// File: contracts/core/interfaces/IWETH.sol
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
// File: contracts/core/interfaces/IPriceOracle.sol
pragma solidity ^0.8.0;
interface IPriceOracle {
function setupTwap(address amm) external;
function quoteFromAmmTwap(address amm, uint256 baseAmount) external view returns (uint256 quoteAmount);
function updateAmmTwap(address pair) external;
// index price maybe get from different oracle, like UniswapV3 TWAP,Chainklink, or others
// source represents which oracle used. 0 = UniswapV3 TWAP
function quote(
address baseToken,
address quoteToken,
uint256 baseAmount
) external view returns (uint256 quoteAmount, uint8 source);
function getIndexPrice(address amm) external view returns (uint256);
function getMarketPrice(address amm) external view returns (uint256);
function getMarkPrice(address amm) external view returns (uint256 price, bool isIndexPrice);
function getMarkPriceAfterSwap(
address amm,
uint256 quoteAmount,
uint256 baseAmount
) external view returns (uint256 price, bool isIndexPrice);
function getMarkPriceInRatio(
address amm,
uint256 quoteAmount,
uint256 baseAmount
)
external
view
returns (
uint256 resultBaseAmount,
uint256 resultQuoteAmount,
bool isIndexPrice
);
function getMarkPriceAcc(
address amm,
uint8 beta,
uint256 quoteAmount,
bool negative
) external view returns (uint256 baseAmount);
function getPremiumFraction(address amm) external view returns (int256);
}
// File: contracts/core/interfaces/IVault.sol
pragma solidity ^0.8.0;
interface IVault {
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, address indexed receiver, uint256 amount);
/// @notice deposit baseToken to user
function deposit(address user, uint256 amount) external;
/// @notice withdraw user's baseToken from margin contract to receiver
function withdraw(
address user,
address receiver,
uint256 amount
) external;
/// @notice get baseToken amount in margin
function reserve() external view returns (uint256);
}
// File: contracts/core/interfaces/IMargin.sol
pragma solidity ^0.8.0;
interface IMargin {
struct Position {
int256 quoteSize; //quote amount of position
int256 baseSize; //margin + fundingFee + unrealizedPnl + deltaBaseWhenClosePosition
uint256 tradeSize; //if quoteSize>0 unrealizedPnl = baseValueOfQuoteSize - tradeSize; if quoteSize<0 unrealizedPnl = tradeSize - baseValueOfQuoteSize;
}
event AddMargin(address indexed trader, uint256 depositAmount, Position position);
event RemoveMargin(
address indexed trader,
address indexed to,
uint256 withdrawAmount,
int256 fundingFee,
uint256 withdrawAmountFromMargin,
Position position
);
event OpenPosition(
address indexed trader,
uint8 side,
uint256 baseAmount,
uint256 quoteAmount,
int256 fundingFee,
Position position
);
event ClosePosition(
address indexed trader,
uint256 quoteAmount,
uint256 baseAmount,
int256 fundingFee,
Position position
);
event Liquidate(
address indexed liquidator,
address indexed trader,
address indexed to,
uint256 quoteAmount,
uint256 baseAmount,
uint256 bonus,
int256 fundingFee,
Position position
);
event UpdateCPF(uint256 timeStamp, int256 cpf);
/// @notice only factory can call this function
/// @param baseToken_ margin's baseToken.
/// @param quoteToken_ margin's quoteToken.
/// @param amm_ amm address.
function initialize(
address baseToken_,
address quoteToken_,
address amm_
) external;
/// @notice add margin to trader
/// @param trader .
/// @param depositAmount base amount to add.
function addMargin(address trader, uint256 depositAmount) external;
/// @notice remove margin to msg.sender
/// @param withdrawAmount base amount to withdraw.
function removeMargin(
address trader,
address to,
uint256 withdrawAmount
) external;
/// @notice open position with side and quoteAmount by msg.sender
/// @param side long or short.
/// @param quoteAmount quote amount.
function openPosition(
address trader,
uint8 side,
uint256 quoteAmount
) external returns (uint256 baseAmount);
/// @notice close msg.sender's position with quoteAmount
/// @param quoteAmount quote amount to close.
function closePosition(address trader, uint256 quoteAmount) external returns (uint256 baseAmount);
/// @notice liquidate trader
function liquidate(address trader, address to)
external
returns (
uint256 quoteAmount,
uint256 baseAmount,
uint256 bonus
);
function updateCPF() external returns (int256);
/// @notice get factory address
function factory() external view returns (address);
/// @notice get config address
function config() external view returns (address);
/// @notice get base token address
function baseToken() external view returns (address);
/// @notice get quote token address
function quoteToken() external view returns (address);
/// @notice get amm address of this margin
function amm() external view returns (address);
/// @notice get all users' net position of quote
function netPosition() external view returns (int256 netQuotePosition);
/// @notice get all users' net position of quote
function totalPosition() external view returns (uint256 totalQuotePosition);
/// @notice get trader's position
function getPosition(address trader)
external
view
returns (
int256 baseSize,
int256 quoteSize,
uint256 tradeSize
);
/// @notice get withdrawable margin of trader
function getWithdrawable(address trader) external view returns (uint256 amount);
/// @notice check if can liquidate this trader's position
function canLiquidate(address trader) external view returns (bool);
/// @notice calculate the latest funding fee with current position
function calFundingFee(address trader) external view returns (int256 fundingFee);
/// @notice calculate the latest debt ratio with Pnl and funding fee
function calDebtRatio(address trader) external view returns (uint256 debtRatio);
function calUnrealizedPnl(address trader) external view returns (int256);
function getNewLatestCPF() external view returns (int256);
function querySwapBaseWithAmm(bool isLong, uint256 quoteAmount) external view returns (uint256);
}
// File: contracts/core/interfaces/IConfig.sol
pragma solidity ^0.8.0;
interface IConfig {
event PriceOracleChanged(address indexed oldOracle, address indexed newOracle);
event RebasePriceGapChanged(uint256 oldGap, uint256 newGap);
event RebaseIntervalChanged(uint256 oldInterval, uint256 newInterval);
event TradingSlippageChanged(uint256 oldTradingSlippage, uint256 newTradingSlippage);
event RouterRegistered(address indexed router);
event RouterUnregistered(address indexed router);
event SetLiquidateFeeRatio(uint256 oldLiquidateFeeRatio, uint256 liquidateFeeRatio);
event SetLiquidateThreshold(uint256 oldLiquidateThreshold, uint256 liquidateThreshold);
event SetLpWithdrawThresholdForNet(uint256 oldLpWithdrawThresholdForNet, uint256 lpWithdrawThresholdForNet);
event SetLpWithdrawThresholdForTotal(uint256 oldLpWithdrawThresholdForTotal, uint256 lpWithdrawThresholdForTotal);
event SetInitMarginRatio(uint256 oldInitMarginRatio, uint256 initMarginRatio);
event SetBeta(uint256 oldBeta, uint256 beta);
event SetFeeParameter(uint256 oldFeeParameter, uint256 feeParameter);
event SetMaxCPFBoost(uint256 oldMaxCPFBoost, uint256 maxCPFBoost);
event SetEmergency(address indexed router);
/// @notice get price oracle address.
function priceOracle() external view returns (address);
/// @notice get beta of amm.
function beta() external view returns (uint8);
/// @notice get feeParameter of amm.
function feeParameter() external view returns (uint256);
/// @notice get init margin ratio of margin.
function initMarginRatio() external view returns (uint256);
/// @notice get liquidate threshold of margin.
function liquidateThreshold() external view returns (uint256);
/// @notice get liquidate fee ratio of margin.
function liquidateFeeRatio() external view returns (uint256);
/// @notice get trading slippage of amm.
function tradingSlippage() external view returns (uint256);
/// @notice get rebase gap of amm.
function rebasePriceGap() external view returns (uint256);
/// @notice get lp withdraw threshold of amm.
function lpWithdrawThresholdForNet() external view returns (uint256);
/// @notice get lp withdraw threshold of amm.
function lpWithdrawThresholdForTotal() external view returns (uint256);
function rebaseInterval() external view returns (uint256);
function routerMap(address) external view returns (bool);
function maxCPFBoost() external view returns (uint256);
function inEmergency(address router) external view returns (bool);
function registerRouter(address router) external;
function unregisterRouter(address router) external;
/// @notice Set a new oracle
/// @param newOracle new oracle address.
function setPriceOracle(address newOracle) external;
/// @notice Set a new beta of amm
/// @param newBeta new beta.
function setBeta(uint8 newBeta) external;
/// @notice Set a new rebase gap of amm
/// @param newGap new gap.
function setRebasePriceGap(uint256 newGap) external;
function setRebaseInterval(uint256 interval) external;
/// @notice Set a new trading slippage of amm
/// @param newTradingSlippage .
function setTradingSlippage(uint256 newTradingSlippage) external;
/// @notice Set a new init margin ratio of margin
/// @param marginRatio new init margin ratio.
function setInitMarginRatio(uint256 marginRatio) external;
/// @notice Set a new liquidate threshold of margin
/// @param threshold new liquidate threshold of margin.
function setLiquidateThreshold(uint256 threshold) external;
/// @notice Set a new lp withdraw threshold of amm net position
/// @param newLpWithdrawThresholdForNet new lp withdraw threshold of amm.
function setLpWithdrawThresholdForNet(uint256 newLpWithdrawThresholdForNet) external;
/// @notice Set a new lp withdraw threshold of amm total position
/// @param newLpWithdrawThresholdForTotal new lp withdraw threshold of amm.
function setLpWithdrawThresholdForTotal(uint256 newLpWithdrawThresholdForTotal) external;
/// @notice Set a new liquidate fee of margin
/// @param feeRatio new liquidate fee of margin.
function setLiquidateFeeRatio(uint256 feeRatio) external;
/// @notice Set a new feeParameter.
/// @param newFeeParameter New feeParameter get from AMM swap fee.
/// @dev feeParameter = (1/fee -1 ) *100 where fee set by owner.
function setFeeParameter(uint256 newFeeParameter) external;
function setMaxCPFBoost(uint256 newMaxCPFBoost) external;
function setEmergency(address router) external;
}
// File: contracts/core/interfaces/IAmm.sol
pragma solidity ^0.8.0;
interface IAmm {
event Mint(address indexed sender, address indexed to, uint256 baseAmount, uint256 quoteAmount, uint256 liquidity);
event Burn(address indexed sender, address indexed to, uint256 baseAmount, uint256 quoteAmount, uint256 liquidity);
event Swap(address indexed trader, address indexed inputToken, address indexed outputToken, uint256 inputAmount, uint256 outputAmount);
event ForceSwap(address indexed trader, address indexed inputToken, address indexed outputToken, uint256 inputAmount, uint256 outputAmount);
event Rebase(uint256 quoteReserveBefore, uint256 quoteReserveAfter, uint256 _baseReserve , uint256 quoteReserveFromInternal, uint256 quoteReserveFromExternal );
event Sync(uint112 reserveBase, uint112 reserveQuote);
// only factory can call this function
function initialize(
address baseToken_,
address quoteToken_,
address margin_
) external;
function mint(address to)
external
returns (
uint256 baseAmount,
uint256 quoteAmount,
uint256 liquidity
);
function burn(address to)
external
returns (
uint256 baseAmount,
uint256 quoteAmount,
uint256 liquidity
);
// only binding margin can call this function
function swap(
address trader,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
) external returns (uint256[2] memory amounts);
// only binding margin can call this function
function forceSwap(
address trader,
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
) external;
function rebase() external returns (uint256 quoteReserveAfter);
function collectFee() external returns (bool feeOn);
function factory() external view returns (address);
function config() external view returns (address);
function baseToken() external view returns (address);
function quoteToken() external view returns (address);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function margin() external view returns (address);
function lastPrice() external view returns (uint256);
function getReserves()
external
view
returns (
uint112 reserveBase,
uint112 reserveQuote,
uint32 blockTimestamp
);
function estimateSwap(
address inputToken,
address outputToken,
uint256 inputAmount,
uint256 outputAmount
) external view returns (uint256[2] memory amounts);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function getFeeLiquidity() external view returns (uint256);
function getTheMaxBurnLiquidity() external view returns (uint256 maxLiquidity);
}
// File: contracts/core/interfaces/IAmmFactory.sol
pragma solidity ^0.8.0;
interface IAmmFactory {
event AmmCreated(address indexed baseToken, address indexed quoteToken, address amm);
function createAmm(address baseToken, address quoteToken) external returns (address amm);
function initAmm(
address baseToken,
address quoteToken,
address margin
) external;
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function upperFactory() external view returns (address);
function config() external view returns (address);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getAmm(address baseToken, address quoteToken) external view returns (address amm);
}
// File: contracts/core/interfaces/IMarginFactory.sol
pragma solidity ^0.8.0;
interface IMarginFactory {
event MarginCreated(address indexed baseToken, address indexed quoteToken, address margin);
function createMargin(address baseToken, address quoteToken) external returns (address margin);
function initMargin(
address baseToken,
address quoteToken,
address amm
) external;
function upperFactory() external view returns (address);
function config() external view returns (address);
function getMargin(address baseToken, address quoteToken) external view returns (address margin);
}
// File: contracts/core/interfaces/IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external pure returns (uint8);
}
// File: contracts/core/Margin.sol
pragma solidity ^0.8.0;
contract Margin is IMargin, IVault, Reentrant {
using SignedMath for int256;
address public immutable override factory;
address public override config;
address public override amm;
address public override baseToken;
address public override quoteToken;
mapping(address => Position) public traderPositionMap;
mapping(address => int256) public traderCPF; //trader's latestCPF checkpoint, to calculate funding fee
uint256 public override reserve;
uint256 public lastUpdateCPF; //last timestamp update cpf
uint256 public totalQuoteLong;
uint256 public totalQuoteShort;
int256 internal latestCPF; //latestCPF with 1e18 multiplied
constructor() {
factory = msg.sender;
}
function initialize(
address baseToken_,
address quoteToken_,
address amm_
) external override {
require(factory == msg.sender, "Margin.initialize: FORBIDDEN");
baseToken = baseToken_;
quoteToken = quoteToken_;
amm = amm_;
config = IMarginFactory(factory).config();
}
//@notice before add margin, ensure contract's baseToken balance larger than depositAmount
function addMargin(address trader, uint256 depositAmount) external override nonReentrant {
uint256 balance = IERC20(baseToken).balanceOf(address(this));
uint256 _reserve = reserve;
require(depositAmount <= balance - _reserve, "Margin.addMargin: WRONG_DEPOSIT_AMOUNT");
Position memory traderPosition = traderPositionMap[trader];
traderPosition.baseSize = traderPosition.baseSize.addU(depositAmount);
traderPositionMap[trader] = traderPosition;
reserve = _reserve + depositAmount;
emit AddMargin(trader, depositAmount, traderPosition);
}
//remove baseToken from trader's fundingFee+unrealizedPnl+margin, remain position need to meet the requirement of initMarginRatio
function removeMargin(
address trader,
address to,
uint256 withdrawAmount
) external override nonReentrant {
require(withdrawAmount > 0, "Margin.removeMargin: ZERO_WITHDRAW_AMOUNT");
require(IConfig(config).routerMap(msg.sender), "Margin.removeMargin: FORBIDDEN");
int256 _latestCPF = updateCPF();
Position memory traderPosition = traderPositionMap[trader];
//after last time operating trader's position, new fundingFee to earn.
int256 fundingFee = _calFundingFee(trader, _latestCPF);
//if close all position, trader can withdraw how much and earn how much pnl
(uint256 withdrawableAmount, int256 unrealizedPnl) = _getWithdrawable(
traderPosition.quoteSize,
traderPosition.baseSize + fundingFee,
traderPosition.tradeSize
);
require(withdrawAmount <= withdrawableAmount, "Margin.removeMargin: NOT_ENOUGH_WITHDRAWABLE");
uint256 withdrawAmountFromMargin;
//withdraw from fundingFee firstly, then unrealizedPnl, finally margin
int256 uncoverAfterFundingFee = int256(1).mulU(withdrawAmount) - fundingFee;
if (uncoverAfterFundingFee > 0) {
//fundingFee cant cover withdrawAmount, use unrealizedPnl and margin.
//update tradeSize only, no quoteSize, so can sub uncoverAfterFundingFee directly
if (uncoverAfterFundingFee <= unrealizedPnl) {
traderPosition.tradeSize -= uncoverAfterFundingFee.abs();
} else {
//fundingFee and unrealizedPnl cant cover withdrawAmount, use margin
withdrawAmountFromMargin = (uncoverAfterFundingFee - unrealizedPnl).abs();
//update tradeSize to current price to make unrealizedPnl zero
traderPosition.tradeSize = traderPosition.quoteSize < 0
? (int256(1).mulU(traderPosition.tradeSize) - unrealizedPnl).abs()
: (int256(1).mulU(traderPosition.tradeSize) + unrealizedPnl).abs();
}
}
traderPosition.baseSize = traderPosition.baseSize - uncoverAfterFundingFee;
traderPositionMap[trader] = traderPosition;
traderCPF[trader] = _latestCPF;
_withdraw(trader, to, withdrawAmount);
emit RemoveMargin(trader, to, withdrawAmount, fundingFee, withdrawAmountFromMargin, traderPosition);
}
function openPosition(
address trader,
uint8 side,
uint256 quoteAmount
) external override nonReentrant returns (uint256 baseAmount) {
require(side == 0 || side == 1, "Margin.openPosition: INVALID_SIDE");
require(quoteAmount > 0, "Margin.openPosition: ZERO_QUOTE_AMOUNT");
require(IConfig(config).routerMap(msg.sender), "Margin.openPosition: FORBIDDEN");
int256 _latestCPF = updateCPF();
Position memory traderPosition = traderPositionMap[trader];
uint256 quoteSizeAbs = traderPosition.quoteSize.abs();
int256 fundingFee = _calFundingFee(trader, _latestCPF);
uint256 quoteAmountMax;
{
int256 marginAcc;
if (traderPosition.quoteSize == 0) {
marginAcc = traderPosition.baseSize + fundingFee;
} else if (traderPosition.quoteSize > 0) {
//simulate to close short
uint256[2] memory result = IAmm(amm).estimateSwap(
address(quoteToken),
address(baseToken),
traderPosition.quoteSize.abs(),
0
);
marginAcc = traderPosition.baseSize.addU(result[1]) + fundingFee;
} else {
//simulate to close long
uint256[2] memory result = IAmm(amm).estimateSwap(
address(baseToken),
address(quoteToken),
0,
traderPosition.quoteSize.abs()
);
marginAcc = traderPosition.baseSize.subU(result[0]) + fundingFee;
}
require(marginAcc > 0, "Margin.openPosition: INVALID_MARGIN_ACC");
(, uint112 quoteReserve, ) = IAmm(amm).getReserves();
(, uint256 _quoteAmountT, bool isIndexPrice) = IPriceOracle(IConfig(config).priceOracle())
.getMarkPriceInRatio(amm, 0, marginAcc.abs());
uint256 _quoteAmount = isIndexPrice
? _quoteAmountT
: IAmm(amm).estimateSwap(baseToken, quoteToken, marginAcc.abs(), 0)[1];
quoteAmountMax =
(quoteReserve * 10000 * _quoteAmount) /
((IConfig(config).initMarginRatio() * quoteReserve) + (200 * _quoteAmount * IConfig(config).beta()));
}
bool isLong = side == 0;
baseAmount = _addPositionWithAmm(trader, isLong, quoteAmount);
require(baseAmount > 0, "Margin.openPosition: TINY_QUOTE_AMOUNT");
if (
traderPosition.quoteSize == 0 ||
(traderPosition.quoteSize < 0 == isLong) ||
(traderPosition.quoteSize > 0 == !isLong)
) {
//baseAmount is real base cost
traderPosition.tradeSize = traderPosition.tradeSize + baseAmount;
} else {
if (quoteAmount < quoteSizeAbs) {
//entry price not change
traderPosition.tradeSize =
traderPosition.tradeSize -
(quoteAmount * traderPosition.tradeSize) /
quoteSizeAbs;
} else {
//after close all opposite position, create new position with new entry price
traderPosition.tradeSize = ((quoteAmount - quoteSizeAbs) * baseAmount) / quoteAmount;
}
}
if (isLong) {
traderPosition.quoteSize = traderPosition.quoteSize.subU(quoteAmount);
traderPosition.baseSize = traderPosition.baseSize.addU(baseAmount) + fundingFee;
totalQuoteLong = totalQuoteLong + quoteAmount;
} else {
traderPosition.quoteSize = traderPosition.quoteSize.addU(quoteAmount);
traderPosition.baseSize = traderPosition.baseSize.subU(baseAmount) + fundingFee;
totalQuoteShort = totalQuoteShort + quoteAmount;
}
require(traderPosition.quoteSize.abs() <= quoteAmountMax, "Margin.openPosition: INIT_MARGIN_RATIO");
require(
_calDebtRatio(traderPosition.quoteSize, traderPosition.baseSize) < IConfig(config).liquidateThreshold(),
"Margin.openPosition: WILL_BE_LIQUIDATED"
);
traderCPF[trader] = _latestCPF;
traderPositionMap[trader] = traderPosition;
emit OpenPosition(trader, side, baseAmount, quoteAmount, fundingFee, traderPosition);
}
function closePosition(address trader, uint256 quoteAmount)
external
override
nonReentrant
returns (uint256 baseAmount)
{
require(IConfig(config).routerMap(msg.sender), "Margin.openPosition: FORBIDDEN");
int256 _latestCPF = updateCPF();
Position memory traderPosition = traderPositionMap[trader];
require(quoteAmount != 0, "Margin.closePosition: ZERO_POSITION");
uint256 quoteSizeAbs = traderPosition.quoteSize.abs();
require(quoteAmount <= quoteSizeAbs, "Margin.closePosition: ABOVE_POSITION");
bool isLong = traderPosition.quoteSize < 0;
int256 fundingFee = _calFundingFee(trader, _latestCPF);
require(
_calDebtRatio(traderPosition.quoteSize, traderPosition.baseSize + fundingFee) <
IConfig(config).liquidateThreshold(),
"Margin.closePosition: DEBT_RATIO_OVER"
);
baseAmount = _minusPositionWithAmm(trader, isLong, quoteAmount);
traderPosition.tradeSize -= (quoteAmount * traderPosition.tradeSize) / quoteSizeAbs;
if (isLong) {
totalQuoteLong = totalQuoteLong - quoteAmount;
traderPosition.quoteSize = traderPosition.quoteSize.addU(quoteAmount);
traderPosition.baseSize = traderPosition.baseSize.subU(baseAmount) + fundingFee;
} else {
totalQuoteShort = totalQuoteShort - quoteAmount;
traderPosition.quoteSize = traderPosition.quoteSize.subU(quoteAmount);
traderPosition.baseSize = traderPosition.baseSize.addU(baseAmount) + fundingFee;
}
if (traderPosition.quoteSize == 0 && traderPosition.baseSize < 0) {
IAmm(amm).forceSwap(trader, quoteToken, baseToken, 0, traderPosition.baseSize.abs());
traderPosition.baseSize = 0;
}
traderCPF[trader] = _latestCPF;
traderPositionMap[trader] = traderPosition;
emit ClosePosition(trader, quoteAmount, baseAmount, fundingFee, traderPosition);
}
function liquidate(address trader, address to)
external
override
nonReentrant
returns (
uint256 quoteAmount,
uint256 baseAmount,
uint256 bonus
)
{
require(IConfig(config).routerMap(msg.sender), "Margin.openPosition: FORBIDDEN");
int256 _latestCPF = updateCPF();
Position memory traderPosition = traderPositionMap[trader];
int256 baseSize = traderPosition.baseSize;
int256 quoteSize = traderPosition.quoteSize;
require(quoteSize != 0, "Margin.liquidate: ZERO_POSITION");
quoteAmount = quoteSize.abs();
bool isLong = quoteSize < 0;
int256 fundingFee = _calFundingFee(trader, _latestCPF);
require(
_calDebtRatio(quoteSize, baseSize + fundingFee) >= IConfig(config).liquidateThreshold(),
"Margin.liquidate: NOT_LIQUIDATABLE"
);
{
(uint256 _baseAmountT, , bool isIndexPrice) = IPriceOracle(IConfig(config).priceOracle())
.getMarkPriceInRatio(amm, quoteAmount, 0);
baseAmount = isIndexPrice ? _baseAmountT : _querySwapBaseWithAmm(isLong, quoteAmount);
(uint256 _baseAmount, uint256 _quoteAmount) = (baseAmount, quoteAmount);
bonus = _executeSettle(trader, isIndexPrice, isLong, fundingFee, baseSize, _baseAmount, _quoteAmount);
if (isLong) {
totalQuoteLong = totalQuoteLong - quoteSize.abs();
} else {
totalQuoteShort = totalQuoteShort - quoteSize.abs();
}
}
traderCPF[trader] = _latestCPF;
if (bonus > 0) {
_withdraw(trader, to, bonus);
}
delete traderPositionMap[trader];
emit Liquidate(msg.sender, trader, to, quoteAmount, baseAmount, bonus, fundingFee, traderPosition);
}
function _executeSettle(
address _trader,
bool isIndexPrice,
bool isLong,
int256 fundingFee,
int256 baseSize,
uint256 baseAmount,
uint256 quoteAmount
) internal returns (uint256 bonus) {
int256 remainBaseAmountAfterLiquidate = isLong
? baseSize.subU(baseAmount) + fundingFee
: baseSize.addU(baseAmount) + fundingFee;
if (remainBaseAmountAfterLiquidate >= 0) {
bonus = (remainBaseAmountAfterLiquidate.abs() * IConfig(config).liquidateFeeRatio()) / 10000;
if (!isIndexPrice) {
_minusPositionWithAmm(_trader, isLong, quoteAmount);
}
if (remainBaseAmountAfterLiquidate.abs() > bonus) {
address treasury = IAmmFactory(IAmm(amm).factory()).feeTo();
if (treasury != address(0)) {
IERC20(baseToken).transfer(treasury, remainBaseAmountAfterLiquidate.abs() - bonus);
} else {
IAmm(amm).forceSwap(
_trader,
baseToken,
quoteToken,
remainBaseAmountAfterLiquidate.abs() - bonus,
0
);
}
}
} else {
if (!isIndexPrice) {
if (isLong) {
IAmm(amm).forceSwap(
_trader,
baseToken,
quoteToken,
((baseSize.subU(bonus) + fundingFee).abs()),
quoteAmount
);
} else {
IAmm(amm).forceSwap(
_trader,
quoteToken,
baseToken,
quoteAmount,
((baseSize.subU(bonus) + fundingFee).abs())
);
}
} else {
IAmm(amm).forceSwap(_trader, quoteToken, baseToken, 0, remainBaseAmountAfterLiquidate.abs());
}
}
}
function deposit(address user, uint256 amount) external override nonReentrant {
require(msg.sender == amm, "Margin.deposit: REQUIRE_AMM");
require(amount > 0, "Margin.deposit: AMOUNT_IS_ZERO");
uint256 balance = IERC20(baseToken).balanceOf(address(this));
require(amount <= balance - reserve, "Margin.deposit: INSUFFICIENT_AMOUNT");
reserve = reserve + amount;
emit Deposit(user, amount);
}
function withdraw(
address user,
address receiver,
uint256 amount
) external override nonReentrant {
require(msg.sender == amm, "Margin.withdraw: REQUIRE_AMM");
_withdraw(user, receiver, amount);
}
function _withdraw(
address user,
address receiver,
uint256 amount
) internal {
require(amount > 0, "Margin._withdraw: AMOUNT_IS_ZERO");
require(amount <= reserve, "Margin._withdraw: NOT_ENOUGH_RESERVE");
reserve = reserve - amount;
IERC20(baseToken).transfer(receiver, amount);
emit Withdraw(user, receiver, amount);
}