/
DopexV2OptionPools.sol
822 lines (714 loc) · 28 KB
/
DopexV2OptionPools.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
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.0 <0.9.0;
import {IDopexV2PositionManager} from "./interfaces/IDopexV2PositionManager.sol";
import {IOptionPricing} from "./pricing/IOptionPricing.sol";
import {IHandler} from "./interfaces/IHandler.sol";
import {IDopexFee} from "./interfaces/IDopexFee.sol";
import {ISwapper} from "./interfaces/ISwapper.sol";
import {ITokenURIFetcher} from "./interfaces/ITokenURIFetcher.sol";
import {ERC721} from "openzeppelin-contracts/contracts/token/ERC721/ERC721.sol";
import {ERC20} from "openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "openzeppelin-contracts/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "openzeppelin-contracts/contracts/security/ReentrancyGuard.sol";
import {Multicall} from "openzeppelin-contracts/contracts/utils/Multicall.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {LiquidityAmounts} from "v3-periphery/libraries/LiquidityAmounts.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {FullMath} from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
/**
* @title DopexV2OptionPools
* @author 0xcarrot
* @dev Allow traders to buy CALL and PUT options using CLAMM liquidity, which can be
* exercised at any time ITM.
*/
contract DopexV2OptionPools is
Ownable,
ReentrancyGuard,
Multicall,
ERC721("Dopex V2 Options Pools", "DV2OP")
{
using TickMath for int24;
struct OptionData {
uint256 opTickArrayLen;
int24 tickLower;
int24 tickUpper;
uint256 expiry;
bool isCall;
}
struct OptionTicks {
IHandler _handler;
IUniswapV3Pool pool;
int24 tickLower;
int24 tickUpper;
uint256 liquidityToUse;
}
struct OptionRollParams {
OptionTicks[] optionTicks;
int24 tickLower;
int24 tickUpper;
uint256 ttl;
bool isCall;
uint256 maxFeeAllowed;
}
struct ExerciseOptionRollParams {
uint256 optionId;
ISwapper swapper;
bytes swapData;
uint256[] liquidityToExercise;
}
struct SettleOptionRollParams {
uint256 optionId;
ISwapper swapper;
bytes swapData;
uint256[] liquidityToSettle;
}
struct PositionSplitterParams {
uint256 optionId;
address to;
uint256[] liquidityToSplit;
}
// events
event LogMintOptionRoll(
address user,
uint256 tokenId,
bool isCall,
uint256 premiumAmount,
uint256 totalAsssetWithdrawn
);
event LogExerciseOptionRoll(
address user,
uint256 tokenId,
uint256 totalProfit
);
event LogSettleOptionRoll(address user, uint256 tokenId);
event LogSplitOptionRoll(
address user,
uint256 tokenId,
uint256 newTokenId,
address to
);
// errors
error DopexV2OptionPools__IVNotSet();
error DopexV2OptionPools__NotValidStrikeTick();
error DopexV2OptionPools__PoolNotApproved();
error DopexV2OptionPools__MaxFeeAllowanceExceeded();
error DopexV2OptionPools__NotOwnerOrDelegator();
error DopexV2OptionPools__ArrayLenMismatch();
error DopexV2OptionPools__OptionExpired();
error DopexV2OptionPools__OptionNotExpired();
error DopexV2OptionPools__NotEnoughAfterSwap();
error DopexV2OptionPools__NotApprovedSettler();
IDopexFee public dpFee;
IOptionPricing public optionPricing;
IDopexV2PositionManager public positionManager;
IUniswapV3Pool public primePool;
address public callAsset;
address public putAsset;
address public feeTo;
address public tokenURIFetcher;
mapping(uint256 => uint256) public ttlToVEID;
mapping(uint256 => OptionData) public opData;
mapping(uint256 => OptionTicks[]) public opTickMap;
mapping(address => mapping(address => bool)) public exerciseDelegator;
mapping(address => bool) public approvedPools;
mapping(address => bool) public settlers;
uint256 public optionIds = 1;
constructor(
address _pm,
address _optionPricing,
address _dpFee,
address _callAsset,
address _putAsset,
address _primePool
) {
positionManager = IDopexV2PositionManager(_pm);
callAsset = _callAsset;
putAsset = _putAsset;
dpFee = IDopexFee(_dpFee);
optionPricing = IOptionPricing(_optionPricing);
primePool = IUniswapV3Pool(_primePool);
}
/**
* @notice Provides the tokenURI for each token
* @param id The token Id.
* @return The tokenURI string data
*/
function tokenURI(uint256 id) public view override returns (string memory) {
return ITokenURIFetcher(tokenURIFetcher).onFetchTokenURIData(id);
}
/**
* @notice Mints an option for the given strike and expiry.
* @param _params The option roll parameters.
*/
function mintOptionRoll(
OptionRollParams calldata _params
) external nonReentrant {
optionIds += 1;
uint256[] memory amountsPerOptionTicks = new uint256[](
_params.optionTicks.length
);
uint256 totalAssetWithdrawn;
bool isAmount0;
address assetToUse = _params.isCall ? callAsset : putAsset;
if (ttlToVEID[_params.ttl] == 0) revert DopexV2OptionPools__IVNotSet();
for (uint256 i; i < _params.optionTicks.length; i++) {
if (
_params.isCall
? _params.tickUpper != _params.optionTicks[i].tickUpper
: _params.tickLower != _params.optionTicks[i].tickLower
) revert DopexV2OptionPools__NotValidStrikeTick();
opTickMap[optionIds].push(
OptionTicks({
_handler: _params.optionTicks[i]._handler,
pool: _params.optionTicks[i].pool,
tickLower: _params.optionTicks[i].tickLower,
tickUpper: _params.optionTicks[i].tickUpper,
liquidityToUse: _params.optionTicks[i].liquidityToUse
})
);
if (!approvedPools[address(_params.optionTicks[i].pool)])
revert DopexV2OptionPools__PoolNotApproved();
bytes memory usePositionData = abi.encode(
_params.optionTicks[i].pool,
_params.optionTicks[i].tickLower,
_params.optionTicks[i].tickUpper,
_params.optionTicks[i].liquidityToUse
);
(, uint256[] memory amounts, ) = positionManager.usePosition(
_params.optionTicks[i]._handler,
usePositionData
);
if (_params.optionTicks[i].pool.token0() == assetToUse) {
require(amounts[0] > 0 && amounts[1] == 0);
amountsPerOptionTicks[i] = (amounts[0]);
totalAssetWithdrawn += amounts[0];
isAmount0 = true;
} else {
require(amounts[1] > 0 && amounts[0] == 0);
amountsPerOptionTicks[i] = (amounts[1]);
totalAssetWithdrawn += amounts[1];
isAmount0 = false;
}
}
uint256 strike = getPricePerCallAssetViaTick(
primePool,
_params.isCall ? _params.tickUpper : _params.tickLower
);
uint256 premiumAmount = _getPremiumAmount(
_params.isCall ? false : true, // isPut
block.timestamp + _params.ttl, // expiry
strike, // Strike
getCurrentPricePerCallAsset(primePool), // Current price
ttlToVEID[_params.ttl], // IV, strike and expiry param is 0 since we are using flat volatility
_params.isCall
? totalAssetWithdrawn
: (totalAssetWithdrawn * (10 ** ERC20(putAsset).decimals())) /
strike
);
uint256 protocolFees;
if (feeTo != address(0)) {
protocolFees = dpFee.onFeeReqReceive();
ERC20(assetToUse).transferFrom(msg.sender, feeTo, protocolFees);
}
if (premiumAmount + protocolFees > _params.maxFeeAllowed)
revert DopexV2OptionPools__MaxFeeAllowanceExceeded();
ERC20(assetToUse).transferFrom(
msg.sender,
address(this),
premiumAmount
);
ERC20(assetToUse).approve(address(positionManager), premiumAmount);
uint128 l = LiquidityAmounts.getLiquidityForAmounts(
_getCurrentSqrtPriceX96(primePool),
_params.tickLower.getSqrtRatioAtTick(),
_params.tickUpper.getSqrtRatioAtTick(),
isAmount0 ? premiumAmount : 0,
isAmount0 ? 0 : premiumAmount
);
for (uint i; i < _params.optionTicks.length; i++) {
uint256 amountLToDonate = (amountsPerOptionTicks[i] * l) /
totalAssetWithdrawn;
bytes memory donatePositionData = abi.encode(
_params.optionTicks[i].pool,
_params.optionTicks[i].tickLower,
_params.optionTicks[i].tickUpper,
amountLToDonate
);
positionManager.donateToPosition(
_params.optionTicks[i]._handler,
donatePositionData
);
}
opData[optionIds] = OptionData({
opTickArrayLen: _params.optionTicks.length,
tickLower: _params.tickLower,
tickUpper: _params.tickUpper,
expiry: block.timestamp + _params.ttl,
isCall: _params.isCall
});
_safeMint(msg.sender, optionIds);
emit LogMintOptionRoll(
msg.sender,
optionIds,
_params.isCall,
premiumAmount,
totalAssetWithdrawn
);
}
/**
* @notice Exercises the given option roll.
* @param _params The exercise option roll parameters.
*/
function exerciseOptionRoll(
ExerciseOptionRollParams calldata _params
) external nonReentrant {
if (
ownerOf(_params.optionId) != msg.sender &&
exerciseDelegator[ownerOf(_params.optionId)][msg.sender] == false
) revert DopexV2OptionPools__NotOwnerOrDelegator();
OptionData memory oData = opData[_params.optionId];
if (oData.opTickArrayLen != _params.liquidityToExercise.length)
revert DopexV2OptionPools__ArrayLenMismatch();
if (oData.expiry < block.timestamp)
revert DopexV2OptionPools__OptionExpired();
uint256 totalProfit;
for (uint256 i; i < oData.opTickArrayLen; i++) {
OptionTicks storage opTick = opTickMap[_params.optionId][i];
bool isAmount0 = oData.isCall
? primePool.token0() == callAsset
: primePool.token0() == putAsset;
uint256 amountToSwap = isAmount0
? LiquidityAmounts.getAmount0ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(_params.liquidityToExercise[i])
)
: LiquidityAmounts.getAmount1ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(_params.liquidityToExercise[i])
);
uint256 prevBalance = ERC20(oData.isCall ? putAsset : callAsset)
.balanceOf(address(this));
ERC20(oData.isCall ? callAsset : putAsset).transfer(
address(_params.swapper),
amountToSwap
);
_params.swapper.onSwapReceived(
oData.isCall ? callAsset : putAsset,
oData.isCall ? putAsset : callAsset,
amountToSwap,
_params.swapData
);
uint256 amountReq = isAmount0
? LiquidityAmounts.getAmount1ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(_params.liquidityToExercise[i])
)
: LiquidityAmounts.getAmount0ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(_params.liquidityToExercise[i])
);
uint256 currentBalance = ERC20(oData.isCall ? putAsset : callAsset)
.balanceOf(address(this));
if (currentBalance < prevBalance + amountReq)
revert DopexV2OptionPools__NotEnoughAfterSwap();
ERC20(oData.isCall ? putAsset : callAsset).approve(
address(positionManager),
amountReq
);
bytes memory unusePositionData = abi.encode(
opTick.pool,
opTick.tickLower,
opTick.tickUpper,
_params.liquidityToExercise[i]
);
positionManager.unusePosition(opTick._handler, unusePositionData);
opTick.liquidityToUse -= _params.liquidityToExercise[i];
totalProfit += currentBalance - (prevBalance + amountReq);
}
ERC20(oData.isCall ? putAsset : callAsset).transfer(
msg.sender,
totalProfit
);
emit LogExerciseOptionRoll(
ownerOf(_params.optionId),
_params.optionId,
totalProfit
);
}
/**
* @notice Settles the given option roll.
* @param _params The settle option roll parameters.
*/
function settleOptionRoll(
SettleOptionRollParams calldata _params
) external nonReentrant {
if (!settlers[msg.sender])
revert DopexV2OptionPools__NotApprovedSettler();
OptionData memory oData = opData[_params.optionId];
if (oData.opTickArrayLen != _params.liquidityToSettle.length)
revert DopexV2OptionPools__ArrayLenMismatch();
if (block.timestamp <= oData.expiry)
revert DopexV2OptionPools__OptionNotExpired();
for (uint256 i; i < oData.opTickArrayLen; i++) {
OptionTicks storage opTick = opTickMap[_params.optionId][i];
uint256 liquidityToSettle = _params.liquidityToSettle[i] != 0
? _params.liquidityToSettle[i]
: opTick.liquidityToUse;
(uint256 amount0, uint256 amount1) = LiquidityAmounts
.getAmountsForLiquidity(
_getCurrentSqrtPriceX96(opTick.pool),
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(liquidityToSettle)
);
bool isAmount0 = oData.isCall
? primePool.token0() == callAsset
: primePool.token0() == putAsset;
if (
(amount0 > 0 && amount1 == 0) || (amount1 > 0 && amount0 == 0)
) {
if (isAmount0 && amount0 > 0) {
ERC20(oData.isCall ? callAsset : putAsset).approve(
address(positionManager),
amount0
);
bytes memory unusePositionData = abi.encode(
opTick.pool,
opTick.tickLower,
opTick.tickUpper,
liquidityToSettle
);
positionManager.unusePosition(
opTick._handler,
unusePositionData
);
opTick.liquidityToUse -= liquidityToSettle;
} else if (!isAmount0 && amount1 > 0) {
ERC20(oData.isCall ? callAsset : putAsset).approve(
address(positionManager),
amount1
);
bytes memory unusePositionData = abi.encode(
opTick.pool,
opTick.tickLower,
opTick.tickUpper,
liquidityToSettle
);
positionManager.unusePosition(
opTick._handler,
unusePositionData
);
opTick.liquidityToUse -= liquidityToSettle;
} else {
uint256 amountToSwap = isAmount0
? LiquidityAmounts.getAmount0ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(liquidityToSettle)
)
: LiquidityAmounts.getAmount1ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(liquidityToSettle)
);
uint256 prevBalance = ERC20(
oData.isCall ? putAsset : callAsset
).balanceOf(address(this));
ERC20(oData.isCall ? callAsset : putAsset).transfer(
address(_params.swapper),
amountToSwap
);
_params.swapper.onSwapReceived(
oData.isCall ? callAsset : putAsset,
oData.isCall ? putAsset : callAsset,
amountToSwap,
_params.swapData
);
uint256 amountReq = isAmount0
? LiquidityAmounts.getAmount1ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(liquidityToSettle)
)
: LiquidityAmounts.getAmount0ForLiquidity(
opTick.tickLower.getSqrtRatioAtTick(),
opTick.tickUpper.getSqrtRatioAtTick(),
uint128(liquidityToSettle)
);
uint256 currentBalance = ERC20(
oData.isCall ? putAsset : callAsset
).balanceOf(address(this));
if (currentBalance < prevBalance + amountReq)
revert DopexV2OptionPools__NotEnoughAfterSwap();
ERC20(oData.isCall ? putAsset : callAsset).approve(
address(positionManager),
amountReq
);
bytes memory unusePositionData = abi.encode(
opTick.pool,
opTick.tickLower,
opTick.tickUpper,
liquidityToSettle
);
positionManager.unusePosition(
opTick._handler,
unusePositionData
);
opTick.liquidityToUse -= liquidityToSettle;
ERC20(oData.isCall ? putAsset : callAsset).transfer(
msg.sender,
currentBalance - (prevBalance + amountReq)
);
}
} else {}
}
emit LogSettleOptionRoll(ownerOf(_params.optionId), _params.optionId);
}
/**
* @notice Splits the given option roll into two new option rolls.
* @param _params The position splitter parameters.
*/
function positionSplitter(
PositionSplitterParams calldata _params
) external nonReentrant {
optionIds += 1;
if (ownerOf(_params.optionId) != msg.sender)
revert DopexV2OptionPools__NotOwnerOrDelegator();
OptionData memory oData = opData[_params.optionId];
if (oData.opTickArrayLen != _params.liquidityToSplit.length)
revert DopexV2OptionPools__ArrayLenMismatch();
for (uint256 i; i < _params.liquidityToSplit.length; i++) {
OptionTicks storage opTick = opTickMap[_params.optionId][i];
opTick.liquidityToUse -= _params.liquidityToSplit[i];
opTickMap[optionIds].push(
OptionTicks({
_handler: opTick._handler,
pool: opTick.pool,
tickLower: opTick.tickLower,
tickUpper: opTick.tickUpper,
liquidityToUse: _params.liquidityToSplit[i]
})
);
}
opData[optionIds] = OptionData({
opTickArrayLen: _params.liquidityToSplit.length,
tickLower: oData.tickLower,
tickUpper: oData.tickUpper,
expiry: oData.expiry,
isCall: oData.isCall
});
_safeMint(_params.to, optionIds);
emit LogSplitOptionRoll(
ownerOf(_params.optionId),
_params.optionId,
optionIds,
_params.to
);
}
/**
* @notice Updates the exercise delegate for the caller's option rolls.
* @param _delegateTo The address of the new exercise delegate.
* @param _status The status of the exercise delegate (true to enable, false to disable).
*/
function updateExerciseDelegate(
address _delegateTo,
bool _status
) external {
exerciseDelegator[msg.sender][_delegateTo] = _status;
}
// internal
/**
* @notice Calculates the price per call asset for the given tick.
* @param _pool The UniswapV3 pool.
* @param _tick The tick.
* @return The price per call asset.
*/
function getPricePerCallAssetViaTick(
IUniswapV3Pool _pool,
int24 _tick
) public view returns (uint256) {
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(_tick);
return _getPrice(_pool, sqrtPriceX96);
}
/**
* @notice Calculates the current price per call asset.
* @param _pool The UniswapV3 pool.
* @return The current price per call asset.
*/
function getCurrentPricePerCallAsset(
IUniswapV3Pool _pool
) public view returns (uint256) {
(uint160 sqrtPriceX96, , , , , , ) = _pool.slot0();
return _getPrice(_pool, sqrtPriceX96);
}
/**
* @notice Calculates the premium amount for the given option parameters.
* @param isPut Whether the option is a put or call.
* @param expiry The expiry of the option.
* @param strike The strike price of the option.
* @param lastPrice The last price of the underlying asset.
* @param baseIv The base implied volatility of the underlying asset.
* @param amount The amount of the underlying asset.
* @return The premium amount.
*/
function getPremiumAmount(
bool isPut,
uint expiry,
uint strike,
uint lastPrice,
uint baseIv,
uint amount
) external view returns (uint256) {
return
_getPremiumAmount(isPut, expiry, strike, lastPrice, baseIv, amount);
}
/**
* @notice Gets the current sqrt price.
* @param pool The UniswapV3 pool.
* @return sqrtPriceX96 The current sqrt price.
*/
function _getCurrentSqrtPriceX96(
IUniswapV3Pool pool
) internal view returns (uint160 sqrtPriceX96) {
(sqrtPriceX96, , , , , , ) = pool.slot0();
}
/**
* @notice Calculates the premium amount for the given option parameters.
* @param isPut Whether the option is a put or call.
* @param expiry The expiry of the option.
* @param strike The strike price of the option.
* @param lastPrice The last price of the underlying asset.
* @param baseIv The base implied volatility of the underlying asset.
* @param amount The amount of the underlying asset.
* @return premiumAmount The premium amount.
*/
function _getPremiumAmount(
bool isPut,
uint expiry,
uint strike,
uint lastPrice,
uint baseIv,
uint amount
) internal view returns (uint256 premiumAmount) {
uint premiumInQuote = (amount *
optionPricing.getOptionPrice(
isPut,
expiry,
strike,
lastPrice,
baseIv
)) /
(
isPut
? 10 ** ERC20(putAsset).decimals()
: 10 ** ERC20(callAsset).decimals()
);
if (isPut) {
return premiumInQuote;
}
return
(premiumInQuote * (10 ** ERC20(callAsset).decimals())) / lastPrice;
}
/**
* @notice Gets the price per call asset in quote asset units.
* @param _pool The UniswapV3 pool instance.
* @param sqrtPriceX96 The sqrt price of the pool.
* @return price The price per call asset in quote asset units.
*/
function _getPrice(
IUniswapV3Pool _pool,
uint160 sqrtPriceX96
) internal view returns (uint256 price) {
if (sqrtPriceX96 <= type(uint128).max) {
uint256 priceX192 = uint256(sqrtPriceX96) * sqrtPriceX96;
price = callAsset == _pool.token0()
? FullMath.mulDiv(
priceX192,
10 ** ERC20(callAsset).decimals(),
1 << 192
)
: FullMath.mulDiv(
1 << 192,
10 ** ERC20(callAsset).decimals(),
priceX192
);
} else {
uint256 priceX192 = FullMath.mulDiv(
sqrtPriceX96,
sqrtPriceX96,
1 << 64
);
price = callAsset == _pool.token0()
? FullMath.mulDiv(
priceX192,
10 ** ERC20(callAsset).decimals(),
1 << 192
)
: FullMath.mulDiv(
1 << 192,
10 ** ERC20(callAsset).decimals(),
priceX192
);
}
}
// admin
/**
* @notice Updates the implied volatility (IV) for the given time to expirations (TTLs).
* @param _ttls The TTLs to update the IV for.
* @param _ttlIV The new IVs for the given TTLs.
* @dev Only the owner can call this function.
*/
function updateIVs(
uint256[] calldata _ttls,
uint256[] calldata _ttlIV
) external onlyOwner {
for (uint256 i; i < _ttls.length; i++) {
ttlToVEID[_ttls[i]] = _ttlIV[i];
}
}
/**
* @notice Updates the addresses of the various components of the contract.
* @param _feeTo The address of the fee recipient.
* @param _tokeURIFetcher The address of the token URI fetcher.
* @param _dpFee The address of the Dopex fee contract.
* @param _optionPricing The address of the option pricing contract.
* @param _settler The address of the settler.
* @param _statusSettler Whether the settler is enabled.
* @param _pool The address of the UniswapV3 pool.
* @param _statusPools Whether the UniswapV3 pool is enabled.
* @dev Only the owner can call this function.
*/
function updateAddress(
address _feeTo,
address _tokeURIFetcher,
address _dpFee,
address _optionPricing,
address _settler,
bool _statusSettler,
address _pool,
bool _statusPools
) external onlyOwner {
feeTo = _feeTo;
tokenURIFetcher = _tokeURIFetcher;
dpFee = IDopexFee(_dpFee);
optionPricing = IOptionPricing(_optionPricing);
settlers[_settler] = _statusSettler;
approvedPools[_pool] = _statusPools;
}
// SOS admin functions
/**
* @notice Performs an emergency withdraw of all tokens from the contract.
* @param token The address of the token to withdraw.
* @dev Only the owner can call this function.
*/
function emergencyWithdraw(address token) external onlyOwner {
ERC20(token).transfer(
msg.sender,
ERC20(token).balanceOf(address(this))
);
}
}