-
Notifications
You must be signed in to change notification settings - Fork 22
/
Amm_flat.sol
executable file
·1499 lines (1181 loc) · 52.4 KB
/
Amm_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/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/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/FullMath.sol
pragma solidity ^0.8.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
// todo unchecked
unchecked {
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (~denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// File: contracts/libraries/Math.sol
pragma solidity ^0.8.0;
library Math {
function min(uint256 x, uint256 y) internal pure returns (uint256) {
if (x > y) {
return y;
}
return x;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/libraries/UQ112x112.sol
pragma solidity ^0.8.0;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(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/IPairFactory.sol
pragma solidity ^0.8.0;
interface IPairFactory {
event NewPair(address indexed baseToken, address indexed quoteToken, address amm, address margin);
function createPair(address baseToken, address quotoToken) external returns (address amm, address margin);
function ammFactory() external view returns (address);
function marginFactory() external view returns (address);
function getAmm(address baseToken, address quoteToken) external view returns (address);
function getMargin(address baseToken, address quoteToken) external view returns (address);
}
// 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/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/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/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/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/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/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/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/interfaces/ILiquidityERC20.sol
pragma solidity ^0.8.0;
interface ILiquidityERC20 is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
}
// File: contracts/core/LiquidityERC20.sol
pragma solidity ^0.8.0;
contract LiquidityERC20 is ILiquidityERC20 {
string public constant override name = "APEX LP";
string public constant override symbol = "APEX-LP";
uint8 public constant override decimals = 18;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public immutable override DOMAIN_SEPARATOR;
uint256 public override totalSupply;
mapping(address => uint256) public override balanceOf;
mapping(address => mapping(address => uint256)) public override allowance;
mapping(address => uint256) public override nonces;
constructor() {
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes("1")),
chainId,
address(this)
)
);
}
function approve(address spender, uint256 value) external override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
if (allowance[from][msg.sender] != type(uint256).max) {
allowance[from][msg.sender] = allowance[from][msg.sender] - value;
}
_transfer(from, to, value);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(deadline >= block.timestamp, "LiquidityERC20: EXPIRED");
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "LiquidityERC20: INVALID_SIGNATURE");
_approve(owner, spender, value);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply + value;
balanceOf[to] = balanceOf[to] + value;
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] = balanceOf[from] - value;
totalSupply = totalSupply - value;
emit Transfer(from, address(0), value);
}
function _approve(
address owner,
address spender,
uint256 value
) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(
address from,
address to,
uint256 value
) private {
balanceOf[from] = balanceOf[from] - value;
balanceOf[to] = balanceOf[to] + value;
emit Transfer(from, to, value);
}
}
// File: contracts/core/Amm.sol
pragma solidity ^0.8.0;
contract Amm is IAmm, LiquidityERC20, Reentrant {
using UQ112x112 for uint224;
using SignedMath for int256;
uint256 public constant override MINIMUM_LIQUIDITY = 10**3;
address public immutable override factory;
address public override config;
address public override baseToken;
address public override quoteToken;
address public override margin;
uint256 public override price0CumulativeLast;
uint256 public override price1CumulativeLast;
uint256 public kLast;
uint256 public override lastPrice;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
uint112 private baseReserve; // uses single storage slot, accessible via getReserves
uint112 private quoteReserve; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast;
uint256 private lastBlockNumber;
uint256 private rebaseTimestampLast;
modifier onlyMargin() {
require(margin == msg.sender, "Amm: ONLY_MARGIN");
_;
}
constructor() {
factory = msg.sender;
}
function initialize(
address baseToken_,
address quoteToken_,
address margin_
) external override {
require(msg.sender == factory, "Amm.initialize: FORBIDDEN"); // sufficient check
baseToken = baseToken_;
quoteToken = quoteToken_;
margin = margin_;
config = IAmmFactory(factory).config();
}