-
Notifications
You must be signed in to change notification settings - Fork 1
/
PanopticPool.sol
1940 lines (1712 loc) · 92.3 KB
/
PanopticPool.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.18;
// Interfaces
import {CollateralTracker} from "@contracts/CollateralTracker.sol";
import {SemiFungiblePositionManager} from "@contracts/SemiFungiblePositionManager.sol";
import {IUniswapV3Pool} from "univ3-core/interfaces/IUniswapV3Pool.sol";
// Inherited implementations
import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import {Multicall} from "@base/Multicall.sol";
// Libraries
import {Constants} from "@libraries/Constants.sol";
import {Errors} from "@libraries/Errors.sol";
import {FeesCalc} from "@libraries/FeesCalc.sol";
import {InteractionHelper} from "@libraries/InteractionHelper.sol";
import {Math} from "@libraries/Math.sol";
import {PanopticMath} from "@libraries/PanopticMath.sol";
// Custom types
import {LeftRightUnsigned, LeftRightSigned} from "@types/LeftRight.sol";
import {LiquidityChunk} from "@types/LiquidityChunk.sol";
import {TokenId} from "@types/TokenId.sol";
/// @title The Panoptic Pool: Create permissionless options on a CLAMM.
/// @author Axicon Labs Limited
/// @notice Manages positions, collateral, liquidations and forced exercises.
contract PanopticPool is ERC1155Holder, Multicall {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice Emitted when an account is liquidated.
/// @dev Need to unpack bonusAmounts to get raw numbers, which are always positive.
/// @param liquidator Address of the caller liquidating the distressed account
/// @param liquidatee Address of the distressed/liquidatable account
/// @param bonusAmounts LeftRight encoding for the the bonus paid for token 0 (right slot) and 1 (left slot) from the Panoptic Pool to the liquidator
event AccountLiquidated(
address indexed liquidator,
address indexed liquidatee,
LeftRightSigned bonusAmounts
);
/// @notice Emitted when a position is force exercised.
/// @param exercisor Address of the account that forces the exercise of the position
/// @param user Address of the owner of the liquidated position
/// @param tokenId TokenId of the liquidated position
/// @param exerciseFee LeftRight encoding for the cost paid by the exercisor to force the exercise of the token;
/// the cost for token 0 (right slot) and 1 (left slot) is represented as negative
event ForcedExercised(
address indexed exercisor,
address indexed user,
TokenId indexed tokenId,
LeftRightSigned exerciseFee
);
/// @notice Emitted when premium is settled independent of a mint/burn (e.g. during `settleLongPremium`).
/// @param user Address of the owner of the settled position
/// @param tokenId TokenId of the settled position
/// @param settledAmounts LeftRight encoding for the amount of premium settled for token0 (right slot) and token1 (left slot)
event PremiumSettled(
address indexed user,
TokenId indexed tokenId,
LeftRightSigned settledAmounts
);
/// @notice Emitted when an option is burned.
/// @param recipient User that burnt the option
/// @param positionSize The number of contracts burnt, expressed in terms of the asset
/// @param tokenId TokenId of the burnt option
/// @param premia LeftRight packing for the amount of premia collected for token0 (right) and token1 (left)
event OptionBurnt(
address indexed recipient,
uint128 positionSize,
TokenId indexed tokenId,
LeftRightSigned premia
);
/// @notice Emitted when an option is minted.
/// @param recipient User that minted the option
/// @param positionSize The number of contracts minted, expressed in terms of the asset
/// @param tokenId TokenId of the created option
/// @param poolUtilizations Packing of the pool utilization (how much funds are in the Panoptic pool versus the AMM pool at the time of minting),
/// right 64bits for token0 and left 64bits for token1, defined as (inAMM * 10_000) / totalAssets()
/// where totalAssets is the total tracked assets in the AMM and PanopticPool minus fees and donations to the Panoptic pool
event OptionMinted(
address indexed recipient,
uint128 positionSize,
TokenId indexed tokenId,
uint128 poolUtilizations
);
/*//////////////////////////////////////////////////////////////
IMMUTABLES & CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Lower price bound used when no slippage check is required.
int24 internal constant MIN_SWAP_TICK = Constants.MIN_V3POOL_TICK - 1;
/// @notice Upper price bound used when no slippage check is required.
int24 internal constant MAX_SWAP_TICK = Constants.MAX_V3POOL_TICK + 1;
/// @notice Flag that signals to compute premia for both the short and long legs of a position.
bool internal constant COMPUTE_ALL_PREMIA = true;
/// @notice Flag that signals to compute premia only for the long legs of a position.
bool internal constant COMPUTE_LONG_PREMIA = false;
/// @notice Flag that indicates only to include the share of (settled) premium that is available to collect when calling `_calculateAccumulatedPremia`.
bool internal constant ONLY_AVAILABLE_PREMIUM = false;
/// @notice Flag that signals to commit both collected Uniswap fees and settled long premium to `s_settledTokens`.
bool internal constant COMMIT_LONG_SETTLED = true;
/// @notice Flag that signals to only commit collected Uniswap fees to `s_settledTokens`.
bool internal constant DONOT_COMMIT_LONG_SETTLED = false;
/// @notice Flag that signals to add a new position to the user's positions hash (as opposed to removing an existing position).
bool internal constant ADD = true;
/// @notice The minimum window (in seconds) used to calculate the TWAP price for solvency checks during liquidations.
uint32 internal constant TWAP_WINDOW = 600;
/// @notice Parameter that determines which oracle type to use for the "slow" oracle price on non-liquidation solvency checks.
/// @dev If false, an 8-slot internal median array is used to compute the "slow" oracle price.
/// @dev This oracle is updated with the last Uniswap observation during `mintOptions` if MEDIAN_PERIOD has elapsed past the last observation.
/// @dev If true, the "slow" oracle price is instead computed on-the-fly from 8 Uniswap observations (spaced 5 observations apart) irrespective of the frequency of `mintOptions` calls.
bool internal constant SLOW_ORACLE_UNISWAP_MODE = false;
/// @notice The minimum amount of time, in seconds, permitted between internal TWAP updates.
uint256 internal constant MEDIAN_PERIOD = 60;
/// @notice Amount of Uniswap observations to include in the "fast" oracle price.
uint256 internal constant FAST_ORACLE_CARDINALITY = 3;
/// @dev Amount of observation indices to skip in between each observation for the "fast" oracle price.
/// @dev Note that the *minimum* total observation time is determined by the blocktime and may need to be adjusted by chain.
/// @dev Uniswap observations snapshot the last block's closing price at the first interaction with the pool in a block.
/// @dev In this case, if there is an interaction every block, the "fast" oracle can consider 3 consecutive block end prices (min=36 seconds on Ethereum).
uint256 internal constant FAST_ORACLE_PERIOD = 1;
/// @notice Amount of Uniswap observations to include in the "slow" oracle price (in Uniswap mode).
uint256 internal constant SLOW_ORACLE_CARDINALITY = 8;
/// @notice Amount of observation indices to skip in between each observation for the "slow" oracle price.
/// @dev Structured such that the minimum total observation time is 8 minutes on Ethereum (similar to internal median mode).
uint256 internal constant SLOW_ORACLE_PERIOD = 5;
/// @notice The maximum allowed delta between the currentTick and the Uniswap TWAP tick during a liquidation (~5% down, ~5.26% up).
/// @dev Mitigates manipulation of the currentTick that causes positions to be liquidated at a less favorable price.
int256 internal constant MAX_TWAP_DELTA_LIQUIDATION = 513;
/// @notice The maximum allowed delta between the fast and slow oracle ticks before solvency is evaluated at the slow oracle tick.
/// @dev Falls back on the more conservative (less solvent) tick during times of extreme volatility.
int256 internal constant MAX_SLOW_FAST_DELTA = 1800;
/// @notice The maximum allowed ratio for a single chunk, defined as: removedLiquidity / netLiquidity.
/// @dev The long premium spread multiplier that corresponds with the MAX_SPREAD value depends on VEGOID,
/// which can be explored in this calculator: https://www.desmos.com/calculator/mdeqob2m04.
uint64 internal constant MAX_SPREAD = 9 * (2 ** 32);
/// @notice The maximum allowed number of opened positions for a user.
uint64 internal constant MAX_POSITIONS = 32;
/// @notice Multiplier in basis points for the collateral requirement in the event of a buying power decrease, such as minting or force exercising another user.
uint256 internal constant BP_DECREASE_BUFFER = 13_333;
/// @notice Multiplier for the collateral requirement in the general case.
uint256 internal constant NO_BUFFER = 10_000;
/// @notice The "engine" of Panoptic - manages AMM liquidity and executes all mints/burns/exercises.
SemiFungiblePositionManager internal immutable SFPM;
/*//////////////////////////////////////////////////////////////
STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice The Uniswap v3 pool that this instance of Panoptic is deployed on.
IUniswapV3Pool internal s_univ3pool;
/// @notice Stores a sorted set of 8 price observations used to compute the internal median oracle price.
// The data for the last 8 interactions is stored as such:
// LAST UPDATED BLOCK TIMESTAMP (40 bits)
// [BLOCK.TIMESTAMP]
// (00000000000000000000000000000000) // dynamic
//
// ORDERING of tick indices least --> greatest (24 bits)
// The value of the bit codon ([#]) is a pointer to a tick index in the tick array.
// The position of the bit codon from most to least significant is the ordering of the
// tick index it points to from least to greatest.
//
// [7] [5] [3] [1] [0] [2] [4] [6]
// 111 101 011 001 000 010 100 110
//
// [Constants.MIN_V3POOL_TICK-1] [7]
// 111100100111011000010111
//
// [Constants.MAX_V3POOL_TICK+1] [0]
// 000011011000100111101001
//
// [Constants.MIN_V3POOL_TICK-1] [6]
// 111100100111011000010111
//
// [Constants.MAX_V3POOL_TICK+1] [1]
// 000011011000100111101001
//
// [Constants.MIN_V3POOL_TICK-1] [5]
// 111100100111011000010111
//
// [Constants.MAX_V3POOL_TICK+1] [2]
// 000011011000100111101001
//
// [CURRENT TICK] [4]
// (000000000000000000000000) // dynamic
//
// [CURRENT TICK] [3]
// (000000000000000000000000) // dynamic
uint256 internal s_miniMedian;
// ERC4626 vaults that users collateralize their positions with
// Each token has its own vault, listed in the same order as the tokens in the pool
// In addition to collateral deposits, these vaults also handle various collateral/bonus/exercise computations
/// @notice Collateral vault for token0 in the Uniswap pool.
CollateralTracker internal s_collateralToken0;
/// @notice Collateral vault for token1 in the Uniswap pool.
CollateralTracker internal s_collateralToken1;
/// @notice Nested mapping that tracks the option formation: address => tokenId => leg => premiaGrowth.
/// @dev Premia growth is taking a snapshot of the chunk premium in SFPM, which is measuring the amount of fees
/// collected for every chunk per unit of liquidity (net or short, depending on the isLong value of the specific leg index).
mapping(address account => mapping(TokenId tokenId => mapping(uint256 leg => LeftRightUnsigned premiaGrowth)))
internal s_options;
/// @notice Per-chunk `last` value that gives the aggregate amount of premium owed to all sellers when multiplied by the total amount of liquidity `totalLiquidity`.
/// @dev totalGrossPremium = totalLiquidity * (grossPremium(perLiquidityX64) - lastGrossPremium(perLiquidityX64)) / 2**64.
/// @dev Used to compute the denominator for the fraction of premium available to sellers to collect.
/// @dev LeftRight - right slot is token0, left slot is token1.
mapping(bytes32 chunkKey => LeftRightUnsigned lastGrossPremium) internal s_grossPremiumLast;
/// @notice Per-chunk accumulator for tokens owed to sellers that have been settled and are now available.
/// @dev This number increases when buyers pay long premium and when tokens are collected from Uniswap.
/// @dev It decreases when sellers close positions and collect the premium they are owed.
/// @dev LeftRight - right slot is token0, left slot is token1.
mapping(bytes32 chunkKey => LeftRightUnsigned settledTokens) internal s_settledTokens;
/// @notice Tracks the amount of liquidity for a user+tokenId (right slot) and the initial pool utilizations when that position was minted (left slot).
// poolUtilizations when minted (left) liquidity=ERC1155 balance (right)
// token0 token1
// |<-- 64 bits -->|<-- 64 bits -->|<---------- 128 bits ---------->|
// |<-------------------------- 256 bits -------------------------->|
mapping(address account => mapping(TokenId tokenId => LeftRightUnsigned balanceAndUtilizations))
internal s_positionBalance;
// numPositions (32 positions max) user positions hash
// |<-- 8 bits -->|<------------------ 248 bits ------------------->|
// |<---------------------- 256 bits ------------------------------>|
/// @notice Tracks the position list hash i.e keccak256(XORs of abi.encodePacked(positionIdList)).
/// @dev The order and content of this list (the preimage for the hash) is emitted in an event every time it is changed.
/// @dev A component of this hash also tracks the total number of positions (i.e. makes sure the length of the provided positionIdList matches).
/// @dev The purpose of this system is to reduce storage usage when a user has more than one active position.
/// @dev Instead of having to manage an unwieldy storage array and do lots of loads, we just store a hash of the array.
/// @dev This hash can be cheaply verified on every operation with a user provided positionIdList - which can then be used for operations
/// without having to every load any other data from storage.
// numPositions (32 positions max) user positions hash
// |<-- 8 bits -->|<------------------ 248 bits ------------------->|
// |<---------------------- 256 bits ------------------------------>|
mapping(address account => uint256 positionsHash) internal s_positionsHash;
/*//////////////////////////////////////////////////////////////
INITIALIZATION
//////////////////////////////////////////////////////////////*/
/// @notice Store the address of the canonical SemiFungiblePositionManager (SFPM) contract.
/// @param _sfpm The address of the SFPM
constructor(SemiFungiblePositionManager _sfpm) {
SFPM = _sfpm;
}
/// @notice Initializes a Panoptic Pool on top of an existing Uniswap v3 + collateral vault pair.
/// @dev Must be called first (by a factory contract) before any transaction can occur.
/// @param _univ3pool Address of the target Uniswap v3 pool
/// @param token0 Address of the pool's token0
/// @param token1 Address of the pool's token1
/// @param collateralTracker0 Address of the collateral vault for token0
/// @param collateralTracker1 Address of the collateral vault for token1
function startPool(
IUniswapV3Pool _univ3pool,
address token0,
address token1,
CollateralTracker collateralTracker0,
CollateralTracker collateralTracker1
) external {
// reverts if the Uniswap pool has already been initialized
if (address(s_univ3pool) != address(0)) revert Errors.PoolAlreadyInitialized();
// Store the univ3Pool variable
s_univ3pool = IUniswapV3Pool(_univ3pool);
(, int24 currentTick, , , , , ) = IUniswapV3Pool(_univ3pool).slot0();
// Store the median data
unchecked {
s_miniMedian =
(uint256(block.timestamp) << 216) +
// magic number which adds (7,5,3,1,0,2,4,6) order and minTick in positions 7, 5, 3 and maxTick in 6, 4, 2
// see comment on s_miniMedian initialization for format of this magic number
(uint256(0xF590A6F276170D89E9F276170D89E9F276170D89E9000000000000)) +
(uint256(uint24(currentTick)) << 24) + // add to slot 4
(uint256(uint24(currentTick))); // add to slot 3
}
// Store the collateral token0
s_collateralToken0 = collateralTracker0;
s_collateralToken1 = collateralTracker1;
// consolidate all 4 approval calls to one library delegatecall in order to reduce bytecode size
// approves:
// SFPM: token0, token1
// CollateralTracker0 - token0
// CollateralTracker1 - token1
InteractionHelper.doApprovals(SFPM, collateralTracker0, collateralTracker1, token0, token1);
}
/*//////////////////////////////////////////////////////////////
QUERY HELPERS
//////////////////////////////////////////////////////////////*/
/// @notice Reverts if the caller has a lower collateral balance than required to meet the provided `minValue0` and `minValue1`.
/// @dev Can be used for composable slippage checks with `multicall` (such as for a force exercise or liquidation).
/// @param minValue0 The minimum acceptable `token0` value of collateral
/// @param minValue1 The minimum acceptable `token1` value of collateral
function assertMinCollateralValues(uint256 minValue0, uint256 minValue1) external view {
CollateralTracker ct0 = s_collateralToken0;
CollateralTracker ct1 = s_collateralToken1;
if (
ct0.convertToAssets(ct0.balanceOf(msg.sender)) < minValue0 ||
ct1.convertToAssets(ct1.balanceOf(msg.sender)) < minValue1
) revert Errors.NotEnoughCollateral();
}
/// @notice Determines if account is eligible to withdraw or transfer collateral.
/// @dev Checks whether account is solvent with `BP_DECREASE_BUFFER` according to `_validateSolvency`.
/// @dev Prevents insolvent and near-insolvent accounts from withdrawing collateral before they are liquidated.
/// @dev Reverts if account is not solvent with `BP_DECREASE_BUFFER`.
/// @param user The account to check for collateral withdrawal eligibility
/// @param positionIdList The list of all option positions held by `user`
function validateCollateralWithdrawable(
address user,
TokenId[] calldata positionIdList
) external view {
_validateSolvency(user, positionIdList, BP_DECREASE_BUFFER);
}
/// @notice Returns the total number of contracts owned by user for a specified position.
/// @param user Address of the account to be checked
/// @param tokenId TokenId of the option position to be checked
/// @return balance Number of contracts of tokenId owned by the user
/// @return poolUtilization0 The utilization of token0 in the Panoptic pool at mint
/// @return poolUtilization1 The utilization of token1 in the Panoptic pool at mint
function optionPositionBalance(
address user,
TokenId tokenId
) external view returns (uint128 balance, uint64 poolUtilization0, uint64 poolUtilization1) {
// Extract the data stored in s_positionBalance for the provided user + tokenId
LeftRightUnsigned balanceData = s_positionBalance[user][tokenId];
// Return the unpacked data: balanceOf(user, tokenId) and packed pool utilizations at the time of minting
balance = balanceData.rightSlot();
// pool utilizations are packed into a single uint128
// the 64 least significant bits are the utilization of token0, so we can simply cast to uint64 to extract it
// (cutting off the 64 most significant bits)
poolUtilization0 = uint64(balanceData.leftSlot());
// the 64 most significant bits are the utilization of token1, so we can shift the number to the right by 64 to extract it
// (shifting away the 64 least significant bits)
poolUtilization1 = uint64(balanceData.leftSlot() >> 64);
}
/// @notice Compute the total amount of premium accumulated for a list of positions.
/// @param user Address of the user that owns the positions
/// @param positionIdList List of positions. Written as [tokenId1, tokenId2, ...]
/// @param includePendingPremium If true, include premium that is owed to the user but has not yet settled; if false, only include premium that is available to collect
/// @return premium0 Premium for token0 (negative = amount is owed)
/// @return premium1 Premium for token1 (negative = amount is owed)
/// @return A list of balances and pool utilization for each position, of the form [[tokenId0, balances0], [tokenId1, balances1], ...]
function calculateAccumulatedFeesBatch(
address user,
bool includePendingPremium,
TokenId[] calldata positionIdList
) external view returns (int128 premium0, int128 premium1, uint256[2][] memory) {
// Get the current tick of the Uniswap pool
(, int24 currentTick, , , , , ) = s_univ3pool.slot0();
// Compute the accumulated premia for all tokenId in positionIdList (includes short+long premium)
(LeftRightSigned premia, uint256[2][] memory balances) = _calculateAccumulatedPremia(
user,
positionIdList,
COMPUTE_ALL_PREMIA,
includePendingPremium,
currentTick
);
// Return the premia as (token0, token1)
return (premia.rightSlot(), premia.leftSlot(), balances);
}
/// @notice Compute the net token amounts owned by a given positionIdList in the Uniswap pool at the given price tick.
/// @param user Address of the user that owns the positions.
/// @param atTick Tick at which the portfolio value is evaluated
/// @param positionIdList List of positions. Written as [tokenId1, tokenId2, ...]
/// @return value0 Net amount of token0 in the Uniswap pool owned by the positionIdList (negative = borrowed liquidity owed to sellers)
/// @return value1 Net amount of token1 in the Uniswap pool owned by the positionIdList (negative = borrowed liquidity owed to sellers)
function calculatePortfolioValue(
address user,
int24 atTick,
TokenId[] calldata positionIdList
) external view returns (int256 value0, int256 value1) {
(value0, value1) = FeesCalc.getPortfolioValue(
atTick,
s_positionBalance[user],
positionIdList
);
}
/// @notice Calculate the accumulated premia owed from the option buyer to the option seller.
/// @param user The holder of options
/// @param positionIdList The list of all option positions held by user
/// @param computeAllPremia Whether to compute accumulated premia for all legs held by the user (true), or just owed premia for long legs (false)
/// @param includePendingPremium If true, include premium that is owed to the user but has not yet settled; if false, only include premium that is available to collect
/// @return portfolioPremium The computed premia of the user's positions, where premia contains the accumulated premia for token0 in the right slot and for token1 in the left slot
/// @return balances A list of balances and pool utilization for each position, of the form [[tokenId0, balances0], [tokenId1, balances1], ...]
function _calculateAccumulatedPremia(
address user,
TokenId[] calldata positionIdList,
bool computeAllPremia,
bool includePendingPremium,
int24 atTick
) internal view returns (LeftRightSigned portfolioPremium, uint256[2][] memory balances) {
uint256 pLength = positionIdList.length;
balances = new uint256[2][](pLength);
address c_user = user;
// loop through each option position/tokenId
for (uint256 k = 0; k < pLength; ) {
TokenId tokenId = positionIdList[k];
balances[k][0] = TokenId.unwrap(tokenId);
balances[k][1] = LeftRightUnsigned.unwrap(s_positionBalance[c_user][tokenId]);
(
LeftRightSigned[4] memory premiaByLeg,
uint256[2][4] memory premiumAccumulatorsByLeg
) = _getPremia(
tokenId,
LeftRightUnsigned.wrap(balances[k][1]).rightSlot(),
c_user,
computeAllPremia,
atTick
);
uint256 numLegs = tokenId.countLegs();
for (uint256 leg = 0; leg < numLegs; ) {
if (tokenId.isLong(leg) == 0 && !includePendingPremium) {
bytes32 chunkKey = keccak256(
abi.encodePacked(
tokenId.strike(leg),
tokenId.width(leg),
tokenId.tokenType(leg)
)
);
LeftRightUnsigned availablePremium = _getAvailablePremium(
_getTotalLiquidity(tokenId, leg),
s_settledTokens[chunkKey],
s_grossPremiumLast[chunkKey],
LeftRightUnsigned.wrap(uint256(LeftRightSigned.unwrap(premiaByLeg[leg]))),
premiumAccumulatorsByLeg[leg]
);
portfolioPremium = portfolioPremium.add(
LeftRightSigned.wrap(int256(LeftRightUnsigned.unwrap(availablePremium)))
);
} else {
portfolioPremium = portfolioPremium.add(premiaByLeg[leg]);
}
unchecked {
++leg;
}
}
unchecked {
++k;
}
}
return (portfolioPremium, balances);
}
/*//////////////////////////////////////////////////////////////
ONBOARD MEDIAN TWAP
//////////////////////////////////////////////////////////////*/
/// @notice Updates the internal median with the last Uniswap observation if the MEDIAN_PERIOD has elapsed.
function pokeMedian() external {
(, , uint16 observationIndex, uint16 observationCardinality, , , ) = s_univ3pool.slot0();
(, uint256 medianData) = PanopticMath.computeInternalMedian(
observationIndex,
observationCardinality,
MEDIAN_PERIOD,
s_miniMedian,
s_univ3pool
);
if (medianData != 0) s_miniMedian = medianData;
}
/*//////////////////////////////////////////////////////////////
MINT/BURN INTERFACE
//////////////////////////////////////////////////////////////*/
/// @notice Validates the current options of the user, and mints a new position.
/// @param positionIdList The list of currently held positions by the user, where the newly minted position(token) will be the last element in 'positionIdList'
/// @param positionSize The size of the position to be minted, expressed in terms of the asset
/// @param effectiveLiquidityLimitX32 Maximum amount of "spread" defined as removedLiquidity/netLiquidity for a new position and
/// denominated as X32 = (ratioLimit * 2**32)
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price
function mintOptions(
TokenId[] calldata positionIdList,
uint128 positionSize,
uint64 effectiveLiquidityLimitX32,
int24 tickLimitLow,
int24 tickLimitHigh
) external {
_mintOptions(
positionIdList,
positionSize,
effectiveLiquidityLimitX32,
tickLimitLow,
tickLimitHigh
);
}
/// @notice Closes and burns the caller's entire balance of `tokenId`.
/// @param tokenId The tokenId of the option position to be burnt
/// @param newPositionIdList The new positionIdList without the token being burnt
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price
function burnOptions(
TokenId tokenId,
TokenId[] calldata newPositionIdList,
int24 tickLimitLow,
int24 tickLimitHigh
) external {
_burnOptions(COMMIT_LONG_SETTLED, tokenId, msg.sender, tickLimitLow, tickLimitHigh);
_validateSolvency(msg.sender, newPositionIdList, NO_BUFFER);
}
/// @notice Closes and burns the caller's entire balance of each `tokenId` in `positionIdList.
/// @param positionIdList The list of tokenIds for the option positions to be burnt
/// @param newPositionIdList The new positionIdList without the token(s) being burnt
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price
function burnOptions(
TokenId[] calldata positionIdList,
TokenId[] calldata newPositionIdList,
int24 tickLimitLow,
int24 tickLimitHigh
) external {
_burnAllOptionsFrom(
msg.sender,
tickLimitLow,
tickLimitHigh,
COMMIT_LONG_SETTLED,
positionIdList
);
_validateSolvency(msg.sender, newPositionIdList, NO_BUFFER);
}
/*//////////////////////////////////////////////////////////////
POSITION MINTING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Validates the current options of the user, and mints a new position.
/// @param positionIdList The list of currently held positions by the user, where the newly minted position(token) will be the last element in 'positionIdList'
/// @param positionSize The size of the position to be minted, expressed in terms of the asset
/// @param effectiveLiquidityLimitX32 Maximum amount of "spread" defined as removedLiquidity/netLiquidity for a new position and
/// denominated as X32 = (ratioLimit * 2**32)
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price
function _mintOptions(
TokenId[] calldata positionIdList,
uint128 positionSize,
uint64 effectiveLiquidityLimitX32,
int24 tickLimitLow,
int24 tickLimitHigh
) internal {
// the new tokenId will be the last element in 'positionIdList'
TokenId tokenId;
unchecked {
tokenId = positionIdList[positionIdList.length - 1];
}
// do duplicate checks and the checks related to minting and positions
_validatePositionList(msg.sender, positionIdList, 1);
// make sure the tokenId is for this Panoptic pool
if (tokenId.poolId() != SFPM.getPoolId(address(s_univ3pool)))
revert Errors.InvalidTokenIdParameter(0);
// disallow user to mint exact same position
// in order to do it, user should burn it first and then mint
if (LeftRightUnsigned.unwrap(s_positionBalance[msg.sender][tokenId]) != 0)
revert Errors.PositionAlreadyMinted();
// Mint in the SFPM and update state of collateral
uint128 poolUtilizations = _mintInSFPMAndUpdateCollateral(
tokenId,
positionSize,
tickLimitLow,
tickLimitHigh
);
// calculate and write position data
_addUserOption(tokenId, effectiveLiquidityLimitX32);
// update the users options balance of position 'tokenId'
// NOTE: user can't mint same position multiple times, so set the positionSize instead of adding
s_positionBalance[msg.sender][tokenId] = LeftRightUnsigned
.wrap(0)
.toLeftSlot(poolUtilizations)
.toRightSlot(positionSize);
// Perform solvency check on user's account to ensure they had enough buying power to mint the option
// Add an initial buffer to the collateral requirement to prevent users from minting their account close to insolvency
uint256 medianData = _validateSolvency(msg.sender, positionIdList, BP_DECREASE_BUFFER);
// Update `s_miniMedian` with a new observation if the last observation is old enough (returned medianData is nonzero)
if (medianData != 0) s_miniMedian = medianData;
emit OptionMinted(msg.sender, positionSize, tokenId, poolUtilizations);
}
/// @notice Move all the required liquidity to/from the AMM and settle any required collateral deltas.
/// @param tokenId The option position to be minted
/// @param positionSize The size of the position, expressed in terms of the asset
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price
/// @return Packing of the pool utilization (how much funds are in the Panoptic pool versus the AMM pool) at the time of minting,
/// right 64bits for token0 and left 64bits for token1
function _mintInSFPMAndUpdateCollateral(
TokenId tokenId,
uint128 positionSize,
int24 tickLimitLow,
int24 tickLimitHigh
) internal returns (uint128) {
(LeftRightUnsigned[4] memory collectedByLeg, LeftRightSigned totalSwapped) = SFPM
.mintTokenizedPosition(tokenId, positionSize, tickLimitLow, tickLimitHigh);
_updateSettlementPostMint(tokenId, collectedByLeg, positionSize);
uint128 poolUtilizations = _payCommissionAndWriteData(tokenId, positionSize, totalSwapped);
return poolUtilizations;
}
/// @notice Take the commission fees for minting `tokenId` and settle any other required collateral deltas.
/// @param tokenId The option position
/// @param positionSize The size of the position, expressed in terms of the asset
/// @param totalSwapped The amount of tokens moved during creation of the option position
/// @return Packing of the pool utilization (how much funds are in the Panoptic pool versus the AMM pool at the time of minting),
/// right 64bits for token0 and left 64bits for token1, defined as (inAMM * 10_000) / totalAssets()
/// where totalAssets is the total tracked assets in the AMM and PanopticPool minus fees and donations to the Panoptic pool
function _payCommissionAndWriteData(
TokenId tokenId,
uint128 positionSize,
LeftRightSigned totalSwapped
) internal returns (uint128) {
// compute how much of tokenId is long and short positions
(LeftRightSigned longAmounts, LeftRightSigned shortAmounts) = PanopticMath
.computeExercisedAmounts(tokenId, positionSize);
int256 utilization0 = s_collateralToken0.takeCommissionAddData(
msg.sender,
longAmounts.rightSlot(),
shortAmounts.rightSlot(),
totalSwapped.rightSlot()
);
int256 utilization1 = s_collateralToken1.takeCommissionAddData(
msg.sender,
longAmounts.leftSlot(),
shortAmounts.leftSlot(),
totalSwapped.leftSlot()
);
// return pool utilizations as a uint128 (pool Utilization is always < 10000)
unchecked {
return uint128(uint256(utilization0) + uint128(uint256(utilization1) << 64));
}
}
/// @notice Add a new option to the user's position hash, perform required checks, and initialize the premium accumulators.
/// @param tokenId The minted option position
/// @param effectiveLiquidityLimitX32 Maximum amount of "spread" defined as removedLiquidity/netLiquidity for a new position
/// denominated as X32 = (ratioLimit * 2**32)
function _addUserOption(TokenId tokenId, uint64 effectiveLiquidityLimitX32) internal {
// Update the position list hash (hash = XOR of all keccak256(tokenId)). Remove hash by XOR'ing again
_updatePositionsHash(msg.sender, tokenId, ADD);
uint256 numLegs = tokenId.countLegs();
// compute upper and lower tick and liquidity
for (uint256 leg = 0; leg < numLegs; ) {
// Extract base fee (AMM swap/trading fees) for the position and add it to s_options
// (ie. the (feeGrowth * liquidity) / 2**128 for each token)
(int24 tickLower, int24 tickUpper) = tokenId.asTicks(leg);
uint256 isLong = tokenId.isLong(leg);
{
(uint128 premiumAccumulator0, uint128 premiumAccumulator1) = SFPM.getAccountPremium(
address(s_univ3pool),
address(this),
tokenId.tokenType(leg),
tickLower,
tickUpper,
type(int24).max,
isLong
);
// update the premium accumulators
s_options[msg.sender][tokenId][leg] = LeftRightUnsigned
.wrap(0)
.toRightSlot(premiumAccumulator0)
.toLeftSlot(premiumAccumulator1);
}
// verify base Liquidity limit only if new position is long
if (isLong == 1) {
// Move this into a new function
_checkLiquiditySpread(
tokenId,
leg,
tickLower,
tickUpper,
uint64(Math.min(effectiveLiquidityLimitX32, MAX_SPREAD))
);
}
unchecked {
++leg;
}
}
}
/*//////////////////////////////////////////////////////////////
POSITION BURNING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Close all options in `positionIdList.
/// @param owner The owner of the option position to be closed
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price on each option close
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price on each option close
/// @param commitLongSettled Whether to commit the long premium that will be settled to storage (disabled during liquidations)
/// @param positionIdList The list of option positions to close
/// @return netPaid The net amount of tokens paid after closing the positions
/// @return premiasByLeg The amount of premia owed to the user for each leg of the position
function _burnAllOptionsFrom(
address owner,
int24 tickLimitLow,
int24 tickLimitHigh,
bool commitLongSettled,
TokenId[] calldata positionIdList
) internal returns (LeftRightSigned netPaid, LeftRightSigned[4][] memory premiasByLeg) {
premiasByLeg = new LeftRightSigned[4][](positionIdList.length);
for (uint256 i = 0; i < positionIdList.length; ) {
LeftRightSigned paidAmounts;
(paidAmounts, premiasByLeg[i]) = _burnOptions(
commitLongSettled,
positionIdList[i],
owner,
tickLimitLow,
tickLimitHigh
);
netPaid = netPaid.add(paidAmounts);
unchecked {
++i;
}
}
}
/// @notice Close a single option position.
/// @param tokenId The option position to burn
/// @param owner The owner of the option position to be burned
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price on each option close
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price on each option close
/// @param commitLongSettled Whether to commit the long premium that will be settled to storage (disabled during liquidations)
/// @return paidAmounts The net amount of tokens paid after closing the position
/// @return premiaByLeg The amount of premia owed to the user for each leg of the position
function _burnOptions(
bool commitLongSettled,
TokenId tokenId,
address owner,
int24 tickLimitLow,
int24 tickLimitHigh
) internal returns (LeftRightSigned paidAmounts, LeftRightSigned[4] memory premiaByLeg) {
uint128 positionSize = s_positionBalance[owner][tokenId].rightSlot();
LeftRightSigned premiaOwed;
// burn position and do exercise checks
(premiaOwed, premiaByLeg, paidAmounts) = _burnAndHandleExercise(
commitLongSettled,
tickLimitLow,
tickLimitHigh,
tokenId,
positionSize,
owner
);
// erase position data
_updatePositionDataBurn(owner, tokenId);
emit OptionBurnt(owner, positionSize, tokenId, premiaOwed);
}
/// @notice Remove an option position from a user's position hash and reset its premium accumulators on close.
/// @param owner The owner of the option position
/// @param tokenId The option position being closed
function _updatePositionDataBurn(address owner, TokenId tokenId) internal {
// reset balances and delete stored option data
s_positionBalance[owner][tokenId] = LeftRightUnsigned.wrap(0);
uint256 numLegs = tokenId.countLegs();
for (uint256 leg = 0; leg < numLegs; ) {
if (tokenId.isLong(leg) == 0) {
// Check the liquidity spread, make sure that closing the option does not exceed the MAX_SPREAD allowed
(int24 tickLower, int24 tickUpper) = tokenId.asTicks(leg);
_checkLiquiditySpread(tokenId, leg, tickLower, tickUpper, MAX_SPREAD);
}
s_options[owner][tokenId][leg] = LeftRightUnsigned.wrap(0);
unchecked {
++leg;
}
}
// Update the position list hash (hash = XOR of all keccak256(tokenId)). Remove hash by XOR'ing again
_updatePositionsHash(owner, tokenId, !ADD);
}
/// @notice Validates the solvency of `user`.
/// @dev Falls back to the more conservative tick if the delta between the fast and slow oracle exceeds `MAX_SLOW_FAST_DELTA`.
/// @dev Effectively, this means that the users must be solvent at both the fast and slow oracle ticks if one of them is stale to mint or burn options.
/// @param user The account to validate
/// @param positionIdList The list of positions to validate solvency for
/// @param buffer The buffer to apply to the collateral requirement for `user`
/// @return medianData If nonzero (enough time has passed since last observation), the updated value for `s_miniMedian` with a new observation
function _validateSolvency(
address user,
TokenId[] calldata positionIdList,
uint256 buffer
) internal view returns (uint256 medianData) {
// check that the provided positionIdList matches the positions in memory
_validatePositionList(user, positionIdList, 0);
IUniswapV3Pool _univ3pool = s_univ3pool;
(
,
int24 currentTick,
uint16 observationIndex,
uint16 observationCardinality,
,
,
) = _univ3pool.slot0();
int24 fastOracleTick = PanopticMath.computeMedianObservedPrice(
_univ3pool,
observationIndex,
observationCardinality,
FAST_ORACLE_CARDINALITY,
FAST_ORACLE_PERIOD
);
int24 slowOracleTick;
if (SLOW_ORACLE_UNISWAP_MODE) {
slowOracleTick = PanopticMath.computeMedianObservedPrice(
_univ3pool,
observationIndex,
observationCardinality,
SLOW_ORACLE_CARDINALITY,
SLOW_ORACLE_PERIOD
);
} else {
(slowOracleTick, medianData) = PanopticMath.computeInternalMedian(
observationIndex,
observationCardinality,
MEDIAN_PERIOD,
s_miniMedian,
_univ3pool
);
}
// Check the user's solvency at the fast tick; revert if not solvent
bool solventAtFast = _checkSolvencyAtTick(
user,
positionIdList,
currentTick,
fastOracleTick,
buffer
);
if (!solventAtFast) revert Errors.NotEnoughCollateral();
// If one of the ticks is too stale, we fall back to the more conservative tick, i.e, the user must be solvent at both the fast and slow oracle ticks.
if (Math.abs(int256(fastOracleTick) - slowOracleTick) > MAX_SLOW_FAST_DELTA)
if (!_checkSolvencyAtTick(user, positionIdList, currentTick, slowOracleTick, buffer))
revert Errors.NotEnoughCollateral();
}
/// @notice Burns and handles the exercise of options.
/// @param commitLongSettled Whether to commit the long premium that will be settled to storage (disabled during liquidations)
/// @param tickLimitLow The lower bound of an acceptable open interval for the ending price
/// @param tickLimitHigh The upper bound of an acceptable open interval for the ending price
/// @param tokenId The option position to burn
/// @param positionSize The size of the option position, expressed in terms of the asset
/// @param owner The owner of the option position
/// @return realizedPremia The net premia paid/received from the option position
/// @return premiaByLeg The premia owed to the user for each leg of the option position
/// @return paidAmounts The net amount of tokens paid after closing the position
function _burnAndHandleExercise(
bool commitLongSettled,
int24 tickLimitLow,
int24 tickLimitHigh,
TokenId tokenId,
uint128 positionSize,
address owner
)
internal
returns (
LeftRightSigned realizedPremia,
LeftRightSigned[4] memory premiaByLeg,
LeftRightSigned paidAmounts
)
{
(LeftRightUnsigned[4] memory collectedByLeg, LeftRightSigned totalSwapped) = SFPM
.burnTokenizedPosition(tokenId, positionSize, tickLimitLow, tickLimitHigh);
(realizedPremia, premiaByLeg) = _updateSettlementPostBurn(
owner,
tokenId,
collectedByLeg,
positionSize,
commitLongSettled
);
(LeftRightSigned longAmounts, LeftRightSigned shortAmounts) = PanopticMath
.computeExercisedAmounts(tokenId, positionSize);
{
int128 paid0 = s_collateralToken0.exercise(
owner,
longAmounts.rightSlot(),
shortAmounts.rightSlot(),
totalSwapped.rightSlot(),
realizedPremia.rightSlot()
);
paidAmounts = paidAmounts.toRightSlot(paid0);
}
{
int128 paid1 = s_collateralToken1.exercise(
owner,
longAmounts.leftSlot(),
shortAmounts.leftSlot(),
totalSwapped.leftSlot(),
realizedPremia.leftSlot()
);
paidAmounts = paidAmounts.toLeftSlot(paid1);
}
}
/*//////////////////////////////////////////////////////////////
LIQUIDATIONS & FORCED EXERCISES
//////////////////////////////////////////////////////////////*/
/// @notice Liquidates a distressed account. Will burn all positions and issue a bonus to the liquidator.
/// @dev Will revert if liquidated account is solvent at the TWAP tick or if TWAP tick is too far away from the current tick.
/// @param positionIdListLiquidator List of positions owned by the liquidator
/// @param liquidatee Address of the distressed account
/// @param delegations LeftRight amounts of token0 and token1 (token0:token1 right:left) delegated to the liquidatee by the liquidator so the option can be smoothly exercised
/// @param positionIdList List of positions owned by the user. Written as [tokenId1, tokenId2, ...]
function liquidate(
TokenId[] calldata positionIdListLiquidator,
address liquidatee,
LeftRightUnsigned delegations,
TokenId[] calldata positionIdList
) external {
_validatePositionList(liquidatee, positionIdList, 0);
// Assert the account we are liquidating is actually insolvent
int24 twapTick = getUniV3TWAP();
LeftRightUnsigned tokenData0;
LeftRightUnsigned tokenData1;
LeftRightSigned premia;
{
(, int24 currentTick, , , , , ) = s_univ3pool.slot0();