-
Notifications
You must be signed in to change notification settings - Fork 32
/
MarketUtils.sol
2390 lines (2076 loc) · 101 KB
/
MarketUtils.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: BUSL-1.1
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "../data/DataStore.sol";
import "../event/EventEmitter.sol";
import "../bank/StrictBank.sol";
import "./Market.sol";
import "./MarketPoolValueInfo.sol";
import "./MarketToken.sol";
import "./MarketEventUtils.sol";
import "./MarketStoreUtils.sol";
import "../position/Position.sol";
import "../order/Order.sol";
import "../oracle/Oracle.sol";
import "../price/Price.sol";
import "../utils/Calc.sol";
import "../utils/Precision.sol";
// @title MarketUtils
// @dev Library for market functions
library MarketUtils {
using SafeCast for int256;
using SafeCast for uint256;
using Market for Market.Props;
using Position for Position.Props;
using Order for Order.Props;
using Price for Price.Props;
// @dev struct to store the prices of tokens of a market
// @param indexTokenPrice price of the market's index token
// @param longTokenPrice price of the market's long token
// @param shortTokenPrice price of the market's short token
struct MarketPrices {
Price.Props indexTokenPrice;
Price.Props longTokenPrice;
Price.Props shortTokenPrice;
}
// @dev struct for the result of the getNextFundingAmountPerSize call
// @param longsPayShorts whether longs pay shorts or shorts pay longs
// @param fundingAmountPerSize_LongCollateral_LongPosition funding amount per
// size for users with a long position using long collateral
// @param fundingAmountPerSize_LongCollateral_ShortPosition funding amount per
// size for users with a short position using long collateral
// @param fundingAmountPerSize_ShortCollateral_LongPosition funding amount per
// size for users with a long position using short collateral
// @param fundingAmountPerSize_ShortCollateral_ShortPosition funding amount per
// size for users with a short position using short collateral
struct GetNextFundingAmountPerSizeResult {
bool longsPayShorts;
uint256 fundingFactorPerSecond;
int256 fundingAmountPerSize_LongCollateral_LongPosition;
int256 fundingAmountPerSize_LongCollateral_ShortPosition;
int256 fundingAmountPerSize_ShortCollateral_LongPosition;
int256 fundingAmountPerSize_ShortCollateral_ShortPosition;
}
// @dev GetNextFundingAmountPerSizeCache struct used in getNextFundingAmountPerSize
// to avoid stack too deep errors
//
// @param durationInSeconds duration in seconds since the last funding update
//
// @param diffUsd the absolute difference in long and short open interest for the market
// @param totalOpenInterest the total long and short open interest for the market
// @param fundingUsd the funding amount in USD
//
// @param fundingUsdForLongCollateral the funding amount in USD for positions using the long token as collateral
// @param fundingUsdForShortCollateral the funding amount in USD for positions using the short token as collateral
struct GetNextFundingAmountPerSizeCache {
GetNextFundingAmountPerSizeOpenInterestCache oi;
GetNextFundingAmountPerSizeFundingPerSizeCache fps;
uint256 durationInSeconds;
uint256 diffUsd;
uint256 totalOpenInterest;
uint256 sizeOfLargerSide;
uint256 fundingUsd;
uint256 fundingUsdForLongCollateral;
uint256 fundingUsdForShortCollateral;
uint256 fundingAmountForLongCollateral;
uint256 fundingAmountForShortCollateral;
}
// @param longOpenInterestWithLongCollateral amount of long open interest using the long token as collateral
// @param longOpenInterestWithShortCollateral amount of long open interest using the short token as collateral
// @param shortOpenInterestWithLongCollateral amount of short open interest using the long token as collateral
// @param shortOpenInterestWithShortCollateral amount of short open interest using the short token as collateral
//
// @param longOpenInterest total long open interest for the market
// @param shortOpenInterest total short open interest for the market
struct GetNextFundingAmountPerSizeOpenInterestCache {
uint256 longOpenInterestWithLongCollateral;
uint256 longOpenInterestWithShortCollateral;
uint256 shortOpenInterestWithLongCollateral;
uint256 shortOpenInterestWithShortCollateral;
uint256 longOpenInterest;
uint256 shortOpenInterest;
}
// @param fundingAmountPerSize_LongCollateral_LongPosition funding per size for longs using the long token as collateral
// @param fundingAmountPerSize_LongCollateral_ShortPosition funding per size for shorts using the long token as collateral
// @param fundingAmountPerSize_ShortCollateral_LongPosition funding per size for longs using the short token as collateral
// @param fundingAmountPerSize_ShortCollateral_ShortPosition funding per size for shorts using the short token as collateral
//
// @param fundingAmountPerSizeDelta_LongCollateral_LongPosition the next funding amount per size for longs using the long token as collateral
// @param fundingAmountPerSizeDelta_LongCollateral_ShortPosition the next funding amount per size for longs using the short token as collateral
// @param fundingAmountPerSizeDelta_ShortCollateral_LongPosition the next funding amount per size for shorts using the long token as collateral
// @param fundingAmountPerSizeDelta_ShortCollateral_ShortPosition the next funding amount per size for shorts using the short token as collateral
struct GetNextFundingAmountPerSizeFundingPerSizeCache {
int256 fundingAmountPerSize_LongCollateral_LongPosition;
int256 fundingAmountPerSize_ShortCollateral_LongPosition;
int256 fundingAmountPerSize_LongCollateral_ShortPosition;
int256 fundingAmountPerSize_ShortCollateral_ShortPosition;
uint256 fundingAmountPerSizeDelta_LongCollateral_LongPosition;
uint256 fundingAmountPerSizeDelta_ShortCollateral_LongPosition;
uint256 fundingAmountPerSizeDelta_LongCollateral_ShortPosition;
uint256 fundingAmountPerSizeDelta_ShortCollateral_ShortPosition;
}
struct GetExpectedMinTokenBalanceCache {
uint256 poolAmount;
uint256 collateralForLongs;
uint256 collateralForShorts;
uint256 swapImpactPoolAmount;
uint256 claimableCollateralAmount;
uint256 claimableFeeAmount;
uint256 claimableUiFeeAmount;
uint256 affiliateRewardAmount;
}
// @dev get the market token's price
// @param dataStore DataStore
// @param market the market to check
// @param longTokenPrice the price of the long token
// @param shortTokenPrice the price of the short token
// @param indexTokenPrice the price of the index token
// @param maximize whether to maximize or minimize the market token price
// @return returns the market token's price
function getMarketTokenPrice(
DataStore dataStore,
Market.Props memory market,
Price.Props memory indexTokenPrice,
Price.Props memory longTokenPrice,
Price.Props memory shortTokenPrice,
bytes32 pnlFactorType,
bool maximize
) external view returns (int256, MarketPoolValueInfo.Props memory) {
MarketPoolValueInfo.Props memory poolValueInfo = getPoolValueInfo(
dataStore,
market,
indexTokenPrice,
longTokenPrice,
shortTokenPrice,
pnlFactorType,
maximize
);
if (poolValueInfo.poolValue == 0) { return (0, poolValueInfo); }
if (poolValueInfo.poolValue < 0) {
revert Errors.UnexpectedPoolValueForTokenPriceCalculation(poolValueInfo.poolValue);
}
uint256 supply = getMarketTokenSupply(MarketToken(payable(market.marketToken)));
if (supply == 0) {
revert Errors.UnexpectedSupplyForTokenPriceCalculation();
}
return (poolValueInfo.poolValue * Precision.WEI_PRECISION.toInt256() / supply.toInt256(), poolValueInfo);
}
// @dev get the total supply of the marketToken
// @param marketToken the marketToken
// @return the total supply of the marketToken
function getMarketTokenSupply(MarketToken marketToken) internal view returns (uint256) {
return marketToken.totalSupply();
}
// @dev get the opposite token of the market
// if the inputToken is the longToken return the shortToken and vice versa
// @param inputToken the input token
// @param market the market values
// @return the opposite token
function getOppositeToken(address inputToken, Market.Props memory market) internal pure returns (address) {
if (inputToken == market.longToken) {
return market.shortToken;
}
if (inputToken == market.shortToken) {
return market.longToken;
}
revert Errors.UnableToGetOppositeToken(inputToken, market.marketToken);
}
function validateSwapMarket(Market.Props memory market) internal pure {
if (market.longToken == market.shortToken) {
revert Errors.InvalidSwapMarket(market.marketToken);
}
}
// @dev get the token price from the stored MarketPrices
// @param token the token to get the price for
// @param the market values
// @param the market token prices
// @return the token price from the stored MarketPrices
function getCachedTokenPrice(address token, Market.Props memory market, MarketPrices memory prices) internal pure returns (Price.Props memory) {
if (token == market.longToken) {
return prices.longTokenPrice;
}
if (token == market.shortToken) {
return prices.shortTokenPrice;
}
if (token == market.indexToken) {
return prices.indexTokenPrice;
}
revert Errors.UnableToGetCachedTokenPrice(token, market.marketToken);
}
// @dev return the latest prices for the market tokens
// the secondary price for market.indexToken is overwritten for certain order
// types, use this value instead of the primary price for positions
// @param oracle Oracle
// @param market the market values
function getMarketPricesForPosition(Oracle oracle, Market.Props memory market) internal view returns (MarketPrices memory) {
return MarketPrices(
oracle.getLatestPrice(market.indexToken),
oracle.getLatestPrice(market.longToken),
oracle.getLatestPrice(market.shortToken)
);
}
// @dev return the primary prices for the market tokens
// @param oracle Oracle
// @param market the market values
function getMarketPrices(Oracle oracle, Market.Props memory market) internal view returns (MarketPrices memory) {
return MarketPrices(
oracle.getPrimaryPrice(market.indexToken),
oracle.getPrimaryPrice(market.longToken),
oracle.getPrimaryPrice(market.shortToken)
);
}
// @dev get the usd value of either the long or short tokens in the pool
// without accounting for the pnl of open positions
// @param dataStore DataStore
// @param market the market values
// @param prices the prices of the market tokens
// @param whether to return the value for the long or short token
// @return the usd value of either the long or short tokens in the pool
function getPoolUsdWithoutPnl(
DataStore dataStore,
Market.Props memory market,
MarketPrices memory prices,
bool isLong
) internal view returns (uint256) {
address token = isLong ? market.longToken : market.shortToken;
uint256 poolAmount = getPoolAmount(dataStore, market, token);
uint256 tokenPrice = isLong ? prices.longTokenPrice.min : prices.shortTokenPrice.min;
return poolAmount * tokenPrice;
}
// @dev get the USD value of a pool
// the value of a pool is the worth of the liquidity provider tokens in the pool - pending trader pnl
// we use the token index prices to calculate this and ignore price impact since if all positions were closed the
// net price impact should be zero
// @param dataStore DataStore
// @param market the market values
// @param longTokenPrice price of the long token
// @param shortTokenPrice price of the short token
// @param indexTokenPrice price of the index token
// @param maximize whether to maximize or minimize the pool value
// @return the value information of a pool
function getPoolValueInfo(
DataStore dataStore,
Market.Props memory market,
Price.Props memory indexTokenPrice,
Price.Props memory longTokenPrice,
Price.Props memory shortTokenPrice,
bytes32 pnlFactorType,
bool maximize
) public view returns (MarketPoolValueInfo.Props memory) {
MarketPoolValueInfo.Props memory result;
result.longTokenAmount = getPoolAmount(dataStore, market, market.longToken);
result.shortTokenAmount = getPoolAmount(dataStore, market, market.shortToken);
result.longTokenUsd = result.longTokenAmount * longTokenPrice.pickPrice(maximize);
result.shortTokenUsd = result.shortTokenAmount * shortTokenPrice.pickPrice(maximize);
uint256 poolValue = result.longTokenUsd + result.shortTokenUsd;
MarketPrices memory prices = MarketPrices(
indexTokenPrice,
longTokenPrice,
shortTokenPrice
);
result.totalBorrowingFees = getTotalPendingBorrowingFees(
dataStore,
market,
prices,
true
);
result.totalBorrowingFees += getTotalPendingBorrowingFees(
dataStore,
market,
prices,
false
);
result.borrowingFeePoolFactor = Precision.FLOAT_PRECISION - dataStore.getUint(Keys.BORROWING_FEE_RECEIVER_FACTOR);
poolValue += Precision.applyFactor(result.totalBorrowingFees, result.borrowingFeePoolFactor);
result.impactPoolAmount = getPositionImpactPoolAmount(dataStore, market.marketToken);
poolValue -= result.impactPoolAmount * indexTokenPrice.pickPrice(maximize);
// !maximize should be used for net pnl as a larger pnl leads to a smaller pool value
// and a smaller pnl leads to a larger pool value
result.longPnl = getPnl(
dataStore,
market,
indexTokenPrice,
true,
!maximize
);
result.longPnl = getCappedPnl(
dataStore,
market.marketToken,
true,
result.longPnl,
result.longTokenUsd,
pnlFactorType
);
result.shortPnl = getPnl(
dataStore,
market,
indexTokenPrice,
false,
!maximize
);
result.shortPnl = getCappedPnl(
dataStore,
market.marketToken,
false,
result.shortPnl,
result.shortTokenUsd,
pnlFactorType
);
result.netPnl = result.longPnl + result.shortPnl;
result.poolValue = Calc.sumReturnInt256(poolValue, -result.netPnl);
return result;
}
// @dev get the net pending pnl for a market
// @param dataStore DataStore
// @param market the market to check
// @param longToken the long token of the market
// @param shortToken the short token of the market
// @param indexTokenPrice the price of the index token
// @param maximize whether to maximize or minimize the net pnl
// @return the net pending pnl for a market
function getNetPnl(
DataStore dataStore,
Market.Props memory market,
Price.Props memory indexTokenPrice,
bool maximize
) internal view returns (int256) {
int256 longPnl = getPnl(dataStore, market, indexTokenPrice, true, maximize);
int256 shortPnl = getPnl(dataStore, market, indexTokenPrice, false, maximize);
return longPnl + shortPnl;
}
// @dev get the capped pending pnl for a market
// @param dataStore DataStore
// @param market the market to check
// @param isLong whether to check for the long or short side
// @param pnl the uncapped pnl of the market
// @param poolUsd the USD value of the pool
// @param pnlFactorType the pnl factor type to use
function getCappedPnl(
DataStore dataStore,
address market,
bool isLong,
int256 pnl,
uint256 poolUsd,
bytes32 pnlFactorType
) internal view returns (int256) {
if (pnl < 0) { return pnl; }
uint256 maxPnlFactor = getMaxPnlFactor(dataStore, pnlFactorType, market, isLong);
int256 maxPnl = Precision.applyFactor(poolUsd, maxPnlFactor).toInt256();
return pnl > maxPnl ? maxPnl : pnl;
}
// @dev get the pending pnl for a market
// @param dataStore DataStore
// @param market the market to check
// @param longToken the long token of the market
// @param shortToken the short token of the market
// @param indexTokenPrice the price of the index token
// @param isLong whether to check for the long or short side
// @param maximize whether to maximize or minimize the pnl
function getPnl(
DataStore dataStore,
Market.Props memory market,
uint256 indexTokenPrice,
bool isLong,
bool maximize
) internal view returns (int256) {
Price.Props memory _indexTokenPrice = Price.Props(indexTokenPrice, indexTokenPrice);
return getPnl(
dataStore,
market,
_indexTokenPrice,
isLong,
maximize
);
}
// @dev get the pending pnl for a market for either longs or shorts
// @param dataStore DataStore
// @param market the market to check
// @param longToken the long token of the market
// @param shortToken the short token of the market
// @param indexTokenPrice the price of the index token
// @param isLong whether to get the pnl for longs or shorts
// @param maximize whether to maximize or minimize the net pnl
// @return the pending pnl for a market for either longs or shorts
function getPnl(
DataStore dataStore,
Market.Props memory market,
Price.Props memory indexTokenPrice,
bool isLong,
bool maximize
) internal view returns (int256) {
int256 openInterest = getOpenInterest(dataStore, market, isLong).toInt256();
uint256 openInterestInTokens = getOpenInterestInTokens(dataStore, market, isLong);
if (openInterest == 0 || openInterestInTokens == 0) {
return 0;
}
uint256 price = indexTokenPrice.pickPriceForPnl(isLong, maximize);
// openInterest is the cost of all positions, openInterestValue is the current worth of all positions
int256 openInterestValue = (openInterestInTokens * price).toInt256();
int256 pnl = isLong ? openInterestValue - openInterest : openInterest - openInterestValue;
return pnl;
}
// @dev get the amount of tokens in the pool
// @param dataStore DataStore
// @param market the market to check
// @param token the token to check
// @return the amount of tokens in the pool
function getPoolAmount(DataStore dataStore, Market.Props memory market, address token) internal view returns (uint256) {
/* Market.Props memory market = MarketStoreUtils.get(dataStore, marketAddress); */
// if the longToken and shortToken are the same, return half of the token amount, so that
// calculations of pool value, etc would be correct
uint256 divisor = getPoolDivisor(market.longToken, market.shortToken);
return dataStore.getUint(Keys.poolAmountKey(market.marketToken, token)) / divisor;
}
// @dev get the max amount of tokens allowed to be in the pool
// @param dataStore DataStore
// @param market the market to check
// @param token the token to check
// @return the max amount of tokens that are allowed in the pool
function getMaxPoolAmount(DataStore dataStore, address market, address token) internal view returns (uint256) {
return dataStore.getUint(Keys.maxPoolAmountKey(market, token));
}
// @dev get the max open interest allowed for the market
// @param dataStore DataStore
// @param market the market to check
// @param isLong whether this is for the long or short side
// @return the max open interest allowed for the market
function getMaxOpenInterest(DataStore dataStore, address market, bool isLong) internal view returns (uint256) {
return dataStore.getUint(Keys.maxOpenInterestKey(market, isLong));
}
// @dev increment the claimable collateral amount
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to increment the claimable collateral for
// @param token the claimable token
// @param account the account to increment the claimable collateral for
// @param delta the amount to increment
function incrementClaimableCollateralAmount(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address token,
address account,
uint256 delta
) internal {
uint256 divisor = dataStore.getUint(Keys.CLAIMABLE_COLLATERAL_TIME_DIVISOR);
uint256 timeKey = Chain.currentTimestamp() / divisor;
uint256 nextValue = dataStore.incrementUint(
Keys.claimableCollateralAmountKey(market, token, timeKey, account),
delta
);
uint256 nextPoolValue = dataStore.incrementUint(
Keys.claimableCollateralAmountKey(market, token),
delta
);
MarketEventUtils.emitClaimableCollateralUpdated(
eventEmitter,
market,
token,
timeKey,
account,
delta,
nextValue,
nextPoolValue
);
}
// @dev increment the claimable funding amount
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the trading market
// @param token the claimable token
// @param account the account to increment for
// @param delta the amount to increment
function incrementClaimableFundingAmount(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address token,
address account,
uint256 delta
) internal {
uint256 nextValue = dataStore.incrementUint(
Keys.claimableFundingAmountKey(market, token, account),
delta
);
uint256 nextPoolValue = dataStore.incrementUint(
Keys.claimableFundingAmountKey(market, token),
delta
);
MarketEventUtils.emitClaimableFundingUpdated(
eventEmitter,
market,
token,
account,
delta,
nextValue,
nextPoolValue
);
}
// @dev claim funding fees
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to claim for
// @param token the token to claim
// @param account the account to claim for
// @param receiver the receiver to send the amount to
function claimFundingFees(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address token,
address account,
address receiver
) internal {
bytes32 key = Keys.claimableFundingAmountKey(market, token, account);
uint256 claimableAmount = dataStore.getUint(key);
dataStore.setUint(key, 0);
uint256 nextPoolValue = dataStore.decrementUint(
Keys.claimableFundingAmountKey(market, token),
claimableAmount
);
MarketToken(payable(market)).transferOut(
token,
receiver,
claimableAmount
);
validateMarketTokenBalance(dataStore, market);
MarketEventUtils.emitFundingFeesClaimed(
eventEmitter,
market,
token,
account,
receiver,
claimableAmount,
nextPoolValue
);
}
// @dev claim collateral
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to claim for
// @param token the token to claim
// @param timeKey the time key
// @param account the account to claim for
// @param receiver the receiver to send the amount to
function claimCollateral(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address token,
uint256 timeKey,
address account,
address receiver
) internal {
uint256 claimableAmount = dataStore.getUint(Keys.claimableCollateralAmountKey(market, token, timeKey, account));
uint256 claimableFactorForTime = dataStore.getUint(Keys.claimableCollateralFactorKey(market, token, timeKey));
uint256 claimableFactorForAccount = dataStore.getUint(Keys.claimableCollateralFactorKey(market, token, timeKey, account));
uint256 claimableFactor = claimableFactorForTime > claimableFactorForAccount ? claimableFactorForTime : claimableFactorForAccount;
uint256 claimedAmount = dataStore.getUint(Keys.claimedCollateralAmountKey(market, token, timeKey, account));
uint256 adjustedClaimableAmount = Precision.applyFactor(claimableAmount, claimableFactor);
if (adjustedClaimableAmount <= claimedAmount) {
revert Errors.CollateralAlreadyClaimed(adjustedClaimableAmount, claimedAmount);
}
uint256 remainingClaimableAmount = adjustedClaimableAmount - claimedAmount;
dataStore.setUint(
Keys.claimedCollateralAmountKey(market, token, timeKey, account),
adjustedClaimableAmount
);
uint256 nextPoolValue = dataStore.decrementUint(
Keys.claimableCollateralAmountKey(market, token),
remainingClaimableAmount
);
MarketToken(payable(market)).transferOut(
token,
receiver,
remainingClaimableAmount
);
validateMarketTokenBalance(dataStore, market);
MarketEventUtils.emitCollateralClaimed(
eventEmitter,
market,
token,
timeKey,
account,
receiver,
remainingClaimableAmount,
nextPoolValue
);
}
// @dev apply a delta to the pool amount
// validatePoolAmount is not called in this function since applyDeltaToPoolAmount
// is called when receiving fees
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to apply to
// @param token the token to apply to
// @param delta the delta amount
function applyDeltaToPoolAmount(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address token,
int256 delta
) internal returns (uint256) {
uint256 nextValue = dataStore.applyDeltaToUint(
Keys.poolAmountKey(market, token),
delta,
"Invalid state, negative poolAmount"
);
applyDeltaToVirtualInventoryForSwaps(
dataStore,
eventEmitter,
market,
token,
delta
);
MarketEventUtils.emitPoolAmountUpdated(eventEmitter, market, token, delta, nextValue);
return nextValue;
}
function getAdjustedSwapImpactFactor(DataStore dataStore, address market, bool isPositive) internal view returns (uint256) {
(uint256 positiveImpactFactor, uint256 negativeImpactFactor) = getAdjustedSwapImpactFactors(dataStore, market);
return isPositive ? positiveImpactFactor : negativeImpactFactor;
}
function getAdjustedSwapImpactFactors(DataStore dataStore, address market) internal view returns (uint256, uint256) {
uint256 positiveImpactFactor = dataStore.getUint(Keys.swapImpactFactorKey(market, true));
uint256 negativeImpactFactor = dataStore.getUint(Keys.swapImpactFactorKey(market, false));
// if the positive impact factor is more than the negative impact factor, positions could be opened
// and closed immediately for a profit if the difference is sufficient to cover the position fees
if (positiveImpactFactor > negativeImpactFactor) {
positiveImpactFactor = negativeImpactFactor;
}
return (positiveImpactFactor, negativeImpactFactor);
}
function getAdjustedPositionImpactFactor(DataStore dataStore, address market, bool isPositive) internal view returns (uint256) {
(uint256 positiveImpactFactor, uint256 negativeImpactFactor) = getAdjustedPositionImpactFactors(dataStore, market);
return isPositive ? positiveImpactFactor : negativeImpactFactor;
}
function getAdjustedPositionImpactFactors(DataStore dataStore, address market) internal view returns (uint256, uint256) {
uint256 positiveImpactFactor = dataStore.getUint(Keys.positionImpactFactorKey(market, true));
uint256 negativeImpactFactor = dataStore.getUint(Keys.positionImpactFactorKey(market, false));
// if the positive impact factor is more than the negative impact factor, positions could be opened
// and closed immediately for a profit if the difference is sufficient to cover the position fees
if (positiveImpactFactor > negativeImpactFactor) {
positiveImpactFactor = negativeImpactFactor;
}
return (positiveImpactFactor, negativeImpactFactor);
}
// @dev cap the input priceImpactUsd by the available amount in the position
// impact pool and the max positive position impact factor
// @param dataStore DataStore
// @param market the trading market
// @param tokenPrice the price of the token
// @param priceImpactUsd the calculated USD price impact
// @return the capped priceImpactUsd
function getCappedPositionImpactUsd(
DataStore dataStore,
address market,
Price.Props memory tokenPrice,
int256 priceImpactUsd,
uint256 sizeDeltaUsd
) internal view returns (int256) {
if (priceImpactUsd < 0) {
return priceImpactUsd;
}
uint256 impactPoolAmount = getPositionImpactPoolAmount(dataStore, market);
int256 maxPriceImpactUsdBasedOnImpactPool = (impactPoolAmount * tokenPrice.min).toInt256();
if (priceImpactUsd > maxPriceImpactUsdBasedOnImpactPool) {
priceImpactUsd = maxPriceImpactUsdBasedOnImpactPool;
}
uint256 maxPriceImpactFactor = getMaxPositionImpactFactor(dataStore, market, true);
int256 maxPriceImpactUsdBasedOnMaxPriceImpactFactor = Precision.applyFactor(sizeDeltaUsd, maxPriceImpactFactor).toInt256();
if (priceImpactUsd > maxPriceImpactUsdBasedOnMaxPriceImpactFactor) {
priceImpactUsd = maxPriceImpactUsdBasedOnMaxPriceImpactFactor;
}
return priceImpactUsd;
}
// @dev get the position impact pool amount
// @param dataStore DataStore
// @param market the market to check
// @return the position impact pool amount
function getPositionImpactPoolAmount(DataStore dataStore, address market) internal view returns (uint256) {
return dataStore.getUint(Keys.positionImpactPoolAmountKey(market));
}
// @dev get the swap impact pool amount
// @param dataStore DataStore
// @param market the market to check
// @param token the token to check
// @return the swap impact pool amount
function getSwapImpactPoolAmount(DataStore dataStore, address market, address token) internal view returns (uint256) {
return dataStore.getUint(Keys.swapImpactPoolAmountKey(market, token));
}
// @dev apply a delta to the swap impact pool
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to apply to
// @param token the token to apply to
// @param delta the delta amount
function applyDeltaToSwapImpactPool(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address token,
int256 delta
) internal returns (uint256) {
uint256 nextValue = dataStore.applyBoundedDeltaToUint(
Keys.swapImpactPoolAmountKey(market, token),
delta
);
MarketEventUtils.emitSwapImpactPoolAmountUpdated(eventEmitter, market, token, delta, nextValue);
return nextValue;
}
// @dev apply a delta to the position impact pool
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to apply to
// @param delta the delta amount
function applyDeltaToPositionImpactPool(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
int256 delta
) internal returns (uint256) {
uint256 nextValue = dataStore.applyBoundedDeltaToUint(
Keys.positionImpactPoolAmountKey(market),
delta
);
MarketEventUtils.emitPositionImpactPoolAmountUpdated(eventEmitter, market, delta, nextValue);
return nextValue;
}
// @dev apply a delta to the open interest
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to apply to
// @param collateralToken the collateralToken to apply to
// @param isLong whether to apply to the long or short side
// @param delta the delta amount
function applyDeltaToOpenInterest(
DataStore dataStore,
EventEmitter eventEmitter,
Market.Props memory market,
address collateralToken,
bool isLong,
int256 delta
) internal returns (uint256) {
if (market.indexToken == address(0)) {
revert Errors.OpenInterestCannotBeUpdatedForSwapOnlyMarket(market.marketToken);
}
uint256 nextValue = dataStore.applyDeltaToUint(
Keys.openInterestKey(market.marketToken, collateralToken, isLong),
delta,
"Invalid state: negative open interest"
);
// if the open interest for longs is increased then tokens were virtually bought from the pool
// so the virtual inventory should be decreased
// if the open interest for longs is decreased then tokens were virtually sold to the pool
// so the virtual inventory should be increased
// if the open interest for shorts is increased then tokens were virtually sold to the pool
// so the virtual inventory should be increased
// if the open interest for shorts is decreased then tokens were virtually bought from the pool
// so the virtual inventory should be decreased
applyDeltaToVirtualInventoryForPositions(
dataStore,
eventEmitter,
market.indexToken,
isLong ? -delta : delta
);
if (delta > 0) {
validateOpenInterest(
dataStore,
market,
isLong
);
}
MarketEventUtils.emitOpenInterestUpdated(eventEmitter, market.marketToken, collateralToken, isLong, delta, nextValue);
return nextValue;
}
// @dev apply a delta to the open interest in tokens
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to apply to
// @param collateralToken the collateralToken to apply to
// @param isLong whether to apply to the long or short side
// @param delta the delta amount
function applyDeltaToOpenInterestInTokens(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address collateralToken,
bool isLong,
int256 delta
) internal returns (uint256) {
uint256 nextValue = dataStore.applyDeltaToUint(
Keys.openInterestInTokensKey(market, collateralToken, isLong),
delta,
"Invalid state: negative open interest in tokens"
);
MarketEventUtils.emitOpenInterestInTokensUpdated(eventEmitter, market, collateralToken, isLong, delta, nextValue);
return nextValue;
}
// @dev apply a delta to the collateral sum
// @param dataStore DataStore
// @param eventEmitter EventEmitter
// @param market the market to apply to
// @param collateralToken the collateralToken to apply to
// @param isLong whether to apply to the long or short side
// @param delta the delta amount
function applyDeltaToCollateralSum(
DataStore dataStore,
EventEmitter eventEmitter,
address market,
address collateralToken,
bool isLong,
int256 delta
) internal returns (uint256) {
uint256 nextValue = dataStore.applyDeltaToUint(
Keys.collateralSumKey(market, collateralToken, isLong),
delta,
"Invalid state: negative collateralSum"
);
MarketEventUtils.emitCollateralSumUpdated(eventEmitter, market, collateralToken, isLong, delta, nextValue);
return nextValue;
}
// @dev update the funding amount per size values
// @param dataStore DataStore
// @param prices the prices of the market tokens
// @param market the market to update
// @param longToken the market's long token
// @param shortToken the market's short token
function updateFundingAmountPerSize(
DataStore dataStore,
EventEmitter eventEmitter,
Market.Props memory market,
MarketPrices memory prices
) external {
GetNextFundingAmountPerSizeResult memory result = getNextFundingAmountPerSize(dataStore, market, prices);
setFundingAmountPerSize(dataStore, eventEmitter, market.marketToken, market.longToken, true, result.fundingAmountPerSize_LongCollateral_LongPosition);
setFundingAmountPerSize(dataStore, eventEmitter, market.marketToken, market.longToken, false, result.fundingAmountPerSize_LongCollateral_ShortPosition);
setFundingAmountPerSize(dataStore, eventEmitter, market.marketToken, market.shortToken, true, result.fundingAmountPerSize_ShortCollateral_LongPosition);
setFundingAmountPerSize(dataStore, eventEmitter, market.marketToken, market.shortToken, false, result.fundingAmountPerSize_ShortCollateral_ShortPosition);
dataStore.setUint(Keys.fundingUpdatedAtKey(market.marketToken), Chain.currentTimestamp());
}
// @dev get the next funding amount per size values
// @param dataStore DataStore
// @param prices the prices of the market tokens
// @param market the market to update
// @param longToken the market's long token
// @param shortToken the market's short token
function getNextFundingAmountPerSize(
DataStore dataStore,
Market.Props memory market,
MarketPrices memory prices
) internal view returns (GetNextFundingAmountPerSizeResult memory) {
GetNextFundingAmountPerSizeResult memory result;
GetNextFundingAmountPerSizeCache memory cache;
uint256 divisor = getPoolDivisor(market.longToken, market.shortToken);