This repository has been archived by the owner on Feb 9, 2024. It is now read-only.
/
MarginEngine.sol
1378 lines (1202 loc) · 49.7 KB
/
MarginEngine.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: Apache-2.0
pragma solidity =0.8.9;
import "./core_libraries/Tick.sol";
import "./interfaces/IMarginEngine.sol";
import "./interfaces/rate_oracles/IRateOracle.sol";
import "./interfaces/fcms/IFCM.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
import "./core_libraries/FixedAndVariableMath.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./core_libraries/SafeTransferLib.sol";
import "./storage/MarginEngineStorage.sol";
import "./utils/SafeCastUni.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./utils/SqrtPriceMath.sol";
contract MarginEngine is
MarginEngineStorage,
IMarginEngine,
Initializable,
OwnableUpgradeable,
UUPSUpgradeable
{
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
using SafeCastUni for uint256;
using SafeCastUni for int256;
using Tick for mapping(int24 => Tick.Info);
using Position for mapping(bytes32 => Position.Info);
using Position for Position.Info;
using SafeTransferLib for IERC20Minimal;
/// @dev Seconds in a year
int256 public constant SECONDS_IN_YEAR = 31536000e18;
uint256 public constant ONE_UINT = 1e18;
int256 public constant ONE = 1e18;
uint256 public constant MAX_FIXED_RATE_WAD = 15e18; // 15 in WAD = 15%. Highest rate used during counterfactual unwinds.
uint256 public constant MAX_LOOKBACK_WINDOW_IN_SECONDS = 315360000; // ten years
uint256 public constant MIN_LOOKBACK_WINDOW_IN_SECONDS = 3600; // one hour
uint256 public constant MAX_CACHE_MAX_AGE_IN_SECONDS = 1209600; // two weeks
uint256 public constant MAX_LIQUIDATOR_REWARD_WAD = 3e17; // 30%
modifier whenNotPaused() {
require(!paused, "Paused");
_;
}
function setPausability(bool state) external onlyVAMM {
paused = state;
if (address(_fcm) != address(0)) {
_fcm.setPausability(state);
}
}
/// @dev In the litepaper the timeFactor is exp(-beta*(t-s)/t_max) where t is the maturity timestamp, and t_max is the max number of seconds for the IRS AMM duration, s is the current timestamp and beta is a diffusion process parameter set via calibration
function computeTimeFactor() internal view returns (int256 timeFactorWad) {
uint256 currentTimestampWad = Time.blockTimestampScaled();
require(currentTimestampWad <= _termEndTimestampWad, "CT<ET");
require(marginCalculatorParameters.betaWad != 0, "B0");
timeFactorWad = (
(int256(_termEndTimestampWad) - int256(currentTimestampWad))
.div(marginCalculatorParameters.tMaxWad)
.mul(-marginCalculatorParameters.betaWad)
).exp();
}
/// @notice Calculates an APY Upper or Lower Bound of a given underlying pool (e.g. Aave v2 USDC Lending Pool)
/// @param historicalApyWad Geometric Mean Time Weighted Average APY (TWAPPY) of the underlying pool (e.g. Aave v2 USDC Lending Pool)
/// @param isUpper isUpper = true ==> calculating the APY Upper Bound, otherwise APY Lower Bound
/// @return apyBoundWad APY Upper or Lower Bound of a given underlying pool (e.g. Aave v2 USDC Lending Pool)
function computeApyBound(uint256 historicalApyWad, bool isUpper)
internal
view
returns (uint256 apyBoundWad)
{
int256 timeFactorWad = computeTimeFactor();
int256 kWad = (marginCalculatorParameters.alphaWad << 2).div(
marginCalculatorParameters.sigmaSquaredWad
);
int256 lambdaWad = (marginCalculatorParameters.betaWad << 2)
.mul(timeFactorWad)
.mul(int256(historicalApyWad))
.div(marginCalculatorParameters.sigmaSquaredWad)
.div(ONE - timeFactorWad);
int256 criticalValueWad = (((lambdaWad << 1) + kWad) << 1).sqrt().mul(
(isUpper)
? marginCalculatorParameters.xiUpperWad
: marginCalculatorParameters.xiLowerWad
);
if (!isUpper) {
criticalValueWad = -criticalValueWad;
}
int256 apyBoundIntWad = marginCalculatorParameters
.sigmaSquaredWad
.mul(ONE - timeFactorWad)
.div(marginCalculatorParameters.betaWad << 2)
.mul(kWad + lambdaWad + criticalValueWad);
apyBoundWad = apyBoundIntWad < 0 ? 0 : uint256(apyBoundIntWad);
}
/// @notice Calculates the Worst Case Variable Factor At Maturity
/// @param isFT isFT => we are dealing with a Fixed Taker (short) IRS position, otherwise it is a Variable Taker (long) IRS position
/// @param isLM isLM => we are computing a Liquidation Margin otherwise computing an Initial Margin
/// @param historicalApyWad Historical Average APY of the underlying pool (e.g. Aave v2 USDC Lending Pool)
/// @return variableFactorWad The Worst Case Variable Factor At Maturity = APY Bound * accrualFactor(timeInYearsFromStartUntilMaturity) where APY Bound = APY Upper Bound for Fixed Takers and APY Lower Bound for Variable Takers (18 decimals)
function worstCaseVariableFactorAtMaturity(
bool isFT,
bool isLM,
uint256 historicalApyWad
) internal view returns (uint256 variableFactorWad) {
uint256 rateFromStart = _rateOracle.variableFactorNoCache(
_termStartTimestampWad,
Time.blockTimestampScaled()
) + ONE_UINT;
uint256 worstApy = computeApyBound(historicalApyWad, isFT);
if (!isLM) {
worstApy = worstApy.mul(
isFT
? marginCalculatorParameters.apyUpperMultiplierWad
: marginCalculatorParameters.apyLowerMultiplierWad
);
}
variableFactorWad =
rateFromStart.mul(
worstApy.mul(
FixedAndVariableMath.accrualFact(
_termEndTimestampWad - Time.blockTimestampScaled()
)
) + ONE_UINT
) -
ONE_UINT;
}
// https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
struct PositionMarginRequirementLocalVars2 {
int24 inRangeTick;
int256 scenario1LPVariableTokenBalance;
int256 scenario1LPFixedTokenBalance;
int256 scenario2LPVariableTokenBalance;
int256 scenario2LPFixedTokenBalance;
}
function initialize(
IERC20Minimal __underlyingToken,
IRateOracle __rateOracle,
uint256 __termStartTimestampWad,
uint256 __termEndTimestampWad
) external override initializer {
require(address(__underlyingToken) != address(0), "UT");
require(address(__rateOracle) != address(0), "RO");
require(__termStartTimestampWad != 0 && __termEndTimestampWad != 0, "TS/E");
require(__termEndTimestampWad > __termStartTimestampWad, "TE<=TS");
_underlyingToken = __underlyingToken;
_termStartTimestampWad = __termStartTimestampWad;
_termEndTimestampWad = __termEndTimestampWad;
_rateOracle = __rateOracle;
_factory = IFactory(msg.sender);
// Todo: set default values for things like _secondsAgo, cacheMaxAge.
// We should see if we need to do any similar defaulting for VAMM, FCM
// _secondsAgo = 2 weeks; // can be changed by owner
// _cacheMaxAgeInSeconds = 6 hours; // can be changed by owner
__Ownable_init();
__UUPSUpgradeable_init();
}
// To authorize the owner to upgrade the contract we implement _authorizeUpgrade with the onlyOwner modifier.
// ref: https://forum.openzeppelin.com/t/uups-proxies-tutorial-solidity-javascript/7786
function _authorizeUpgrade(address) internal override onlyOwner {}
modifier nonZeroDelta(int256 marginDelta) {
if (marginDelta == 0) {
revert CustomErrors.InvalidMarginDelta();
}
_;
}
/// @dev Modifier that ensures only the VAMM can execute certain actions
modifier onlyVAMM() {
if (msg.sender != address(_vamm)) {
revert CustomErrors.OnlyVAMM();
}
_;
}
/// @dev Modifier that reverts if the msg.sender is not the Full Collateralisation Module
modifier onlyFCM() {
if (msg.sender != address(_fcm)) {
revert CustomErrors.OnlyFCM();
}
_;
}
/// @dev Modifier that reverts if the termEndTimestamp is higher than the current block timestamp
/// @dev This modifier ensures that actions such as settlePosition (can only be done after maturity)
modifier onlyAfterMaturity() {
if (_termEndTimestampWad > Time.blockTimestampScaled()) {
revert CustomErrors.CannotSettleBeforeMaturity();
}
_;
}
/// @dev Modifier that ensures new LP positions cannot be minted after one day before the maturity of the vamm
/// @dev also ensures new swaps cannot be conducted after one day before maturity of the vamm
modifier checkCurrentTimestampTermEndTimestampDelta() {
if (Time.isCloseToMaturityOrBeyondMaturity(_termEndTimestampWad, _vamm.maturityBufferWad())) {
revert CustomErrors.closeToOrBeyondMaturity();
}
_;
}
// GETTERS FOR STORAGE SLOTS
// Not auto-generated by public variables in the storage contract, cos solidity doesn't support that for functions that implement an interface
/// @inheritdoc IMarginEngine
function termStartTimestampWad() external view override returns (uint256) {
return _termStartTimestampWad;
}
/// @inheritdoc IMarginEngine
function marginEngineParameters() external view override returns (MarginCalculatorParameters memory) {
return marginCalculatorParameters;
}
/// @inheritdoc IMarginEngine
function termEndTimestampWad() external view override returns (uint256) {
return _termEndTimestampWad;
}
/// @inheritdoc IMarginEngine
function lookbackWindowInSeconds()
external
view
override
returns (uint256)
{
return _secondsAgo;
}
/// @inheritdoc IMarginEngine
function cacheMaxAgeInSeconds() external view override returns (uint256) {
return _cacheMaxAgeInSeconds;
}
/// @inheritdoc IMarginEngine
function liquidatorRewardWad() external view override returns (uint256) {
return _liquidatorRewardWad;
}
/// @inheritdoc IMarginEngine
function underlyingToken() external view override returns (IERC20Minimal) {
return _underlyingToken;
}
/// @inheritdoc IMarginEngine
function fcm() external view override returns (IFCM) {
return _fcm;
}
/// @inheritdoc IMarginEngine
function vamm() external view override returns (IVAMM) {
return _vamm;
}
/// @inheritdoc IMarginEngine
function factory() external view override returns (IFactory) {
return _factory;
}
/// @inheritdoc IMarginEngine
function rateOracle() external view override returns (IRateOracle) {
return _rateOracle;
}
/// @inheritdoc IMarginEngine
function setMarginCalculatorParameters(
MarginCalculatorParameters memory _marginCalculatorParameters
) external override onlyOwner {
marginCalculatorParameters = _marginCalculatorParameters;
emit MarginCalculatorParametersSetting(marginCalculatorParameters);
}
/// @inheritdoc IMarginEngine
function setVAMM(IVAMM _vAMM) external override onlyOwner {
_vamm = _vAMM;
emit VAMMSetting(_vamm);
}
/// @inheritdoc IMarginEngine
function setRateOracle(IRateOracle __rateOracle)
external
override
onlyOwner
{
_rateOracle = __rateOracle;
emit RateOracleSetting(_rateOracle);
}
/// @inheritdoc IMarginEngine
function setFCM(IFCM _newFCM) external override onlyOwner {
_fcm = _newFCM;
emit FCMSetting(_fcm);
}
/// @inheritdoc IMarginEngine
function setLookbackWindowInSeconds(uint256 _newSecondsAgo)
external
override
onlyOwner
{
require(
(_newSecondsAgo <= MAX_LOOKBACK_WINDOW_IN_SECONDS) &&
(_newSecondsAgo >= MIN_LOOKBACK_WINDOW_IN_SECONDS),
"LB OOB"
);
if (_secondsAgo == 0) {
// First time setting the value. Anything goes.
_secondsAgo = _newSecondsAgo;
} else {
// Updating value. Invalidate cache and make sure we can read the rates we need from the rate oracle.
_secondsAgo = _newSecondsAgo;
// Cache invalidated
_refreshHistoricalApyCache();
}
emit HistoricalApyWindowSetting(_secondsAgo);
}
/// @inheritdoc IMarginEngine
function setCacheMaxAgeInSeconds(uint256 _newCacheMaxAgeInSeconds)
external
override
onlyOwner
{
require(
_newCacheMaxAgeInSeconds <= MAX_CACHE_MAX_AGE_IN_SECONDS,
"CMA OOB"
);
_cacheMaxAgeInSeconds = _newCacheMaxAgeInSeconds;
emit CacheMaxAgeSetting(_cacheMaxAgeInSeconds);
}
/// @inheritdoc IMarginEngine
function collectProtocol(address _recipient, uint256 _amount)
external
override
whenNotPaused
onlyOwner
{
if (_amount > 0) {
/// @dev if the amount exceeds the available balances, _vamm.updateProtocolFees(amount) should be reverted as intended
_vamm.updateProtocolFees(_amount);
_underlyingToken.safeTransfer(_recipient, _amount);
}
emit ProtocolCollection(msg.sender, _recipient, _amount);
}
/// @inheritdoc IMarginEngine
function setLiquidatorReward(uint256 _newLiquidatorRewardWad)
external
override
onlyOwner
{
require(_newLiquidatorRewardWad <= MAX_LIQUIDATOR_REWARD_WAD, "LR OOB");
_liquidatorRewardWad = _newLiquidatorRewardWad;
emit LiquidatorRewardSetting(_liquidatorRewardWad);
}
/// @inheritdoc IMarginEngine
function getPosition(
address _owner,
int24 _tickLower,
int24 _tickUpper
) external override returns (Position.Info memory) {
Position.Info storage _position = positions.get(
_owner,
_tickLower,
_tickUpper
);
_updatePositionTokenBalancesAndAccountForFees(
_position,
_tickLower,
_tickUpper,
false
); // isMint=false
return _position;
}
/// @notice _transferMargin function which:
/// @dev Transfers funds in from account if _marginDelta is positive, or out to account if _marginDelta is negative
/// @dev if the margiDelta is positive, we conduct a safe transfer from the _account address to the address of the MarginEngine
/// @dev if the marginDelta is negative, the user wishes to withdraw underlying tokens from the MarginEngine,
/// @dev in that case we first check the balance of the marginEngine in terms of the underlying tokens, if the balance is sufficient to cover the margin transfer, then we cover it via a safeTransfer
/// @dev if the marginEngineBalance is not sufficient to cover the marginDelta then we cover the remainingDelta by invoking the transferMarginToMarginEngineTrader function of the fcm which in case of Aave will calls the Aave withdraw function to settle with the MarginEngine in underlying tokens
function _transferMargin(address _account, int256 _marginDelta) internal {
if (_marginDelta > 0) {
_underlyingToken.safeTransferFrom(
_account,
address(this),
uint256(_marginDelta)
);
} else {
uint256 _marginEngineBalance = _underlyingToken.balanceOf(
address(this)
);
uint256 _remainingDeltaToCover;
unchecked {
_remainingDeltaToCover = uint256(-_marginDelta);
}
if (_remainingDeltaToCover > _marginEngineBalance) {
if (_marginEngineBalance > 0) {
_remainingDeltaToCover -= _marginEngineBalance;
_underlyingToken.safeTransfer(
_account,
_marginEngineBalance
);
}
_fcm.transferMarginToMarginEngineTrader(
_account,
_remainingDeltaToCover
);
} else {
_underlyingToken.safeTransfer(_account, _remainingDeltaToCover);
}
}
}
/// @inheritdoc IMarginEngine
function transferMarginToFCMTrader(address _account, uint256 _marginDelta)
external
override
whenNotPaused
onlyFCM
{
_underlyingToken.safeTransfer(_account, _marginDelta);
}
/// @inheritdoc IMarginEngine
function isAlpha() external view override returns (bool) {
return _isAlpha;
}
/// @inheritdoc IMarginEngine
function setIsAlpha(bool __isAlpha) external override onlyOwner {
_isAlpha = __isAlpha;
emit IsAlpha(_isAlpha);
}
/// @inheritdoc IMarginEngine
function updatePositionMargin(
address _owner,
int24 _tickLower,
int24 _tickUpper,
int256 _marginDelta
) external override whenNotPaused nonZeroDelta(_marginDelta) {
require(_owner != address(0), "O0");
Tick.checkTicks(_tickLower, _tickUpper);
Position.Info storage _position = positions.get(
_owner,
_tickLower,
_tickUpper
);
/// @dev if in alpha --> revert (unless call via periphery)
if (_isAlpha) {
IPeriphery _periphery = _factory.periphery();
require(msg.sender == address(_periphery), "pphry only");
}
_updatePositionTokenBalancesAndAccountForFees(
_position,
_tickLower,
_tickUpper,
false
); // isMint=false
if (_marginDelta < 0) {
if (
_owner != msg.sender && !_factory.isApproved(_owner, msg.sender)
) {
revert CustomErrors.OnlyOwnerCanUpdatePosition();
}
_position.updateMarginViaDelta(_marginDelta);
_checkPositionMarginCanBeUpdated(_position, _tickLower, _tickUpper);
_transferMargin(_owner, _marginDelta);
} else {
_position.updateMarginViaDelta(_marginDelta);
_transferMargin(msg.sender, _marginDelta);
}
_position.rewardPerAmount = 0;
emit PositionMarginUpdate(
msg.sender,
_owner,
_tickLower,
_tickUpper,
_marginDelta
);
emit PositionUpdate(
_owner,
_tickLower,
_tickUpper,
_position._liquidity,
_position.margin,
_position.fixedTokenBalance,
_position.variableTokenBalance,
_position.accumulatedFees
);
}
/// @inheritdoc IMarginEngine
function settlePosition(
address _owner,
int24 _tickLower,
int24 _tickUpper
) external override whenNotPaused onlyAfterMaturity {
Tick.checkTicks(_tickLower, _tickUpper);
Position.Info storage _position = positions.get(
_owner,
_tickLower,
_tickUpper
);
_updatePositionTokenBalancesAndAccountForFees(
_position,
_tickLower,
_tickUpper,
false
);
int256 _settlementCashflow = FixedAndVariableMath
.calculateSettlementCashflow(
_position.fixedTokenBalance,
_position.variableTokenBalance,
_termStartTimestampWad,
_termEndTimestampWad,
_rateOracle.variableFactor(
_termStartTimestampWad,
_termEndTimestampWad
)
);
_position.updateBalancesViaDeltas(
-_position.fixedTokenBalance,
-_position.variableTokenBalance
);
_position.updateMarginViaDelta(_settlementCashflow);
_position.settlePosition();
emit PositionSettlement(
_owner,
_tickLower,
_tickUpper,
_settlementCashflow
);
emit PositionUpdate(
_owner,
_tickLower,
_tickUpper,
_position._liquidity,
_position.margin,
_position.fixedTokenBalance,
_position.variableTokenBalance,
_position.accumulatedFees
);
}
/// @inheritdoc IMarginEngine
function getHistoricalApy() public override returns (uint256) {
if (
block.timestamp - cachedHistoricalApyWadRefreshTimestamp >
_cacheMaxAgeInSeconds
) {
// Cache is stale
_refreshHistoricalApyCache();
emit HistoricalApy(cachedHistoricalApyWad);
}
return cachedHistoricalApyWad;
}
/// @inheritdoc IMarginEngine
function getHistoricalApyReadOnly() public view returns (uint256) {
if (
block.timestamp - cachedHistoricalApyWadRefreshTimestamp >
_cacheMaxAgeInSeconds
) {
// Cache is stale
return _getHistoricalApy();
}
return cachedHistoricalApyWad;
}
/// @notice Computes the historical APY value of the RateOracle
/// @dev The lookback window used by this function is determined by the _secondsAgo state variable
function _getHistoricalApy() internal view returns (uint256) {
uint256 _from = block.timestamp - _secondsAgo;
uint256 historicalApy = _rateOracle.getApyFromTo(
_from,
block.timestamp
);
return historicalApy;
}
/// @notice Updates the cached historical APY value of the RateOracle even if the cache is not stale
function _refreshHistoricalApyCache() internal {
cachedHistoricalApyWad = _getHistoricalApy();
cachedHistoricalApyWadRefreshTimestamp = block.timestamp;
}
/// @inheritdoc IMarginEngine
function liquidatePosition(
address _owner,
int24 _tickLower,
int24 _tickUpper
)
external
override
whenNotPaused
checkCurrentTimestampTermEndTimestampDelta
returns (uint256)
{
/// @dev can only happen before maturity, this is checked when an unwind is triggered which in turn triggers a swap which checks for this condition
Tick.checkTicks(_tickLower, _tickUpper);
Position.Info storage _position = positions.get(
_owner,
_tickLower,
_tickUpper
);
_updatePositionTokenBalancesAndAccountForFees(
_position,
_tickLower,
_tickUpper,
false
); // isMint=false
(bool _isLiquidatable, ) = _isLiquidatablePosition(
_position,
_tickLower,
_tickUpper
);
if (!_isLiquidatable) {
revert CannotLiquidate();
}
if (_position.rewardPerAmount == 0) {
uint256 _absVariableTokenBalance = _position.variableTokenBalance <
0
? uint256(-_position.variableTokenBalance)
: uint256(_position.variableTokenBalance);
if (_position.margin > 0) {
_position.rewardPerAmount = PRBMathUD60x18.div(
PRBMathUD60x18.mul(
uint256(_position.margin),
_liquidatorRewardWad
),
_absVariableTokenBalance
);
} else {
_position.rewardPerAmount = 0;
}
}
uint256 _liquidatorRewardValue = 0;
if (_position._liquidity > 0) {
/// @dev pass position._liquidity to ensure all of the liqudity is burnt
_vamm.burn(_owner, _tickLower, _tickUpper, _position._liquidity);
_position.updateLiquidity(-int128(_position._liquidity));
/// @dev liquidator reward for burning liquidity
_liquidatorRewardValue += PRBMathUD60x18.mul(
uint256(_position.margin),
_liquidatorRewardWad
);
}
int256 _variableTokenDelta = _unwindPosition(
_position,
_owner,
_tickLower,
_tickUpper
);
/// @dev liquidator reward for unwinding position
if (_variableTokenDelta != 0) {
_liquidatorRewardValue += (_variableTokenDelta < 0)
? PRBMathUD60x18.mul(
uint256(-_variableTokenDelta),
_position.rewardPerAmount
)
: PRBMathUD60x18.mul(
uint256(_variableTokenDelta),
_position.rewardPerAmount
);
}
if (_liquidatorRewardValue > 0) {
_position.updateMarginViaDelta(-_liquidatorRewardValue.toInt256());
_underlyingToken.safeTransfer(msg.sender, _liquidatorRewardValue);
}
emit PositionLiquidation(
_owner,
_tickLower,
_tickUpper,
msg.sender,
_variableTokenDelta,
_liquidatorRewardValue
);
emit PositionUpdate(
_owner,
_tickLower,
_tickUpper,
_position._liquidity,
_position.margin,
_position.fixedTokenBalance,
_position.variableTokenBalance,
_position.accumulatedFees
);
return _liquidatorRewardValue;
}
/// @inheritdoc IMarginEngine
function updatePositionPostVAMMInducedMintBurn(
IVAMM.ModifyPositionParams memory _params
)
external
override
whenNotPaused
onlyVAMM
returns (int256 _positionMarginRequirement)
{
Position.Info storage _position = positions.get(
_params.owner,
_params.tickLower,
_params.tickUpper
);
_updatePositionTokenBalancesAndAccountForFees(
_position,
_params.tickLower,
_params.tickUpper,
true
); // isMint=true
_position.updateLiquidity(_params.liquidityDelta);
if (_params.liquidityDelta > 0) {
_positionMarginRequirement = _checkPositionMarginAboveRequirement(
_position,
_params.tickLower,
_params.tickUpper
);
}
if (_position.rewardPerAmount >= 0) {
_position.rewardPerAmount = 0;
}
emit PositionUpdate(
_params.owner,
_params.tickLower,
_params.tickUpper,
_position._liquidity,
_position.margin,
_position.fixedTokenBalance,
_position.variableTokenBalance,
_position.accumulatedFees
);
}
/// @inheritdoc IMarginEngine
function updatePositionPostVAMMInducedSwap(
address _owner,
int24 _tickLower,
int24 _tickUpper,
int256 _fixedTokenDelta,
int256 _variableTokenDelta,
uint256 _cumulativeFeeIncurred,
int256 _fixedTokenDeltaUnbalanced
)
external
override
whenNotPaused
onlyVAMM
returns (int256 _positionMarginRequirement)
{
/// @dev this function can only be called by the vamm following a swap
Position.Info storage _position = positions.get(
_owner,
_tickLower,
_tickUpper
);
_updatePositionTokenBalancesAndAccountForFees(
_position,
_tickLower,
_tickUpper,
false
); // isMint=false
/// @dev isUnwind means the trader is getting into a swap with the opposite direction to their net position
/// @dev in that case it does not make sense to revert the transaction if the position margin requirement is not met since
/// @dev it could have been even further from the requirement prior to the unwind
bool _isUnwind = (
_variableTokenDelta < 0 &&
_position.variableTokenBalance + _variableTokenDelta >= 0
) ||
(
_variableTokenDelta > 0 &&
_position.variableTokenBalance + _variableTokenDelta <= 0
);
if (_cumulativeFeeIncurred > 0) {
_position.updateMarginViaDelta(-_cumulativeFeeIncurred.toInt256());
}
_position.updateBalancesViaDeltas(
_fixedTokenDelta,
_variableTokenDelta
);
_positionMarginRequirement = _getPositionMarginRequirement(
_position,
_tickLower,
_tickUpper,
false
).toInt256();
/// @dev only check the margin requirement if it is not an unwind since an unwind could bring the position to a better state
/// @dev and still not make it through the initial margin requirement
if ((_positionMarginRequirement > _position.margin) && !_isUnwind) {
IVAMM.VAMMVars memory _v = _vamm.vammVars();
revert CustomErrors.MarginRequirementNotMet(
_positionMarginRequirement,
_v.tick,
_fixedTokenDelta,
_variableTokenDelta,
_cumulativeFeeIncurred,
_fixedTokenDeltaUnbalanced
);
}
_position.rewardPerAmount = 0;
emit PositionUpdate(
_owner,
_tickLower,
_tickUpper,
_position._liquidity,
_position.margin,
_position.fixedTokenBalance,
_position.variableTokenBalance,
_position.accumulatedFees
);
}
/// @notice update position token balances and account for fees
/// @dev if the _liquidity of the position supplied to this function is >0 then we
/// @dev 1. retrieve the fixed, variable and fee Growth variables from the vamm by invoking the computeGrowthInside function of the VAMM
/// @dev 2. calculate the deltas that need to be applied to the position's fixed and variable token balances by taking into account trades that took place in the VAMM since the last mint/poke/burn that invoked this function
/// @dev 3. update the fixed and variable token balances and the margin of the position to account for deltas (outlined above) and fees generated by the active liquidity supplied by the position
/// @dev 4. additionally, we need to update the last growth inside variables in the Position.Info struct so that we take a note that we've accounted for the changes up until this point
/// @dev if _liquidity of the position supplied to this function is zero, then we need to check if isMintBurn is set to true (if it is set to true) then we know this function was called post a mint/burn event,
/// @dev meaning we still need to correctly update the last fixed, variable and fee growth variables in the Position.Info struct
function _updatePositionTokenBalancesAndAccountForFees(
Position.Info storage _position,
int24 _tickLower,
int24 _tickUpper,
bool _isMintBurn
) internal {
if (_position._liquidity > 0) {
(
int256 _fixedTokenGrowthInsideX128,
int256 _variableTokenGrowthInsideX128,
uint256 _feeGrowthInsideX128
) = _vamm.computeGrowthInside(_tickLower, _tickUpper);
(int256 _fixedTokenDelta, int256 _variableTokenDelta) = _position
.calculateFixedAndVariableDelta(
_fixedTokenGrowthInsideX128,
_variableTokenGrowthInsideX128
);
uint256 _feeDelta = _position.calculateFeeDelta(
_feeGrowthInsideX128
);
_position.updateBalancesViaDeltas(
_fixedTokenDelta - 1,
_variableTokenDelta - 1
);
_position.updateFixedAndVariableTokenGrowthInside(
_fixedTokenGrowthInsideX128,
_variableTokenGrowthInsideX128
);
/// @dev collect fees
if (_feeDelta > 0) {
_position.accumulatedFees += _feeDelta - 1;
_position.updateMarginViaDelta(_feeDelta.toInt256() - 1);
}
_position.updateFeeGrowthInside(_feeGrowthInsideX128);
} else {
if (_isMintBurn) {
(
int256 _fixedTokenGrowthInsideX128,
int256 _variableTokenGrowthInsideX128,
uint256 _feeGrowthInsideX128
) = _vamm.computeGrowthInside(_tickLower, _tickUpper);
_position.updateFixedAndVariableTokenGrowthInside(
_fixedTokenGrowthInsideX128,
_variableTokenGrowthInsideX128
);
_position.updateFeeGrowthInside(_feeGrowthInsideX128);
}
}
}
/// @notice Internal function that checks if the position's current margin is above the requirement
/// @param _position Position.Info of the position of interest, updates to position, edit it in storage
/// @param _tickLower Lower Tick of the position
/// @param _tickUpper Upper Tick of the position
/// @dev This function calculates the position margin requirement, compares it with the position.margin and reverts if the current position margin is below the requirement
function _checkPositionMarginAboveRequirement(
Position.Info storage _position,
int24 _tickLower,
int24 _tickUpper
) internal returns (int256 _positionMarginRequirement) {
_positionMarginRequirement = _getPositionMarginRequirement(
_position,
_tickLower,
_tickUpper,
false
).toInt256();
if (_position.margin <= _positionMarginRequirement) {
revert CustomErrors.MarginLessThanMinimum(
_positionMarginRequirement
);
}
}
/// @notice Check the position margin can be updated
/// @param _position Position.Info of the position of interest, updates to position, edit it in storage
/// @param _tickLower Lower Tick of the position
/// @param _tickUpper Upper Tick of the position
function _checkPositionMarginCanBeUpdated(
Position.Info storage _position,
int24 _tickLower,
int24 _tickUpper
) internal {
/// @dev If the IRS AMM has reached maturity, the only reason why someone would want to update
/// @dev their margin is to withdraw it completely. If so, the position needs to be settled
if (Time.blockTimestampScaled() >= _termEndTimestampWad) {
if (!_position.isSettled) {
revert CustomErrors.PositionNotSettled();