-
Notifications
You must be signed in to change notification settings - Fork 16
/
CollateralTracker.sol
2025 lines (1779 loc) · 100 KB
/
CollateralTracker.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 {PanopticFactory} from "./PanopticFactory.sol";
import {PanopticPool} from "./PanopticPool.sol";
import {IERC20Partial} from "@tokens/interfaces/IERC20Partial.sol";
import {IUniswapV3Pool} from "univ3-core/interfaces/IUniswapV3Pool.sol";
// Inherited implementations
import {ERC20Minimal} from "@tokens/ERC20Minimal.sol";
import {Multicall} from "@multicall/Multicall.sol";
// Libraries
import {Constants} from "@libraries/Constants.sol";
import {Errors} from "@libraries/Errors.sol";
import {InteractionHelper} from "@libraries/InteractionHelper.sol";
import {Math} from "@libraries/Math.sol";
import {PanopticMath} from "@libraries/PanopticMath.sol";
import {SafeTransferLib} from "@libraries/SafeTransferLib.sol";
// Custom types
import {TickStateCallContext} from "@types/TickStateCallContext.sol";
import {LeftRight} from "@types/LeftRight.sol";
import {LiquidityChunk} from "@types/LiquidityChunk.sol";
import {TokenId} from "@types/TokenId.sol";
/// @title Collateral Tracking System / Margin Accounting used in conjunction with a Panoptic Pool.
/// @author Axicon Labs Limited
//
/// @notice Tracks collateral of users which is key to ensure the correct level of collateralization is achieved.
/// This is represented as an ERC20 share token. A Panoptic pool has 2 tokens, each issued by its own instance of a CollateralTracker.
/// All math within this contract pertains to a single token.
//
/// @notice This contract uses the ERC4626 standard allowing the minting and burning of "shares" (represented using ERC20 inheritance) in exchange for underlying "assets".
/// Panoptic uses a collateral tracking system that is similar to TradFi margin accounts. While users can borrow and
/// effectively control funds several times larger than the collateral they deposited, they cannot withdraw those funds
/// from the Panoptic-Uniswap ecosystem. All funds are always owned by the Panoptic protocol, but users will:
//
/// @notice 1) collect any fees generated by selling an option.
//
/// @notice 2) get any gain in capital that results from buying an option that becomes in-the-money.
contract CollateralTracker is ERC20Minimal, Multicall {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
/// @notice emitted when assets are deposited into the Collateral Tracker.
/// @param sender the address of the caller (and depositor).
/// @param owner the address of the recipient of the newly minted shares.
/// @param assets the amount of assets deposited by 'sender' in exchange for 'shares'.
/// @param shares the amount of shares minted to 'owner'.
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
/// @notice emitted when assets are withdrawn from the Collateral Tracker.
/// @param sender the address of the caller.
/// @param receiver the address of the recipient of the withdrawn assets.
/// @param owner the address of the owner of the shares being burned.
/// @param assets the amount of assets withdrawn to 'receiver'.
/// @param shares the amount of shares burned by 'owner' in exchange for 'assets'.
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/// @notice Emitted when the collateral tracking parameters are changed. See struct 'Parameters' for passed in arguments.
/// @param newParameters A single packed struct that contains information about the new parameters.
event ParametersUpdated(Parameters newParameters);
/*//////////////////////////////////////////////////////////////
TYPES
//////////////////////////////////////////////////////////////*/
// enables packing of types within int128|int128 or uint128|uint128 containers.
using LeftRight for int256;
using LeftRight for uint256;
// represents a single liquidity chunk in Uniswap. Contains tickLower, tickUpper, and amount of liquidity
using LiquidityChunk for uint256;
// container that holds current tick, median tick, and caller
using TickStateCallContext for uint256;
// represents an option position of up to four legs as a single ERC1155 tokenId
using TokenId for uint256;
/// @notice Mutable parameters that can be used to adjust various protocol mechanisms and behaviors.
/// These parameters are stored in CollateralTracker and are used in various calculations.
/// They can be updated with the 'updateParameters' function in this contract.
/// @dev maintenaceMarginRatio minimum ratio of actual to required collateral that must be maintained to mint a new position (decimals=10000).
/// @dev commissionFee the commission fee (basis points).
/// @dev ITMSpreadFee additional risk premium charged on intrinsic value of ITM positions defined in basis points as a multiple of the pool fee / 10000.
/// @dev sellCollateralRatio minimum collateral ratio for selling options when pool utilization < targetPoolUtilization (basis points).
/// @dev buyCollateralRatio maximum collateral ratio for buying options when pool utilization < targetPoolUtilization (basis points).
/// @dev targetPoolUtilization utilization where sell collateral slopes upwards and buy collateral slopes downwards after (basis points).
/// @dev saturatedPoolUtilization pool utilization at which sell collateral ratio reaches its maximum and buy collateral ratio reaches its minimum (basis points).
/// @dev exerciseCost maximum cost of force exercising an OTM position immediately out-of-range, decreases exponentially as the tick moves more ranges away (basis points).
struct Parameters {
uint256 maintenanceMarginRatio;
int128 commissionFee;
int128 ITMSpreadFee;
int128 sellCollateralRatio;
int128 buyCollateralRatio;
int128 targetPoolUtilization;
int128 saturatedPoolUtilization;
int128 exerciseCost;
}
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice prefix for the symbol (i.e poUSDC)
string internal constant TICKER_PREFIX = "po";
/// @notice prefix for the name (i.e POPT-V1 USDC LP on ETH/USDC 30bps)
string internal constant NAME_PREFIX = "POPT-V1";
/// @notice Decimals for computation (1 bps (basis point) precision: 0.01%)
/// uint type for composability with unsigned integer based mathematical operations.
uint256 internal constant DECIMALS = 10_000;
/// @notice Decimals for computation (1 bps (basis point) precision: 0.01%)
/// int type for composability with signed integer based mathematical operations.
int128 internal constant DECIMALS_128 = 10_000;
/*//////////////////////////////////////////////////////////////
UNISWAP POOL DATA
//////////////////////////////////////////////////////////////*/
/// @dev address of underlying token0 or token1 from the uniswapPool
/// whether this is token0 or token1 depends on which collateral token is being tracked in this CollateralTracker instance.
address internal s_underlyingToken;
/// @dev Boolean which tracks whether this CollateralTracker has been initialized.
/// As each instance is deployed via proxy clone, initial parameters must only be initalized once via startToken().
/// @notice a token can only be initialized once - which is done by the Panoptic pool.
bool internal s_initialized;
/// @dev stores address of token0 from the underlying uniswap v3 pool.
address internal s_univ3token0;
/// @dev stores address of token1 from the underlying uniswap v3 pool.
address internal s_univ3token1;
/// @dev store whether the current collateral token is token0 of the AMM (true) or token1 (false).
bool internal s_underlyingIsToken0;
/*//////////////////////////////////////////////////////////////
PANOPTIC POOL DATA
//////////////////////////////////////////////////////////////*/
/// @dev The Collateral Tracker Token keeps a reference to the Panoptic Pool using it.
PanopticPool internal s_panopticPool;
/// @dev The Panoptic factory - permissioned operations such as 'updateParameters' are performed by this.
/// @dev When parameters are updated, the factory calls on behalf of the EOA/multisig/DAO that owns it, so we need this to gate access to the function.
PanopticFactory internal factory;
/// @dev Cached amount of assets accounted to be held by the Panoptic Pool - ignores donations, pending fee payouts, and other untracked balance changes.
uint128 internal s_poolAssets;
/// @dev Amount of assets moved from the Panoptic Pool to the AMM.
uint128 internal s_inAMM;
/// @dev The tick spacing in the Uniswap pool.
int24 internal s_tickSpacing;
/// @dev The fee of the Uniswap pool.
uint24 internal s_poolFee;
/*//////////////////////////////////////////////////////////////
RISK PARAMETERS
//////////////////////////////////////////////////////////////*/
/// @dev Amount of ticks that correspond to a move of -s_sellCollateralRatio/DECIMALS.
uint24 internal s_tickDeviation;
/// @notice when creating an option, collect a commission for the Panoptic LPs.
/// In Panoptic, options never expire, commissions are only paid when a new position is minted.
/// We believe that this will eliminate the impact of the commission fee on the user's decision-making process when closing a position.
int128 internal s_commissionFee;
/// @notice additional risk premium charged on intrinsic value of ITM positions,
/// defined in basis points as a multiple of the pool fee / 10_000.
/// @dev The result of the calculation is stored instead of the multiple to save gas during usage.
/// When the fee is set, the multiple is calculated and stored
int128 internal s_ITMSpreadFee;
// base collateral ratios
/// @notice Required collateral ratios for buying, represented as percentage * 10_000.
/// i.e 20% -> 0.2 * 10_000 = 2_000.
int128 internal s_sellCollateralRatio;
/// @notice Required collateral ratios for selling, represented as percentage * 10_000.
/// i.e 10% -> 0.1 * 10_000 = 1_000.
int128 internal s_buyCollateralRatio;
// liquidation parameters
/// @notice basal cost to force exercise a position that is barely far-the-money (out-of-range).
int128 internal s_exerciseCost;
/// @notice prevents minting of new options when collateral < (maintenanceMarginRatio * requiredCollateral).
uint256 internal s_maintenanceMarginRatio;
// Targets a pool utilization (balance between buying and selling)
/// @notice Target pool utilization below which buying+selling is optimal, represented as percentage * 10_000.
/// i.e 50% -> 0.5 * 10_000 = 5_000.
int128 internal s_targetPoolUtilization;
/// @notice Pool utilization above which selling is 100% collateral backed, represented as percentage * 10_000.
/// i.e 90% -> 0.9 * 10_000 = 9_000.
int128 internal s_saturatedPoolUtilization;
/*//////////////////////////////////////////////////////////////
ACCESS CONTROL
//////////////////////////////////////////////////////////////*/
/// @notice Ensure that the Panoptic Factory owner is the caller. Revert if not.
/// @notice the Panoptic Factory is what spins out new Panoptic Pools.
modifier onlyFactoryOwner() {
if (msg.sender != factory.factoryOwner()) revert Errors.NotOwner();
_;
}
/// @notice Ensure that the associated Panoptic pool is the caller. Revert if not.
modifier onlyPanopticPool() {
if (msg.sender != address(s_panopticPool)) revert Errors.NotPanopticPool();
_;
}
/*//////////////////////////////////////////////////////////////
INITIALIZATION & PARAMETER SETTINGS
//////////////////////////////////////////////////////////////*/
/// @notice Initialize a new collateral tracker for a specific token corresponding to the Panoptic Pool being created by the factory that called it.
/// @dev The factory calls this function to start a new collateral tracking system for the incoming token at 'underlyingToken'.
/// The factory will do this for each of the two tokens being tracked. Thus, the collateral tracking system does not track *both* tokens at once.
/// @param underlyingToken the address of the token to track collateral for corresponding to the Panoptic Pool being created by the factory calling this (as 'msg.sender').
/// @param uniswapPool the address of the Uniswap pool that this token is a part of.
/// @param panopticPool the address of the Panoptic Pool being created and linked to this Collateral Tracker.
function startToken(
address underlyingToken,
IUniswapV3Pool uniswapPool,
PanopticPool panopticPool
) external {
// fails if already initialized
if (s_initialized) revert Errors.CollateralTokenAlreadyInitialized();
s_initialized = true;
// cache the token0 and token1 addresses from the uniswap pool
address token0 = uniswapPool.token0();
address token1 = uniswapPool.token1();
// Set the factory to the pool creator
// This function is called within the same transaction as cloning the reference contract
// Ensuring that the deployer/owner sets the correct parameters on genesis
// Calling 'startToken' on the reference itself is not a concern, as it's storage is never accessed
factory = PanopticFactory(msg.sender);
// store the address of the underlying ERC20 token
s_underlyingToken = underlyingToken;
// store the Panoptic pool for this collateral token
s_panopticPool = panopticPool;
// store the tickSpacing of the underlying Uniswap pool
s_tickSpacing = uniswapPool.tickSpacing();
// cache the pool fee in basis points
uint24 _poolFee;
unchecked {
_poolFee = uniswapPool.fee() / 100;
}
s_poolFee = _poolFee;
// Stores the addresses of the underlying tracked tokens.
s_univ3token0 = token0;
s_univ3token1 = token1;
// store whether the current collateral token is token0 (true) or token1 (false; since there's always exactly two tokens it could be)
s_underlyingIsToken0 = underlyingToken == token0;
// Set the Collateral Tracking System Parameters
// Set default base parameters (see 'updateParameters(uint256)' for updating):
s_maintenanceMarginRatio = 13_333; // prevents minting of new options when collateral < 1.3333*required
// commission fee levied when a new option is minted. This fee goes to the Panoptic LP's
s_commissionFee = 10;
// Additional risk premium charged on intrinsic value of ITM positions
// Initial ITM spread fee is double the underlying poolFee.
unchecked {
s_ITMSpreadFee = int24(2 * _poolFee);
}
// amount of ticks that correspond to a move of -s_sellCollateralRatio/DECIMALS
// 1.0001**-2230 = 0.8 = (10000-2000)/10000
s_tickDeviation = 2230;
// basal collateral ratio for selling an option (20% of notional)
s_sellCollateralRatio = 2_000;
// basal collateral ratio for buying an option (10% of notional)
s_buyCollateralRatio = 1_000;
// Target pool utilization where buying+selling is optimal (50%)
s_targetPoolUtilization = 5_000;
// Pool utilization above which selling is 100% collateral backed (90%)
s_saturatedPoolUtilization = 9_000;
// basal cost to force exercise a position that is barely far-the-money (out-of-range).
s_exerciseCost = -1_024;
}
/// @notice update the parameters of the Collateral Tracking System.
/// @dev see struct 'Parameters' for passed in arguments.
/// @param newParameters Struct containing the new parameters to set.
function updateParameters(
CollateralTracker.Parameters calldata newParameters
) external onlyFactoryOwner {
s_maintenanceMarginRatio = newParameters.maintenanceMarginRatio;
s_commissionFee = newParameters.commissionFee;
// precompute the final spread fee - ITMSpreadFee is passed as a multiplier of the pool fee in basis points
unchecked {
s_ITMSpreadFee = int128(
(int256(newParameters.ITMSpreadFee) * int24(s_poolFee)) / DECIMALS_128
);
}
s_sellCollateralRatio = newParameters.sellCollateralRatio;
// calculate amount of ticks required for upwards and downwards moves, used to check if current and mini-median tick
// are out of sync (then apply a 100% collateral requirement)
unchecked {
// taylor expand log(1-sellCollateralRatio)/log(1.0001) around sellCollateralRatio=2000 up to 3rd order
/// since we're dropping the higher order terms, which are all negative, this will underestimate the number of ticks for a 20% move
int128 ratioTick = (newParameters.sellCollateralRatio - 2000);
s_tickDeviation = uint24(
uint128(
2230 +
(12500 * ratioTick) /
10_000 +
(7812 * ratioTick ** 2) /
10_000 ** 2 +
(6510 * ratioTick ** 3) /
10_000 ** 3
)
);
}
s_buyCollateralRatio = newParameters.buyCollateralRatio;
s_targetPoolUtilization = newParameters.targetPoolUtilization;
s_saturatedPoolUtilization = newParameters.saturatedPoolUtilization;
s_exerciseCost = newParameters.exerciseCost;
emit ParametersUpdated(newParameters);
}
/*//////////////////////////////////////////////////////////////
COLLATERAL TOKEN INFORMATION
//////////////////////////////////////////////////////////////*/
/// @notice Get the Panoptic pool data.
/// @dev the Panoptic pool owns this collateral token. This token, in turn, keeps a reference to the Panoptic pool.
/// @return poolAssets cached amount of assets accounted to be held by the Panoptic Pool - ignores donations, pending fee payouts, and other untracked balance changes.
/// @return insideAMM the underlying token amount held in the AMM.
/// @return currentPoolUtilization 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 getPoolData()
external
view
returns (uint256 poolAssets, uint256 insideAMM, int128 currentPoolUtilization)
{
poolAssets = s_poolAssets;
insideAMM = s_inAMM;
currentPoolUtilization = _poolUtilization();
}
/// @notice Returns name of token composed of underlying token symbol and pool data.
/// @return name The name of the token.
function name() external view returns (string memory name) {
// this logic requires multiple external calls and error handling, so we do it in a delegatecall to a library to save bytecode size
return
InteractionHelper.computeName(
s_univ3token0,
s_univ3token1,
s_underlyingIsToken0,
s_poolFee,
NAME_PREFIX
);
}
/// @notice Returns symbol as prefixed symbol of underlying token.
/// @return symbol The symbol of the token.
function symbol() external view returns (string memory symbol) {
// this logic requires multiple external calls and error handling, so we do it in a delegatecall to a library to save bytecode size
return InteractionHelper.computeSymbol(s_underlyingToken, TICKER_PREFIX);
}
/// @notice Returns decimals of underlying token (0 if not present)
/// @return decimals The decimals of the token.
function decimals() external view returns (uint8) {
// this logic requires multiple external calls and error handling, so we do it in a delegatecall to a library to save bytecode size
return InteractionHelper.computeDecimals(s_underlyingToken);
}
/*//////////////////////////////////////////////////////////////
LIMITED TRANSFER FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @dev See {IERC20-transfer}.
/// Requirements:
/// - the caller must have a balance of at least 'amount'.
/// - the msg.sender must not have any position on the panoptic pool
function transfer(
address recipient,
uint256 amount
) public override(ERC20Minimal) returns (bool) {
// make sure the caller does not have any open option positions
// if they do: we don't want them sending panoptic pool shares to others
// since that's like reducing collateral
if (s_panopticPool.numberOfPositions(msg.sender) != 0) revert Errors.PositionCountNotZero();
return ERC20Minimal.transfer(recipient, amount);
}
/// @dev See {IERC20-transferFrom}.
/// Requirements:
/// - the 'from' must have a balance of at least 'amount'.
/// - the caller must have allowance for 'from' of at least 'amount' tokens.
/// - 'from' must not have any open positions on the panoptic pool.
function transferFrom(
address from,
address to,
uint256 amount
) public override(ERC20Minimal) returns (bool) {
// make sure the caller does not have any open option positions
// if they do: we don't want them sending panoptic pool shares to others
// as this would reduce their amount of collateral against the opened positions
if (s_panopticPool.numberOfPositions(from) != 0) revert Errors.PositionCountNotZero();
return ERC20Minimal.transferFrom(from, to, amount);
}
/*//////////////////////////////////////////////////////////////
STANDARD ERC4626 INTERFACE
//////////////////////////////////////////////////////////////*/
/// @notice Get the token contract address of the underlying asset being managed.
/// @return assetTokenAddress The address of the underlying asset.
function asset() external view returns (address assetTokenAddress) {
return s_underlyingToken;
}
/// @notice Get the total amount of assets managed by the CollateralTracker vault.
/// @dev This returns the total tracked assets in the AMM and PanopticPool,
/// @dev - EXCLUDING the amount of collected fees (because they are reserved for short options)
/// @dev - EXCLUDING any donations that have been made to the pool
/// @return totalManagedAssets The total amount of assets managed.
function totalAssets() public view returns (uint256 totalManagedAssets) {
unchecked {
return s_poolAssets + s_inAMM;
}
}
/// @notice Returns the amount of shares that can be minted for the given amount of assets.
/// @param assets The amount of assets to be deposited.
/// @return shares The amount of shares that can be minted.
function convertToShares(uint256 assets) public view returns (uint256 shares) {
uint256 supply = totalSupply;
return supply == 0 ? assets : Math.mulDiv(assets, supply, totalAssets());
}
/// @notice Returns the amount of assets that can be redeemed for the given amount of shares.
/// @param shares The amount of shares to be redeemed.
/// @return assets The amount of assets that can be redeemed.
function convertToAssets(uint256 shares) public view returns (uint256 assets) {
uint256 supply = totalSupply;
return supply == 0 ? shares : Math.mulDiv(shares, totalAssets(), supply);
}
/// @notice returns The maximum deposit amount.
/// @return maxAssets The maximum amount of assets that can be deposited.
function maxDeposit(address) external pure returns (uint256 maxAssets) {
return type(uint104).max;
}
/// @notice Returns shares received for depositing given amount of assets.
/// @param assets The amount of assets to be deposited.
/// @return shares The amount of shares that can be minted.
function previewDeposit(uint256 assets) public view returns (uint256 shares) {
// compute the MEV tax, which is equal to a single payment of the commissionRate BEFORE adding the funds
unchecked {
shares = convertToShares(assets - (assets * (uint128(s_commissionFee))) / DECIMALS);
}
}
/// @notice Deposit underlying tokens (assets) to the Panoptic pool from the LP and mint corresponding amount of shares.
/// There is a maximum asset deposit limit of (2 ** 104) - 1.
/// An MEV tax is levied, which is equal to a single payment of the commissionRate BEFORE adding the funds.
/// @dev Shares are minted and sent to the LP ('receiver').
/// @param assets Amount of assets deposited.
/// @param receiver User to receive the shares.
/// @return shares The amount of Panoptic pool shares that were minted to the recipient.
function deposit(uint256 assets, address receiver) external returns (uint256 shares) {
if (assets > type(uint104).max) revert Errors.DepositTooLarge();
// update the Panoptic pool median with the current tick
s_panopticPool.pokeMedian();
shares = previewDeposit(assets);
// transfer assets (underlying token funds) from the user/the LP to the PanopticPool
// in return for the shares to be minted
SafeTransferLib.safeTransferFrom(
s_underlyingToken,
msg.sender,
address(s_panopticPool),
assets
);
// mint collateral shares of the Panoptic Pool funds (this ERC20 token)
_mint(receiver, shares);
// update tracked asset balance
unchecked {
s_poolAssets += uint128(assets);
}
emit Deposit(msg.sender, receiver, assets, shares);
}
/// @notice Returns the maximum shares received for a deposit.
/// @return maxShares The maximum amount of shares that can be minted.
function maxMint(address) external view returns (uint256 maxShares) {
unchecked {
return
(convertToShares(type(uint104).max) * DECIMALS) /
(DECIMALS + uint128(s_commissionFee));
}
}
/// @notice Returns the amount of assets that would be deposited to mint a given amount of shares.
/// @param shares The amount of shares to be minted.
/// @return assets The amount of assets that would be deposited.
function previewMint(uint256 shares) public view returns (uint256 assets) {
uint256 supply = totalSupply;
// round up depositing assets to avoid protocol loss
// This prevents minting of shares where the assets provided is rounded down to zero
assets = supply == 0 ? shares : Math.mulDivRoundingUp(shares, totalAssets(), supply);
// compute the MEV tax, which is equal to a single payment of the commissionRate BEFORE adding the funds
unchecked {
assets += (assets * uint128(s_commissionFee)) / DECIMALS;
}
}
/// @notice Deposit required amount of assets to receive specified amount of shares.
/// There is a maximum asset deposit limit of (2 ** 104) - 1.
/// An MEV tax is levied, which is equal to a single payment of the commissionRate BEFORE adding the funds.
/// @dev Shares are minted and sent to the LP ('receiver').
/// @param shares Amount of shares to be minted.
/// @param receiver User to receive the shares.
/// @return assets The amount of assets deposited to mint the desired amount of shares.
function mint(uint256 shares, address receiver) external returns (uint256 assets) {
// update the panoptic pool median with the current tick
s_panopticPool.pokeMedian();
assets = previewMint(shares);
if (assets > type(uint104).max) revert Errors.DepositTooLarge();
// transfer assets (underlying token funds) from the user/the LP to the PanopticPool
// in return for the shares to be minted
SafeTransferLib.safeTransferFrom(
s_underlyingToken,
msg.sender,
address(s_panopticPool),
assets
);
// mint collateral shares of the Panoptic Pool funds (this ERC20 token)
_mint(receiver, shares);
// update tracked asset balance
unchecked {
s_poolAssets += uint128(assets);
}
emit Deposit(msg.sender, receiver, assets, shares);
}
/// @notice Returns The maximum amount of assets that can be withdrawn for a given user.
/// If the user has any open positions, the max withdrawable balance is zero.
/// @dev Calculated from the balance of the user; limited by the assets the pool has available.
/// @param owner The address being withdrawn for.
/// @return maxAssets The maximum amount of assets that can be withdrawn.
function maxWithdraw(address owner) public view returns (uint256 maxAssets) {
// We can only use the standard 4626 withdraw function if the user has no open positions
// For the sake of simplicity assets can only be withdrawn through the redeem function
uint256 available = s_poolAssets;
uint256 balance = convertToAssets(balanceOf[owner]);
return
s_panopticPool.numberOfPositions(owner) == 0
? available > balance ? balance : available
: 0;
}
/// @notice Returns the amount of shares that would be burned to withdraw a given amount of assets.
/// @param assets The amount of assets to be withdrawn.
/// @return shares The amount of shares that would be burned.
function previewWithdraw(uint256 assets) public view returns (uint256 shares) {
uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.
return supply == 0 ? assets : Math.mulDivRoundingUp(assets, supply, totalAssets());
}
/// @notice Redeem the amount of shares required to withdraw the specified amount of assets.
/// We can only use this standard 4626 withdraw function if the user has no open positions.
/// @dev Shares are burned and assets are sent to the LP ('receiver').
/// @param assets Amount of assets to be withdrawn.
/// @param receiver User to receive the assets.
/// @param owner User to burn the shares from.
/// @return shares The amount of shares burned to withdraw the desired amount of assets.
function withdraw(
uint256 assets,
address receiver,
address owner
) external returns (uint256 shares) {
if (assets > maxWithdraw(owner)) revert Errors.ExceedsMaximumRedemption();
// update the panoptic pool median with the current tick
s_panopticPool.pokeMedian();
shares = previewWithdraw(assets);
// check/update allowance for approved withdraw
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
// burn collateral shares of the Panoptic Pool funds (this ERC20 token)
_burn(owner, shares);
// update tracked asset balance
unchecked {
s_poolAssets -= uint128(assets);
}
// transfer assets (underlying token funds) from the PanopticPool to the LP
SafeTransferLib.safeTransferFrom(
s_underlyingToken,
address(s_panopticPool),
receiver,
assets
);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
return shares;
}
/// @notice Returns the maximum amount of shares that can be redeemed for a given user.
/// If the user has any open positions, the max redeemable balance is zero.
/// @param owner The redeeming address.
/// @return maxShares The maximum amount of shares that can be redeemed.
function maxRedeem(address owner) public view returns (uint256 maxShares) {
uint256 available = convertToShares(s_poolAssets);
uint256 balance = balanceOf[owner];
return
s_panopticPool.numberOfPositions(owner) == 0
? available > balance ? balance : available
: 0;
}
/// @notice returns the amount of assets resulting from a given amount of shares being redeemed
/// @param shares the amount of shares to be redeemed
/// @return assets the amount of assets resulting from the redemption
function previewRedeem(uint256 shares) public view returns (uint256 assets) {
return convertToAssets(shares);
}
/// @notice Redeem exact shares for underlying assets
/// We can only use this standard 4626 redeem function if the user has no open positions.
/// @param shares Amount of shares to be redeemed
/// @param receiver User to receive the assets
/// @param owner User to burn the shares from
/// @return assets the amount of assets resulting from the redemption
function redeem(
uint256 shares,
address receiver,
address owner
) external returns (uint256 assets) {
// update the panoptic pool median with the current tick
s_panopticPool.pokeMedian();
if (shares > maxRedeem(owner)) revert Errors.ExceedsMaximumRedemption();
// check/update allowance for approved redeem
if (msg.sender != owner) {
uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;
}
assets = previewRedeem(shares);
// burn collateral shares of the Panoptic Pool funds (this ERC20 token)
_burn(owner, shares);
// update tracked asset balance
unchecked {
s_poolAssets -= uint128(assets);
}
// transfer assets (underlying token funds) from the PanopticPool to the LP
SafeTransferLib.safeTransferFrom(
s_underlyingToken,
address(s_panopticPool),
receiver,
assets
);
emit Withdraw(msg.sender, receiver, owner, assets, shares);
return assets;
}
/*//////////////////////////////////////////////////////////////
ACCOUNTING LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Compute a liquidator's potential bonus during liquidation of an account. The bonus depends on degree of distress (0% bonus at 100% collateral).
/// @param account The account to be liquidated.
/// @param positionBalanceArray The list of all historical positions held by the 'optionOwner', stored as [[tokenId, balance/poolUtilizationAtMint], ...].
/// @param otherTokenData The token data of the other collateral token in the Panoptic Pool (with tokenBalance in right slot and required collateral in the left slot).
/// @param twapTick Tick at which the collateral requirement will be evaluated at(Uniswap TWAP tick at time of call).
/// @param sqrtPriceX96 The sqrt price to 96 bit precision.
/// @param premium The premium of the open positions.
/// @return bonusAmounts LeftRight encoding for the bonus paid in each token in the Panoptic Pool to the liquidator.
/// @return tokenData LeftRight encoding with tokenbalance, ie assets, (in the right slot) and amount required in collateral (left slot).
function computeBonus(
address account,
uint256[2][] memory positionBalanceArray,
uint256 otherTokenData,
int24 twapTick,
uint160 sqrtPriceX96,
int128 premium
) external view returns (int256 bonusAmounts, uint256 tokenData) {
// Check status for each token, returns tokenData variable that contains userBalance (right Slot) and
// tokens required (left slot) for the account to be healthy (have enough collateral/margin)
tokenData = _getAccountMargin(account, twapTick, positionBalanceArray, premium);
// Need a valid price to compute the bonus
if (sqrtPriceX96 == 0) return (bonusAmounts, tokenData);
// value of the token balance for both tokens 0 and 1:
// otherTokenData is token0, which is provided as an input and used to compute the tokenValue when a nonzero sqrtPriceX96 value is provided
// computes value as "realValue"/sqrtPrice -> token1.balance/sqrtPrice + token0.balance*sqrtPrice
// this avoids squaring sqrtPrice
uint256 token1TotalValue;
uint256 tokenValue;
unchecked {
token1TotalValue = (tokenData.rightSlot() * Constants.FP96) / sqrtPriceX96;
}
unchecked {
tokenValue =
// token1.balance/sqrtPrice + token0.balance*sqrtPrice
token1TotalValue +
Math.mulDiv96(otherTokenData.rightSlot(), sqrtPriceX96);
}
// value of the required collateral
// otherTokenData is token0, which is provided as an input and used to compute the tokenValue when a nonzero sqrtPriceX96 value is provided
// computes value as "realValue"/sqrtPrice -> token1.required/sqrtPrice + token0.required*sqrtPrice
uint256 requiredValue;
unchecked {
requiredValue =
(tokenData.leftSlot() * Constants.FP96) /
sqrtPriceX96 +
Math.mulDiv96(otherTokenData.leftSlot(), sqrtPriceX96);
}
// What fraction of the collateral value is in token1
// computes (token1.balance/sqrtPrice) / (token1.balance/sqrtPrice + token0.balance*sqrtPrice)
uint256 valueRatio1;
unchecked {
valueRatio1 =
(tokenData.rightSlot() * Constants.FP96 * DECIMALS) /
tokenValue /
sqrtPriceX96;
}
// Position must be margin called (token value is less than required collateral)
if (tokenValue >= requiredValue) revert Errors.NotMarginCalled();
int128 bonus0;
int128 bonus1;
unchecked {
bonus0 = int128(
int256(
otherTokenData.leftSlot() < otherTokenData.rightSlot() // If required is less than balance of that specific token (ie. user uses cross-collateralization), then seize all that collateral and use that as the bonus
? ((tokenValue) * (DECIMALS - valueRatio1) * Constants.FP96) / sqrtPriceX96 // else, the bonus is just (requiredValue - tokenValue)
: ((requiredValue - tokenValue) *
(DECIMALS - valueRatio1) *
Constants.FP96) / sqrtPriceX96
)
);
bonus1 = int128(
int256(
tokenData.leftSlot() < tokenData.rightSlot() // If required is less than balance of that specific token (ie. user uses cross-collateralization), then seize all that collateral and use that as the bonus
? Math.mulDiv96((tokenValue) * (valueRatio1), sqrtPriceX96) // else, the bonus is just (requiredValue - tokenValue)
: Math.mulDiv96((requiredValue - tokenValue) * (valueRatio1), sqrtPriceX96)
)
);
// store bonus amounts as actual amounts by dividing by DECIMALS_128
bonusAmounts = bonusAmounts.toRightSlot(bonus0 / DECIMALS_128).toLeftSlot(
bonus1 / DECIMALS_128
);
}
return (bonusAmounts, tokenData);
}
/// @notice Get the cost of exercising an option. Used during a forced exercise.
/// @dev This one computes the cost of calling the forceExercise function on a position:
/// - The forceExercisor will have to *pay* the exercisee because their position will be closed "against their will"
/// - The cost must be larger when the position is close to being in-range, and should be minimal when it is far from being in range. eg. Exercising a (1000, 1050)
/// position will cost more if the price is 999 than if it is 100
/// - The cost is an exponentially decaying function of the distance between the position's strike and the current price
/// - The cost decreases by a factor of 2 for every "position's width"
/// - Note that the cost is the largest among all active legs, not the sum
/// @dev Example exercise costs:
/// - 10% if the position is liquidated when the price is between 950 and 1000, or if it is between 1050 and 1100
/// - 5% if the price is between 900 and 950 or (1100, 1150)
/// - 2.5% if between (850, 900) or (1150, 1200)
/// @param currentTick The current price tick.
/// @param medianTick The median price tick.
/// @param positionId The position to be exercised
/// @param positionBalance The balance in `account` of the position to be exercised
/// @param longAmounts The amount of longs in the position.
/// @return exerciseFees The fees for exercising the option position.
function exerciseCost(
int24 currentTick,
int24 medianTick,
uint256 positionId,
uint128 positionBalance,
int256 longAmounts
) external view returns (int256 exerciseFees) {
// find the leg furthest to the strike price 'currentTick'; this will have the lowest exercise cost
// we don't need the leg information itself, really just "the number of half ranges" from the strike price:
uint256 maxNumRangesFromStrike; // technically "maxNum(Half)RangesFromStrike" but the name is long
int24 _currentTick = currentTick;
int24 _medianTick = medianTick;
unchecked {
for (uint256 leg = 0; leg < TokenId.countLegs(positionId); ++leg) {
// short legs are not counted - exercise is intended to be based on long legs
if (positionId.isLong(leg) == 0) continue;
int24 strike = positionId.strike(leg);
int24 range = (positionId.width(leg) * s_tickSpacing) / 2;
uint256 currNumRangesFromStrike;
if (_currentTick < (strike - range)) {
/**
current strike
tick │
│ ┌─────▼─────┐
────▼──────┴───────────┴─
<- width ->
range=width/2
*/
currNumRangesFromStrike = uint256(
(2 * int256(strike - range - _currentTick)) / range
); // = (strike - range - _currentTick) / (range / 2); the "range/2" are the "half ranges"
} else if (_currentTick > (strike + range)) {
/**
strike current
│ tick
┌───▼───┐ │
──┴───────┴───────▼────
<-->
range
*/
currNumRangesFromStrike = uint256(
(2 * int256(_currentTick - strike - range)) / range
);
}
maxNumRangesFromStrike = currNumRangesFromStrike > maxNumRangesFromStrike
? currNumRangesFromStrike
: maxNumRangesFromStrike;
uint256 tokenType = positionId.tokenType(leg);
uint256 liquidityChunk = PanopticMath.getLiquidityChunk(
positionId,
leg,
positionBalance,
s_tickSpacing
);
(uint256 currentValue0, uint256 currentValue1) = Math.getAmountsForLiquidity(
_currentTick,
liquidityChunk
);
(uint256 medianValue0, uint256 medianValue1) = Math.getAmountsForLiquidity(
_medianTick,
liquidityChunk
);
// compensate user for loss in value if chunk has lost money between current and median tick
// note: the delta for one token will be positive and the other will be negative. This cancels out any moves in their positions
if (
(tokenType == 0 && currentValue1 < medianValue1) ||
(tokenType == 1 && currentValue0 < medianValue0)
)
exerciseFees = exerciseFees.sub(
int256(0)
.toRightSlot(
int128(uint128(medianValue0)) - int128(uint128(currentValue0))
)
.toLeftSlot(
int128(uint128(medianValue1)) - int128(uint128(currentValue1))
)
);
}
// note: we HAVE to start with a negative number as the base exercise cost because when shifting a negative number right by n bits,
// the result is rounded DOWN and NOT toward zero
// this divergence is observed when n (the number of half ranges) is > 10 (ensuring the floor is not zero, but -1 = 1bps at that point)
int256 fee = (s_exerciseCost >> maxNumRangesFromStrike); // exponential decay of fee based on number of half ranges away from the price
// store the exercise fees in the exerciseFees variable
exerciseFees = exerciseFees
.toRightSlot(int128((int256(longAmounts.rightSlot()) * int256(fee)) / DECIMALS_128))
.toLeftSlot(int128((int256(longAmounts.leftSlot()) * int256(fee)) / DECIMALS_128));
}
}
/// @notice Returns the original delegated value to a user at a certain tick based on the available collateral from the exercised user.
/// @dev Only called on collateralTracker0, so we must query balances from collateralTracker1.
/// @param refunder Address of the user the refund is coming from (the force exercisee).
/// @param refundValues Token values to refund at the given tick(atTick) rightSlot = token0 left = token1.
/// @param atTick Tick to convert values at. This can be the current tick or some TWAP/median tick.
/// @param collateralToken1 The address of the collateralTracker for token 1.
/// @return refundAmounts The amount of tokens to refund to the user.
function getRefundAmounts(
address refunder,
int256 refundValues,
int24 atTick,
CollateralTracker collateralToken1
) public view returns (int256 refundAmounts) {
uint160 sqrtPriceX96 = Math.getSqrtRatioAtTick(atTick);
unchecked {
// if the refunder lacks sufficient token0 to pay back the refundee, have them pay back the equivalent value in token1
// note: it is possible for refunds to be negative when the exercise fee is higher than the delegated amounts. This is expected behavior
int256 balanceShortage = refundValues.rightSlot() -
int256(convertToAssets(balanceOf[refunder]));
if (balanceShortage > 0) {
return
int256(0)
.toRightSlot(int128(refundValues.rightSlot() - balanceShortage))
.toLeftSlot(
int128(
int256(
PanopticMath.convert0to1(uint256(balanceShortage), sqrtPriceX96)
) + refundValues.leftSlot()
)
);
}
balanceShortage =
refundValues.leftSlot() -
int256(collateralToken1.convertToAssets(collateralToken1.balanceOf(refunder)));
if (balanceShortage > 0) {
return
int256(0)
.toLeftSlot(int128(refundValues.leftSlot() - balanceShortage))
.toRightSlot(
int128(
int256(
PanopticMath.convert1to0(uint256(balanceShortage), sqrtPriceX96)
) + refundValues.rightSlot()
)
);
}
}
// otherwise, we can just refund the original amounts requested with no problems
return refundValues;
}
/// @notice Get the pool utilization; it is a measure of the ratio of assets in the AMM vs the total assets managed by the pool.
// With total assets being the current Panoptic pool balance + the amount in the AMM.
/// @dev compute: inAMM/totalAssets().
/// @dev 1bps precision controlled by DECIMALS.
/// @return poolUtilization the pool utilization as a fraction.
function _poolUtilization() internal view returns (int128 poolUtilization) {