-
Notifications
You must be signed in to change notification settings - Fork 1
/
CollateralTracker.sol
1656 lines (1445 loc) · 80.7 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 {PanopticPool} from "./PanopticPool.sol";
// Inherited implementations
import {ERC20Minimal} from "@tokens/ERC20Minimal.sol";
import {Multicall} from "@base/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 {LeftRightUnsigned, LeftRightSigned} 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 {
using Math for uint256;
/*//////////////////////////////////////////////////////////////
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
);
/*//////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @notice Prefix for the token symbol (i.e. poUSDC).
string internal constant TICKER_PREFIX = "po";
/// @notice Prefix for the token 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%).
/// @dev 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%).
/// @dev int type for composability with signed integer based mathematical operations.
int128 internal constant DECIMALS_128 = 10_000;
/*//////////////////////////////////////////////////////////////
UNISWAP POOL DATA
//////////////////////////////////////////////////////////////*/
/// @notice The address of underlying token0 or token1 from the Uniswap Pool.
/// @dev Whether this is token0 or token1 depends on which collateral token is being tracked in this CollateralTracker instance.
address internal s_underlyingToken;
/// @notice Boolean which tracks whether this CollateralTracker has been initialized.
/// @dev As each instance is deployed via proxy clone, initial parameters must only be initalized once via startToken().
bool internal s_initialized;
/// @notice Stores address of token0 from the underlying Uniswap V3 pool.
address internal s_univ3token0;
/// @notice Stores address of token1 from the underlying Uniswap V3 pool.
address internal s_univ3token1;
/// @notice Store whether the current collateral token is token0 of the AMM (true) or token1 (false).
bool internal s_underlyingIsToken0;
/*//////////////////////////////////////////////////////////////
PANOPTIC POOL DATA
//////////////////////////////////////////////////////////////*/
/// @notice The Collateral Tracker keeps a reference to the Panoptic Pool using it.
PanopticPool internal s_panopticPool;
/// @notice 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;
/// @notice Amount of assets moved from the Panoptic Pool to the AMM.
uint128 internal s_inAMM;
/// @notice Additional risk premium charged on intrinsic value of ITM positions,
/// defined in hundredths of basis points.
/// @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.
uint128 internal s_ITMSpreadFee;
/// @notice The fee of the Uniswap pool in hundredths of basis points.
uint24 internal s_poolFee;
/*//////////////////////////////////////////////////////////////
RISK PARAMETERS
//////////////////////////////////////////////////////////////*/
/// @notice The commission fee, in basis points, collected from PLPs at option mint.
/// @dev In Panoptic, options never expire, commissions are only paid when a new position is minted.
/// @dev We believe that this will eliminate the impact of the commission fee on the user's decision-making process when closing a position.
uint256 immutable COMMISSION_FEE;
// base collateral ratios
/// @notice Required collateral ratios for buying, represented as percentage * 10_000.
/// @dev i.e 20% -> 0.2 * 10_000 = 2_000.
uint256 immutable SELLER_COLLATERAL_RATIO;
/// @notice Required collateral ratios for selling, represented as percentage * 10_000.
/// @dev i.e 10% -> 0.1 * 10_000 = 1_000.
uint256 immutable BUYER_COLLATERAL_RATIO;
// miscellaneous parameters
/// @notice Basal cost (in bps of notional) to force exercise a position that is barely far-the-money (out-of-range).
int256 immutable FORCE_EXERCISE_COST;
// Targets a pool utilization (balance between buying and selling)
/// @notice Target pool utilization below which buying+selling is optimal, represented as percentage * 10_000.
/// @dev i.e 50% -> 0.5 * 10_000 = 5_000.
uint256 immutable TARGET_POOL_UTIL;
/// @notice Pool utilization above which selling is 100% collateral backed, represented as percentage * 10_000.
/// @dev i.e 90% -> 0.9 * 10_000 = 9_000.
uint256 immutable SATURATED_POOL_UTIL;
/// @notice Multiplier, in basis points, to the pool fee that is charged on the intrinsic value of ITM positions.
/// @dev e.g. ITM_SPREAD_MULTIPLIER = 20_000, s_ITMSpreadFee = 2 * s_poolFee.
uint256 immutable ITM_SPREAD_MULTIPLIER;
/*//////////////////////////////////////////////////////////////
ACCESS CONTROL
//////////////////////////////////////////////////////////////*/
/// @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 Set immutable parameters for the Collateral Tracker.
/// @param _commissionFee The commission fee, in basis points, collected from PLPs at option mint.
/// @param _sellerCollateralRatio Required collateral ratios for buying, represented as percentage * 10_000.
/// @param _buyerCollateralRatio Required collateral ratios for selling, represented as percentage * 10_000.
/// @param _forceExerciseCost Basal cost (in bps of notional) to force exercise a position that is barely far-the-money (out-of-range).
/// @param _targetPoolUtilization Target pool utilization below which buying+selling is optimal, represented as percentage * 10_000.
/// @param _saturatedPoolUtilization Pool utilization above which selling is 100% collateral backed, represented as percentage * 10_000.
/// @param _ITMSpreadMultiplier Multiplier, in basis points, to the pool fee that is charged on the intrinsic value of ITM positions.
constructor(
uint256 _commissionFee,
uint256 _sellerCollateralRatio,
uint256 _buyerCollateralRatio,
int256 _forceExerciseCost,
uint256 _targetPoolUtilization,
uint256 _saturatedPoolUtilization,
uint256 _ITMSpreadMultiplier
) {
COMMISSION_FEE = _commissionFee;
SELLER_COLLATERAL_RATIO = _sellerCollateralRatio;
BUYER_COLLATERAL_RATIO = _buyerCollateralRatio;
FORCE_EXERCISE_COST = _forceExerciseCost;
TARGET_POOL_UTIL = _targetPoolUtilization;
SATURATED_POOL_UTIL = _saturatedPoolUtilization;
ITM_SPREAD_MULTIPLIER = _ITMSpreadMultiplier;
}
/// @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'.
/// @dev 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 underlyingIsToken0 whether this collateral tracker is for token0 (true) or token1 (false)
/// @param token0 token 0 of the Uniswap pool
/// @param token1 token 1 of the Uniswap pool
/// @param fee the fee of the Uniswap pool
/// @param panopticPool the address of the Panoptic Pool being created and linked to this Collateral Tracker
function startToken(
bool underlyingIsToken0,
address token0,
address token1,
uint24 fee,
PanopticPool panopticPool
) external {
// fails if already initialized
if (s_initialized) revert Errors.CollateralTokenAlreadyInitialized();
s_initialized = true;
// these virtual shares function as a multiplier for the capital requirement to manipulate the pool price
// e.g if the virtual shares are 10**6, then the capital requirement to manipulate the price to 10**12 is 10**18
totalSupply = 10 ** 6;
// set total assets to 1
// the initial share price is defined by 1/virtualShares
s_poolAssets = 1;
// store the address of the underlying ERC20 token
s_underlyingToken = underlyingIsToken0 ? token0 : token1;
// store the Panoptic pool for this collateral token
s_panopticPool = panopticPool;
// cache the pool fee in hundredths of basis points
s_poolFee = fee;
// 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 = underlyingIsToken0;
// Additional risk premium charged on intrinsic value of ITM positions
unchecked {
s_ITMSpreadFee = uint128((ITM_SPREAD_MULTIPLIER * fee) / DECIMALS);
}
}
/*//////////////////////////////////////////////////////////////
COLLATERAL TOKEN INFORMATION
//////////////////////////////////////////////////////////////*/
/// @notice Get information about the utilization of this collateral vault.
/// @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, int256 currentPoolUtilization)
{
poolAssets = s_poolAssets;
insideAMM = s_inAMM;
currentPoolUtilization = _poolUtilization();
}
/// @notice Returns name of token composed of underlying token symbol and pool data.
/// @return The name of the token
function name() external view returns (string memory) {
// 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 The symbol of the token
function symbol() external view returns (string memory) {
// 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 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
// as this would reduce their amount of collateral against the opened positions
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) {
return Math.mulDiv(assets, totalSupply, 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) {
return Math.mulDiv(shares, totalAssets(), totalSupply);
}
/// @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 on the FINAL (post mev-tax) assets paid
unchecked {
shares = Math.mulDiv(
assets * (DECIMALS - COMMISSION_FEE),
totalSupply,
totalAssets() * DECIMALS
);
}
}
/// @notice Deposit underlying tokens (assets) to the Panoptic pool from the LP and mint corresponding amount of shares.
/// @dev There is a maximum asset deposit limit of (2 ** 104) - 1.
/// @dev 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();
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 - COMMISSION_FEE)) / DECIMALS;
}
}
/// @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) {
// round up depositing assets to avoid protocol loss
// This prevents minting of shares where the assets provided is rounded down to zero
// compute the MEV tax, which is equal to a single payment of the commissionRate on the FINAL (post mev-tax) assets paid
// finalAssets - convertedAssets = commissionRate * finalAssets
// finalAssets - commissionRate * finalAssets = convertedAssets
// finalAssets * (1 - commissionRate) = convertedAssets
// finalAssets = convertedAssets / (1 - commissionRate)
assets = Math.mulDivRoundingUp(
shares * DECIMALS,
totalAssets(),
totalSupply * (DECIMALS - COMMISSION_FEE)
);
}
/// @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) {
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 ? Math.min(available, balance) : 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 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();
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 Redeem the amount of shares required to withdraw the specified amount of assets.
/// @dev Reverts if the account is not solvent with the given `positionIdList`.
/// @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
/// @param positionIdList The list of all option positions held by `owner`
/// @return shares The amount of shares burned to withdraw the desired amount of assets
function withdraw(
uint256 assets,
address receiver,
address owner,
TokenId[] calldata positionIdList
) external returns (uint256 shares) {
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);
}
// reverts if account is not solvent/eligible to withdraw
s_panopticPool.validateCollateralWithdrawable(owner, positionIdList);
// 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 ? Math.min(available, balance) : 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) {
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 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 oracleTick The price oracle 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 oracleTick,
TokenId positionId,
uint128 positionBalance,
LeftRightSigned longAmounts
) external view returns (LeftRightSigned 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 = 1; // technically "maxNum(Half)RangesFromStrike" but the name is long
unchecked {
for (uint256 leg = 0; leg < positionId.countLegs(); ++leg) {
// short legs are not counted - exercise is intended to be based on long legs
if (positionId.isLong(leg) == 0) continue;
{
int24 range = int24(
int256(
Math.unsafeDivRoundingUp(
uint24(positionId.width(leg) * positionId.tickSpacing()),
2
)
)
);
maxNumRangesFromStrike = Math.max(
maxNumRangesFromStrike,
uint256(Math.abs(currentTick - positionId.strike(leg)) / range)
);
}
uint256 currentValue0;
uint256 currentValue1;
uint256 oracleValue0;
uint256 oracleValue1;
{
LiquidityChunk liquidityChunk = PanopticMath.getLiquidityChunk(
positionId,
leg,
positionBalance
);
(currentValue0, currentValue1) = Math.getAmountsForLiquidity(
currentTick,
liquidityChunk
);
(oracleValue0, oracleValue1) = Math.getAmountsForLiquidity(
oracleTick,
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
exerciseFees = exerciseFees.sub(
LeftRightSigned
.wrap(0)
.toRightSlot(int128(uint128(oracleValue0)) - int128(uint128(currentValue0)))
.toLeftSlot(int128(uint128(oracleValue1)) - 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)
// subtract 1 from max half ranges from strike so fee starts at FORCE_EXERCISE_COST when moving OTM
int256 fee = (FORCE_EXERCISE_COST >> (maxNumRangesFromStrike - 1)); // 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((longAmounts.rightSlot() * fee) / DECIMALS_128))
.toLeftSlot(int128((longAmounts.leftSlot() * fee) / DECIMALS_128));
}
}
/// @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().
/// @return poolUtilization The pool utilization in basis points
function _poolUtilization() internal view returns (int256 poolUtilization) {
unchecked {
return int256((s_inAMM * DECIMALS) / totalAssets());
}
}
/// @notice Get the (sell) collateral ratio that is paid when a short option is minted at a specific pool utilization.
/// @dev This is computed at the time the position is minted.
/// @param utilization The fraction of totalAssets() that belongs to the Uniswap Pool
/// @return sellCollateralRatio The sell collateral ratio at `utilization`
function _sellCollateralRatio(
int256 utilization
) internal view returns (uint256 sellCollateralRatio) {
// the sell ratio is on a straight line defined between two points (x0,y0) and (x1,y1):
// (x0,y0) = (targetPoolUtilization,min_sell_ratio) and
// (x1,y1) = (saturatedPoolUtilization,max_sell_ratio)
// the line's formula: y = a * (x - x0) + y0, where a = (y1 - y0) / (x1 - x0)
/**
SELL
COLLATERAL
RATIO
^
| max ratio = 100%
100% - | _------
| _-¯
| _-¯
20% - |---------¯
| . . .
+---------+-------+-+---> POOL_
50% 90% 100% UTILIZATION
*/
uint256 min_sell_ratio = SELLER_COLLATERAL_RATIO;
/// if utilization is less than zero, this is the calculation for a strangle, which gets 2x the capital efficiency at low pool utilization
/// at 0% utilization, strangle legs do not compound efficiency
if (utilization < 0) {
unchecked {
min_sell_ratio /= 2;
utilization = -utilization;
}
}
// return the basal sell ratio if pool utilization is lower than target
if (uint256(utilization) < TARGET_POOL_UTIL) {
return min_sell_ratio;
}
// return 100% collateral ratio if utilization is above saturated pool utilization
// this means all new positions are fully collateralized, which reduces risks of insolvency at high pool utilization
if (uint256(utilization) > SATURATED_POOL_UTIL) {
return DECIMALS;
}
unchecked {
return
min_sell_ratio +
((DECIMALS - min_sell_ratio) * (uint256(utilization) - TARGET_POOL_UTIL)) /
(SATURATED_POOL_UTIL - TARGET_POOL_UTIL);
}
}
/// @notice Get the (buy) collateral ratio that is paid when a long option is minted at a specific pool utilization.
/// @dev This is computed at the time the position is minted.
/// @param utilization The fraction of totalBalance() that belongs to the Uniswap Pool
/// @return buyCollateralRatio The buy collateral ratio at `utilization`
function _buyCollateralRatio(
uint256 utilization
) internal view returns (uint256 buyCollateralRatio) {
// linear from BUY to BUY/2 between 50% and 90%
// the buy ratio is on a straight line defined between two points (x0,y0) and (x1,y1):
// (x0,y0) = (targetPoolUtilization,buyCollateralRatio) and
// (x1,y1) = (saturatedPoolUtilization,buyCollateralRatio / 2)
// note that y1<y0 so the slope is negative:
// aka the buy ratio starts high and drops to a lower value with increased utilization; the sell ratio does the opposite (slope is positive)
// the line's formula: y = a * (x - x0) + y0, where a = (y1 - y0) / (x1 - x0)
// but since a<0, we rewrite as:
// y = a' * (x0 - x) + y0, where a' = (y0 - y1) / (x1 - x0)
// HOWEVER, if the utilization is larger than 10_000, then default to 100% buying power requirement.
// this denotes a situation where the median is too far away from the current price, so we need to require fully collateralized positions for safety
/**
BUY
COLLATERAL
RATIO
^
| buy_ratio = 10%
10% - |----------__ min_ratio = 5%
5% - | . . . . . ¯¯¯--______
| . . .
+---------+-------+-+---> POOL_
50% 90% 100% UTILIZATION
*/
// return the basal buy ratio if pool utilization is lower than target
if (utilization < TARGET_POOL_UTIL) {
return BUYER_COLLATERAL_RATIO;
}
// return the basal ratio divided by 2 if pool utilization is above saturated pool utilization
/// this is incentivized buying, which returns funds to the panoptic pool
if (utilization > SATURATED_POOL_UTIL) {
unchecked {
return BUYER_COLLATERAL_RATIO / 2;
}
}
unchecked {
return
(BUYER_COLLATERAL_RATIO +
(BUYER_COLLATERAL_RATIO * (SATURATED_POOL_UTIL - utilization)) /
(SATURATED_POOL_UTIL - TARGET_POOL_UTIL)) / 2; // do the division by 2 at the end after all addition and multiplication; b/c y1 = buyCollateralRatio / 2
}
}
/*////////////////////////////////////////////////////////////////////
LIFECYCLE OF A COLLATERAL TOKEN AND DELEGATE/REVOKE LOGIC
////////////////////////////////////////////////////////////////////*/
/// @notice Delegate and transfer shares corresponding to the incoming assets 'from' delegator 'to' delegatee.
/// @dev This is controlled by the Panoptic Pool - not individual users.
/// @param delegator The delegator to send shares from - the sender of the shares
/// @param delegatee The delegatee to send shares to - the recipient of the shares
/// @param assets The assets to which the shares delegated correspond
function delegate(
address delegator,
address delegatee,
uint256 assets
) external onlyPanopticPool {
/*
┌────────┐
│Panoptic│
│Pool │
└────┬───┘
│(1) convert 'assets' to shares (this ERC20 contract)
┌─────────┐ │ ┌─────────┐
│delegator├──▼──►delegatee│
└─────────┘(2) └─────────┘
move shares
from delegator
to delegatee
*/
uint256 shares = convertToShares(assets);
// transfer shares from the delegator to the delegatee
_transferFrom(delegator, delegatee, shares);
}
/// @notice Delegate and transfer shares corresponding to the incoming assets from the protocol to `delegatee`.
/// @dev This is controlled by the Panoptic Pool - not individual users.
/// @dev Mints ghost shares so a position can be settled - the total supply is not affected.
/// @param delegatee The delegatee to send shares to - the recipient of the shares
/// @param assets The assets to which the shares delegated correspond
function delegate(address delegatee, uint256 assets) external onlyPanopticPool {
balanceOf[delegatee] += convertToShares(assets);
}
/// @notice Refunds delegated tokens back to the protocol.
/// @dev Assumes that `delegatee` has enough money to pay for the refund.
/// @dev Burns ghost shares after a position has been settled - the total supply is not affected.
/// @param delegatee The account refunding tokens to 'delegatee'
/// @param assets The amount of assets to which the shares to refund to the protocol correspond
function refund(address delegatee, uint256 assets) external onlyPanopticPool {
balanceOf[delegatee] -= convertToShares(assets);
}
/// @notice Revoke previously delegated shares. The opposite of 'delegate'.
/// @param delegator The delegator to send shares *to* (because we are revoking - opposite when we delegate)
/// @param delegatee The delegatee to send shares *from* (because we are revoking - opposite when we delegate)
/// @param assets The assets to which the shares revoked correspond
function revoke(
address delegator,
address delegatee,
uint256 assets
) external onlyPanopticPool {
/**
┌────────┐
│Panoptic│
│Pool │
└────┬───┘
│(1) convert 'assets' to shares (this ERC20 contract)
┌─────────┐ │ ┌─────────┐
│delegator◄──▼─┤delegatee│
└─────────┘(2) └─────────┘
moves shares
from delegatee
back to delegator
*/
uint256 shares = convertToShares(assets);
// get the delegateeBalance and compare later against requestedAmount
uint256 delegateeBalance = balanceOf[delegatee];
// if requested amount is larger than user balance, transfer shares back,
// then issue new shares
if (shares > delegateeBalance) {
// transfer delegatee balance to delegator
_transferFrom(delegatee, delegator, delegateeBalance);
// this is paying out protocol loss, so correct for that in the amount of shares to be minted
// X: total assets in vault
// Y: total supply of shares
// Z: desired value (assets) of shares to be minted
// N: total shares corresponding to Z
// T: transferred shares from liquidatee which are a component of N but do not contribute toward protocol loss
// Z = N * X / (Y + N - T)
// Z * (Y + N - T) = N * X
// ZY + ZN - ZT = NX
// ZY - ZT = N(X - Z)
// N = (ZY - ZT) / (X - Z)
// N = Z(Y - T) / (X - Z)
// subtract delegatee balance from N since it was already transferred to the delegator
_mint(
delegator,
Math.mulDiv(
assets,
totalSupply - delegateeBalance,
uint256(Math.max(1, int256(totalAssets()) - int256(assets)))
) - delegateeBalance
);
}
// if requested amount < delegatee balance, then just transfer shares back
else {
_transferFrom(delegatee, delegator, shares);
}
}
/// @notice Refunds delegated tokens to 'refunder' from 'refundee', similar to 'revoke'.
/// @dev Assumes that the refunder has enough money to pay for the refund.
/// @dev Can handle negative refund amounts that go from refundee to refunder in the case of high exercise fees.
/// @param refunder The account refunding tokens to 'refundee'
/// @param refundee The account being refunded to
/// @param assets The amount of assets to refund. Positive means a transfer from refunder to refundee, vice versa for negative
function refund(address refunder, address refundee, int256 assets) external onlyPanopticPool {
if (assets > 0) {
_transferFrom(refunder, refundee, convertToShares(uint256(assets)));
} else {
unchecked {
_transferFrom(refundee, refunder, convertToShares(uint256(-assets)));
}