文件 1 的 44:AccessControl.sol
pragma solidity >=0.8.0;
import "../interfaces/IAuthority.sol";
error UNAUTHORIZED();
abstract contract AccessControl {
event AuthorityUpdated(IAuthority authority);
IAuthority public authority;
constructor(IAuthority _authority) {
authority = _authority;
emit AuthorityUpdated(_authority);
}
function setAuthority(IAuthority _newAuthority) external {
_onlyGovernor();
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
function _onlyGovernor() internal view {
if (msg.sender != authority.governor()) revert UNAUTHORIZED();
}
function _onlyGuardian() internal view {
if (!authority.guardian(msg.sender) && msg.sender != authority.governor()) revert UNAUTHORIZED();
}
function _onlyManager() internal view {
if (msg.sender != authority.manager() && msg.sender != authority.governor())
revert UNAUTHORIZED();
}
}
文件 2 的 44:AddressBookInterface.sol
pragma solidity 0.8.9;
interface AddressBookInterface {
function getOtokenImpl() external view returns (address);
function getOtokenFactory() external view returns (address);
function getWhitelist() external view returns (address);
function getController() external view returns (address);
function getOracle() external view returns (address);
function getMarginPool() external view returns (address);
function getMarginCalculator() external view returns (address);
function getLiquidationManager() external view returns (address);
function getAddress(bytes32 _id) external view returns (address);
function setOtokenImpl(address _otokenImpl) external;
function setOtokenFactory(address _factory) external;
function setOracleImpl(address _otokenImpl) external;
function setWhitelist(address _whitelist) external;
function setController(address _controller) external;
function setMarginPool(address _marginPool) external;
function setMarginCalculator(address _calculator) external;
function setLiquidationManager(address _liquidationManager) external;
function setAddress(bytes32 _id, address _newImpl) external;
}
文件 3 的 44:AggregatorV3Interface.sol
pragma solidity >=0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
文件 4 的 44:AlphaPortfolioValuesFeed.sol
pragma solidity ^0.8.9;
import "./PriceFeed.sol";
import "./Protocol.sol";
import "./OptionExchange.sol";
import "./VolatilityFeed.sol";
import "./libraries/Types.sol";
import "./libraries/BlackScholes.sol";
import "./libraries/CustomErrors.sol";
import "./libraries/AccessControl.sol";
import "./libraries/EnumerableSet.sol";
import "./libraries/OptionsCompute.sol";
import "./interfaces/GammaInterface.sol";
import "./interfaces/ILiquidityPool.sol";
import "./interfaces/IOptionRegistry.sol";
import "./interfaces/IPortfolioValuesFeed.sol";
import "./interfaces/AddressBookInterface.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
contract AlphaPortfolioValuesFeed is AccessControl, IPortfolioValuesFeed {
using EnumerableSet for EnumerableSet.AddressSet;
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
struct OptionStores {
Types.OptionSeries optionSeries;
int256 shortExposure;
int256 longExposure;
}
uint256 constant oTokenDecimals = 8;
int256 private constant SCALE = 1e18;
Protocol public immutable protocol;
mapping(address => OptionStores) public storesForAddress;
EnumerableSet.AddressSet internal addressSet;
mapping(address => mapping(address => Types.PortfolioValues)) private portfolioValues;
mapping(bytes32 => int256) public netDhvExposure;
ILiquidityPool public liquidityPool;
mapping(address => bool) public handler;
mapping(address => bool) public keeper;
uint256 public rfr = 0;
uint256 public maxNetDhvExposure;
event DataFullfilled(
address indexed underlying,
address indexed strike,
int256 delta,
int256 gamma,
int256 vega,
int256 theta,
int256 callPutsValue
);
event RequestedUpdate(address _underlying, address _strike);
event StoresUpdated(
address seriesAddress,
int256 shortExposure,
int256 longExposure,
Types.OptionSeries optionSeries
);
event MaxNetDhvExposureUpdated(uint256 maxNetDhvExposure);
event NetDhvExposureChanged(
bytes32 indexed optionHash,
int256 oldNetDhvExposure,
int256 newNetDhvExposure
);
error OptionHasExpiredInStores(uint256 index, address seriesAddress);
error MaxNetDhvExposureExceeded();
error NoVaultForShortPositions();
error IncorrectSeriesToRemove();
error SeriesNotExpired();
error NoShortPositions();
constructor(
address _authority,
uint256 _maxNetDhvExposure,
address _protocol
) AccessControl(IAuthority(_authority)) {
maxNetDhvExposure = _maxNetDhvExposure;
protocol = Protocol(_protocol);
}
function setLiquidityPool(address _liquidityPool) external {
_onlyGovernor();
liquidityPool = ILiquidityPool(_liquidityPool);
}
function setRFR(uint256 _rfr) external {
_onlyGovernor();
rfr = _rfr;
}
function setKeeper(address _keeper, bool _auth) external {
_onlyGovernor();
keeper[_keeper] = _auth;
}
function setHandler(address _handler, bool _auth) external {
_onlyGovernor();
handler[_handler] = _auth;
}
function setMaxNetDhvExposure(uint256 _maxNetDhvExposure) external {
_onlyGovernor();
maxNetDhvExposure = _maxNetDhvExposure;
emit MaxNetDhvExposureUpdated(_maxNetDhvExposure);
}
function setNetDhvExposures(
bytes32[] memory _optionHashes,
int256[] memory _netDhvExposures
) external {
_onlyGovernor();
_isExchangePaused();
uint256 arrayLength = _optionHashes.length;
require(arrayLength == _netDhvExposures.length);
for (uint i; i < arrayLength; i++) {
if (uint256(_netDhvExposures[i].abs()) > maxNetDhvExposure) revert MaxNetDhvExposureExceeded();
emit NetDhvExposureChanged(
_optionHashes[i],
netDhvExposure[_optionHashes[i]],
_netDhvExposures[i]
);
netDhvExposure[_optionHashes[i]] = _netDhvExposures[i];
}
}
function fulfill(address _underlying, address _strikeAsset) external {
int256 delta;
int256 callPutsValue;
uint256 lengthAddy = addressSet.length();
uint256 spotPrice = _getUnderlyingPrice(_underlying, _strikeAsset);
VolatilityFeed volFeed = _getVolatilityFeed();
uint256 _rfr = rfr;
for (uint256 i = 0; i < lengthAddy; i++) {
OptionStores memory _optionStores = storesForAddress[addressSet.at(i)];
if (_optionStores.optionSeries.expiration < block.timestamp) {
revert OptionHasExpiredInStores(i, addressSet.at(i));
}
(uint256 vol, uint256 forward) = volFeed.getImpliedVolatilityWithForward(
_optionStores.optionSeries.isPut,
spotPrice,
_optionStores.optionSeries.strike,
_optionStores.optionSeries.expiration
);
(uint256 _callPutsValue, int256 _delta) = BlackScholes.blackScholesCalcGreeks(
forward,
_optionStores.optionSeries.strike,
_optionStores.optionSeries.expiration,
vol,
_rfr,
_optionStores.optionSeries.isPut
);
_callPutsValue = _callPutsValue.mul(spotPrice).div(forward);
int256 netExposure = _optionStores.shortExposure - _optionStores.longExposure;
delta -= (_delta * netExposure) / SCALE;
callPutsValue += (int256(_callPutsValue) * netExposure) / SCALE;
}
Types.PortfolioValues memory portfolioValue = Types.PortfolioValues({
delta: delta,
gamma: 0,
vega: 0,
theta: 0,
callPutsValue: callPutsValue,
spotPrice: spotPrice,
timestamp: block.timestamp
});
portfolioValues[_underlying][_strikeAsset] = portfolioValue;
liquidityPool.resetEphemeralValues();
emit DataFullfilled(_underlying, _strikeAsset, delta, 0, 0, 0, callPutsValue);
}
function updateStores(
Types.OptionSeries memory _optionSeries,
int256 shortExposure,
int256 longExposure,
address _seriesAddress
) external {
_isHandler();
if (!addressSet.contains(_seriesAddress)) {
addressSet.add(_seriesAddress);
storesForAddress[_seriesAddress] = OptionStores(_optionSeries, shortExposure, longExposure);
} else {
storesForAddress[_seriesAddress].shortExposure += shortExposure;
storesForAddress[_seriesAddress].longExposure += longExposure;
}
bytes32 oHash = keccak256(
abi.encodePacked(_optionSeries.expiration, _optionSeries.strike, _optionSeries.isPut)
);
netDhvExposure[oHash] -= shortExposure;
netDhvExposure[oHash] += longExposure;
if (uint256(netDhvExposure[oHash].abs()) > maxNetDhvExposure) revert MaxNetDhvExposureExceeded();
emit StoresUpdated(_seriesAddress, shortExposure, longExposure, _optionSeries);
}
address[] private addyList;
function syncLooper() external {
_isKeeper();
uint256 lengthAddy = addressSet.length();
for (uint256 i; i < lengthAddy; i++) {
if (storesForAddress[addressSet.at(i)].optionSeries.expiration < block.timestamp) {
addyList.push(addressSet.at(i));
}
}
lengthAddy = addyList.length;
for (uint256 j; j < lengthAddy; j++) {
_cleanLooper(addyList[j]);
}
delete addyList;
}
function cleanLooperManually(address _series) external {
_isKeeper();
if (!addressSet.contains(_series)) {
revert IncorrectSeriesToRemove();
}
if (storesForAddress[_series].optionSeries.expiration > block.timestamp) {
revert SeriesNotExpired();
}
_cleanLooper(_series);
}
function _cleanLooper(address _series) internal {
addressSet.remove(_series);
delete storesForAddress[_series];
}
function accountLiquidatedSeries(address _series) external {
_isKeeper();
if (!addressSet.contains(_series)) {
revert IncorrectSeriesToRemove();
}
OptionStores memory _optionStores = storesForAddress[_series];
if (_optionStores.shortExposure == 0) {
revert NoShortPositions();
}
IOptionRegistry optionRegistry = _getOptionRegistry();
uint256 vaultId = optionRegistry.vaultIds(_series);
if (vaultId == 0) {
revert NoVaultForShortPositions();
}
uint256 shortAmounts = OptionsCompute.convertFromDecimals(
IController(AddressBookInterface(optionRegistry.addressBook()).getController())
.getVault(address(optionRegistry), vaultId)
.shortAmounts[0],
oTokenDecimals
);
storesForAddress[_series].shortExposure = int256(shortAmounts);
}
function migrate(IPortfolioValuesFeed _migrateContract) external {
_onlyGovernor();
uint256 lengthAddy = addressSet.length();
for (uint256 i = 0; i < lengthAddy; i++) {
address oTokenAddy = addressSet.at(i);
OptionStores memory _optionStores = storesForAddress[oTokenAddy];
_migrateContract.updateStores(
_optionStores.optionSeries,
_optionStores.shortExposure,
_optionStores.longExposure,
oTokenAddy
);
}
}
function requestPortfolioData(address _underlying, address _strike) external returns (bytes32 id) {
emit RequestedUpdate(_underlying, _strike);
}
function getPortfolioValues(
address underlying,
address strike
) external view returns (Types.PortfolioValues memory) {
return portfolioValues[underlying][strike];
}
function _isKeeper() internal view {
if (
!keeper[msg.sender] && msg.sender != authority.governor() && msg.sender != authority.manager()
) {
revert CustomErrors.NotKeeper();
}
}
function _isHandler() internal view {
if (!handler[msg.sender]) {
revert();
}
}
function isAddressInSet(address _a) external view returns (bool) {
return addressSet.contains(_a);
}
function addressAtIndexInSet(uint256 _i) external view returns (address) {
return addressSet.at(_i);
}
function addressSetLength() external view returns (uint256) {
return addressSet.length();
}
function getAddressSet() external view returns (address[] memory) {
return addressSet.values();
}
function _getVolatilityFeed() internal view returns (VolatilityFeed) {
return VolatilityFeed(protocol.volatilityFeed());
}
function _getOptionRegistry() internal view returns (IOptionRegistry) {
return IOptionRegistry(protocol.optionRegistry());
}
function _getUnderlyingPrice(
address underlying,
address _strikeAsset
) internal view returns (uint256) {
return PriceFeed(protocol.priceFeed()).getNormalizedRate(underlying, _strikeAsset);
}
function _isExchangePaused() internal view {
if (!OptionExchange(protocol.optionExchange()).paused()) {
revert CustomErrors.ExchangeNotPaused();
}
}
}
文件 5 的 44:BeyondPricer.sol
pragma solidity >=0.8.9;
import "./Protocol.sol";
import "./PriceFeed.sol";
import "./OptionExchange.sol";
import "./VolatilityFeed.sol";
import "./tokens/ERC20.sol";
import "./libraries/Types.sol";
import "./utils/ReentrancyGuard.sol";
import "./libraries/CustomErrors.sol";
import "./libraries/AccessControl.sol";
import "./libraries/OptionsCompute.sol";
import "./libraries/SafeTransferLib.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/IMarginCalculator.sol";
import "./interfaces/ILiquidityPool.sol";
import "./interfaces/IPortfolioValuesFeed.sol";
import "./interfaces/AddressBookInterface.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
contract BeyondPricer is AccessControl, ReentrancyGuard {
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
struct DeltaBorrowRates {
int sellLong;
int sellShort;
int buyLong;
int buyShort;
}
struct DeltaBandMultipliers {
int80[] callSlippageGradientMultipliers;
int80[] putSlippageGradientMultipliers;
int80[] callSpreadCollateralMultipliers;
int80[] putSpreadCollateralMultipliers;
int80[] callSpreadDeltaMultipliers;
int80[] putSpreadDeltaMultipliers;
}
ILiquidityPool public immutable liquidityPool;
Protocol public immutable protocol;
AddressBookInterface public immutable addressBook;
address public immutable strikeAsset;
address public immutable underlyingAsset;
address public immutable collateralAsset;
uint256 public bidAskIVSpread;
uint256 public riskFreeRate;
uint256 public feePerContract = 5e5;
uint256 public slippageGradient;
uint256 public deltaBandWidth;
uint16 public numberOfTenors;
DeltaBandMultipliers[] internal tenorPricingParams;
uint16 public maxTenorValue;
uint256 public collateralLendingRate;
DeltaBorrowRates public deltaBorrowRates;
uint256 public lowDeltaSellOptionFlatIV = 35e16;
uint256 public lowDeltaThreshold = 5e16;
uint256 private constant SIX_DPS = 1_000_000;
uint256 private constant ONE_YEAR_SECONDS = 31557600;
uint256 private constant SCALE_FROM = 10 ** 10;
uint256 private constant ONE_DELTA = 100e18;
uint256 private constant ONE_SCALE = 1e18;
int256 private constant ONE_SCALE_INT = 1e18;
int256 private constant SIX_DPS_INT = 1_000_000;
event TenorParamsSet();
event SlippageGradientMultipliersChanged();
event SpreadCollateralMultipliersChanged();
event SpreadDeltaMultipliersChanged();
event DeltaBandWidthChanged(uint256 newDeltaBandWidth, uint256 oldDeltaBandWidth);
event CollateralLendingRateChanged(
uint256 newCollateralLendingRate,
uint256 oldCollateralLendingRate
);
event DeltaBorrowRatesChanged(
DeltaBorrowRates newDeltaBorrowRates,
DeltaBorrowRates oldDeltaBorrowRates
);
event SlippageGradientChanged(uint256 newSlippageGradient, uint256 oldSlippageGradient);
event FeePerContractChanged(uint256 newFeePerContract, uint256 oldFeePerContract);
event RiskFreeRateChanged(uint256 newRiskFreeRate, uint256 oldRiskFreeRate);
event BidAskIVSpreadChanged(uint256 newBidAskIVSpread, uint256 oldBidAskIVSpread);
event LowDeltaSellOptionFlatIVChanged(
uint256 newLowDeltaSellOptionFlatIV,
uint256 oldLowDeltaSellOptionFlatIV
);
event LowDeltaThresholdChanged(uint256 newLowDeltaThreshold, uint256 oldLowDeltaThreshold);
error InvalidMultipliersArrayLength();
error InvalidMultiplierValue();
error InvalidTenorArrayLength();
constructor(
address _authority,
address _protocol,
address _liquidityPool,
address _addressBook,
uint256 _slippageGradient,
uint256 _collateralLendingRate,
DeltaBorrowRates memory _deltaBorrowRates
) AccessControl(IAuthority(_authority)) {
protocol = Protocol(_protocol);
liquidityPool = ILiquidityPool(_liquidityPool);
addressBook = AddressBookInterface(_addressBook);
collateralAsset = liquidityPool.collateralAsset();
underlyingAsset = liquidityPool.underlyingAsset();
strikeAsset = liquidityPool.strikeAsset();
slippageGradient = _slippageGradient;
collateralLendingRate = _collateralLendingRate;
deltaBorrowRates = _deltaBorrowRates;
}
function setLowDeltaSellOptionFlatIV(uint256 _lowDeltaSellOptionFlatIV) external {
_onlyManager();
_isExchangePaused();
emit LowDeltaSellOptionFlatIVChanged(_lowDeltaSellOptionFlatIV, lowDeltaSellOptionFlatIV);
lowDeltaSellOptionFlatIV = _lowDeltaSellOptionFlatIV;
}
function setLowDeltaThreshold(uint256 _lowDeltaThreshold) external {
_onlyManager();
_isExchangePaused();
emit LowDeltaThresholdChanged(_lowDeltaThreshold, lowDeltaThreshold);
lowDeltaThreshold = _lowDeltaThreshold;
}
function setRiskFreeRate(uint256 _riskFreeRate) external {
_onlyManager();
_isExchangePaused();
emit RiskFreeRateChanged(_riskFreeRate, riskFreeRate);
riskFreeRate = _riskFreeRate;
}
function setBidAskIVSpread(uint256 _bidAskIVSpread) external {
_onlyManager();
_isExchangePaused();
emit BidAskIVSpreadChanged(_bidAskIVSpread, bidAskIVSpread);
bidAskIVSpread = _bidAskIVSpread;
}
function setFeePerContract(uint256 _feePerContract) external {
_onlyGovernor();
_isExchangePaused();
emit FeePerContractChanged(_feePerContract, feePerContract);
feePerContract = _feePerContract;
}
function setSlippageGradient(uint256 _slippageGradient) external {
_onlyManager();
_isExchangePaused();
emit SlippageGradientChanged(_slippageGradient, slippageGradient);
slippageGradient = _slippageGradient;
}
function setCollateralLendingRate(uint256 _collateralLendingRate) external {
_onlyManager();
_isExchangePaused();
emit CollateralLendingRateChanged(_collateralLendingRate, collateralLendingRate);
collateralLendingRate = _collateralLendingRate;
}
function setDeltaBorrowRates(DeltaBorrowRates calldata _deltaBorrowRates) external {
_onlyManager();
_isExchangePaused();
emit DeltaBorrowRatesChanged(_deltaBorrowRates, deltaBorrowRates);
deltaBorrowRates = _deltaBorrowRates;
}
function initializeTenorParams(
uint256 _deltaBandWidth,
uint16 _numberOfTenors,
uint16 _maxTenorValue,
DeltaBandMultipliers[] memory _tenorPricingParams
) external {
_onlyManager();
_isExchangePaused();
if (_tenorPricingParams.length != _numberOfTenors) {
revert InvalidTenorArrayLength();
}
for (uint16 i = 0; i < _numberOfTenors; i++) {
if (
_tenorPricingParams[i].callSlippageGradientMultipliers.length != ONE_DELTA / _deltaBandWidth ||
_tenorPricingParams[i].putSlippageGradientMultipliers.length != ONE_DELTA / _deltaBandWidth ||
_tenorPricingParams[i].callSpreadCollateralMultipliers.length != ONE_DELTA / _deltaBandWidth ||
_tenorPricingParams[i].putSpreadCollateralMultipliers.length != ONE_DELTA / _deltaBandWidth ||
_tenorPricingParams[i].callSpreadDeltaMultipliers.length != ONE_DELTA / _deltaBandWidth ||
_tenorPricingParams[i].putSpreadDeltaMultipliers.length != ONE_DELTA / _deltaBandWidth
) {
revert InvalidMultipliersArrayLength();
}
uint256 len = _tenorPricingParams[i].callSlippageGradientMultipliers.length;
for (uint256 j = 0; j < len; j++) {
if (
_tenorPricingParams[i].callSlippageGradientMultipliers[j] < ONE_SCALE_INT ||
_tenorPricingParams[i].putSlippageGradientMultipliers[j] < ONE_SCALE_INT ||
_tenorPricingParams[i].callSpreadCollateralMultipliers[j] < ONE_SCALE_INT ||
_tenorPricingParams[i].putSpreadCollateralMultipliers[j] < ONE_SCALE_INT ||
_tenorPricingParams[i].callSpreadDeltaMultipliers[j] < ONE_SCALE_INT ||
_tenorPricingParams[i].putSpreadDeltaMultipliers[j] < ONE_SCALE_INT
) {
revert InvalidMultiplierValue();
}
}
}
numberOfTenors = _numberOfTenors;
maxTenorValue = _maxTenorValue;
deltaBandWidth = _deltaBandWidth;
delete tenorPricingParams;
for (uint i = 0; i < _numberOfTenors; i++) {
tenorPricingParams.push(_tenorPricingParams[i]);
}
emit TenorParamsSet();
}
function setSlippageGradientMultipliers(
uint16 _tenorIndex,
int80[] memory _callSlippageGradientMultipliers,
int80[] memory _putSlippageGradientMultipliers
) public {
_onlyManager();
_isExchangePaused();
if (
_callSlippageGradientMultipliers.length != ONE_DELTA / deltaBandWidth ||
_putSlippageGradientMultipliers.length != ONE_DELTA / deltaBandWidth
) {
revert InvalidMultipliersArrayLength();
}
uint256 len = _callSlippageGradientMultipliers.length;
for (uint256 i = 0; i < len; i++) {
if (
_callSlippageGradientMultipliers[i] < ONE_SCALE_INT ||
_putSlippageGradientMultipliers[i] < ONE_SCALE_INT
) {
revert InvalidMultiplierValue();
}
}
tenorPricingParams[_tenorIndex]
.callSlippageGradientMultipliers = _callSlippageGradientMultipliers;
tenorPricingParams[_tenorIndex].putSlippageGradientMultipliers = _putSlippageGradientMultipliers;
emit SlippageGradientMultipliersChanged();
}
function setSpreadCollateralMultipliers(
uint16 _tenorIndex,
int80[] memory _callSpreadCollateralMultipliers,
int80[] memory _putSpreadCollateralMultipliers
) public {
_onlyManager();
_isExchangePaused();
if (
_callSpreadCollateralMultipliers.length != ONE_DELTA / deltaBandWidth ||
_putSpreadCollateralMultipliers.length != ONE_DELTA / deltaBandWidth
) {
revert InvalidMultipliersArrayLength();
}
uint256 len = _callSpreadCollateralMultipliers.length;
for (uint256 i = 0; i < len; i++) {
if (
_callSpreadCollateralMultipliers[i] < ONE_SCALE_INT ||
_putSpreadCollateralMultipliers[i] < ONE_SCALE_INT
) {
revert InvalidMultiplierValue();
}
}
tenorPricingParams[_tenorIndex]
.callSpreadCollateralMultipliers = _callSpreadCollateralMultipliers;
tenorPricingParams[_tenorIndex].putSpreadCollateralMultipliers = _putSpreadCollateralMultipliers;
emit SpreadCollateralMultipliersChanged();
}
function setSpreadDeltaMultipliers(
uint16 _tenorIndex,
int80[] memory _callSpreadDeltaMultipliers,
int80[] memory _putSpreadDeltaMultipliers
) public {
_onlyManager();
_isExchangePaused();
if (
_callSpreadDeltaMultipliers.length != ONE_DELTA / deltaBandWidth ||
_putSpreadDeltaMultipliers.length != ONE_DELTA / deltaBandWidth
) {
revert InvalidMultipliersArrayLength();
}
uint256 len = _callSpreadDeltaMultipliers.length;
for (uint256 i = 0; i < len; i++) {
if (
_callSpreadDeltaMultipliers[i] < ONE_SCALE_INT || _putSpreadDeltaMultipliers[i] < ONE_SCALE_INT
) {
revert InvalidMultiplierValue();
}
}
tenorPricingParams[_tenorIndex].callSpreadDeltaMultipliers = _callSpreadDeltaMultipliers;
tenorPricingParams[_tenorIndex].putSpreadDeltaMultipliers = _putSpreadDeltaMultipliers;
emit SpreadDeltaMultipliersChanged();
}
function quoteOptionPrice(
Types.OptionSeries memory _optionSeries,
uint256 _amount,
bool isSell,
int256 netDhvExposure
) external view returns (uint256 totalPremium, int256 totalDelta, uint256 totalFees) {
uint256 underlyingPrice = _getUnderlyingPrice(underlyingAsset, strikeAsset);
(uint256 iv, uint256 forward) = _getVolatilityFeed().getImpliedVolatilityWithForward(
_optionSeries.isPut,
underlyingPrice,
_optionSeries.strike,
_optionSeries.expiration
);
(uint256 vanillaPremium, int256 delta) = OptionsCompute.quotePriceGreeks(
_optionSeries,
isSell,
bidAskIVSpread,
riskFreeRate,
iv,
forward,
false
);
vanillaPremium = vanillaPremium.mul(underlyingPrice).div(forward);
uint256 premium = vanillaPremium.mul(
_getSlippageMultiplier(_optionSeries, _amount, delta, isSell, netDhvExposure)
);
int spread = _getSpreadValue(
isSell,
_optionSeries,
_amount,
delta,
netDhvExposure,
underlyingPrice
);
if (spread < 0) {
spread = 0;
}
totalPremium = isSell
? uint(OptionsCompute.max(int(premium.mul(_amount)) - spread, 0))
: premium.mul(_amount) + uint(spread);
totalPremium = OptionsCompute.convertToDecimals(totalPremium, ERC20(collateralAsset).decimals());
totalDelta = delta.mul(int256(_amount));
totalFees = feePerContract.mul(_amount);
if (isSell && uint256(delta.abs()) < lowDeltaThreshold) {
(uint overridePremium, ) = OptionsCompute.quotePriceGreeks(
_optionSeries,
isSell,
bidAskIVSpread,
riskFreeRate,
lowDeltaSellOptionFlatIV,
forward,
true
);
overridePremium = overridePremium.mul(underlyingPrice).div(forward);
overridePremium = OptionsCompute.convertToDecimals(
overridePremium.mul(_amount),
ERC20(collateralAsset).decimals()
);
totalPremium = OptionsCompute.min(totalPremium, overridePremium);
}
}
function getCallSlippageGradientMultipliers(
uint16 _tenorIndex
) external view returns (int80[] memory) {
return tenorPricingParams[_tenorIndex].callSlippageGradientMultipliers;
}
function getPutSlippageGradientMultipliers(
uint16 _tenorIndex
) external view returns (int80[] memory) {
return tenorPricingParams[_tenorIndex].putSlippageGradientMultipliers;
}
function getCallSpreadCollateralMultipliers(
uint16 _tenorIndex
) external view returns (int80[] memory) {
return tenorPricingParams[_tenorIndex].callSpreadCollateralMultipliers;
}
function getPutSpreadCollateralMultipliers(
uint16 _tenorIndex
) external view returns (int80[] memory) {
return tenorPricingParams[_tenorIndex].putSpreadCollateralMultipliers;
}
function getCallSpreadDeltaMultipliers(uint16 _tenorIndex) external view returns (int80[] memory) {
return tenorPricingParams[_tenorIndex].callSpreadDeltaMultipliers;
}
function getPutSpreadDeltaMultipliers(uint16 _tenorIndex) external view returns (int80[] memory) {
return tenorPricingParams[_tenorIndex].putSpreadDeltaMultipliers;
}
function _getUnderlyingPrice(
address underlying,
address _strikeAsset
) internal view returns (uint256) {
return PriceFeed(protocol.priceFeed()).getNormalizedRate(underlying, _strikeAsset);
}
function _getVolatilityFeed() internal view returns (VolatilityFeed) {
return VolatilityFeed(protocol.volatilityFeed());
}
function _getSlippageMultiplier(
Types.OptionSeries memory _optionSeries,
uint256 _amount,
int256 _optionDelta,
bool _isSell,
int256 _netDhvExposure
) internal view returns (uint256 slippageMultiplier) {
if (slippageGradient == 0) {
slippageMultiplier = ONE_SCALE;
return slippageMultiplier;
}
int256 newExposureExponent = _isSell
? _netDhvExposure + int256(_amount)
: _netDhvExposure - int256(_amount);
int256 oldExposureExponent = _netDhvExposure;
uint256 modifiedSlippageGradient;
uint256 deltaBandIndex = (uint256(_optionDelta.abs()) * 100) / deltaBandWidth;
(uint16 tenorIndex, int256 remainder) = _getTenorIndex(_optionSeries.expiration);
if (_optionDelta < 0) {
modifiedSlippageGradient = slippageGradient.mul(
_interpolateSlippageGradient(tenorIndex, remainder, true, deltaBandIndex)
);
} else {
modifiedSlippageGradient = slippageGradient.mul(
_interpolateSlippageGradient(tenorIndex, remainder, false, deltaBandIndex)
);
}
int256 slippageFactor = int256(ONE_SCALE + modifiedSlippageGradient);
if (_isSell) {
slippageMultiplier = uint256(
(slippageFactor.pow(-oldExposureExponent) - slippageFactor.pow(-newExposureExponent)).div(
slippageFactor.ln()
)
).div(_amount);
} else {
slippageMultiplier = uint256(
(slippageFactor.pow(-newExposureExponent) - slippageFactor.pow(-oldExposureExponent)).div(
slippageFactor.ln()
)
).div(_amount);
}
}
function _getSpreadValue(
bool _isSell,
Types.OptionSeries memory _optionSeries,
uint256 _amount,
int256 _optionDelta,
int256 _netDhvExposure,
uint256 _underlyingPrice
) internal view returns (int256 spreadPremium) {
uint256 time = (_optionSeries.expiration - block.timestamp).div(ONE_YEAR_SECONDS);
uint256 deltaBandIndex = (uint256(_optionDelta.abs()) * 100) / deltaBandWidth;
(uint16 tenorIndex, int256 remainder) = _getTenorIndex(_optionSeries.expiration);
if (!_isSell) {
spreadPremium += int(
_getCollateralLendingPremium(
_optionSeries,
_amount,
_optionDelta,
_netDhvExposure,
time,
deltaBandIndex,
tenorIndex,
remainder
)
);
}
spreadPremium += _getDeltaBorrowPremium(
_isSell,
_amount,
_optionDelta,
time,
deltaBandIndex,
_underlyingPrice,
tenorIndex,
remainder
);
}
function _getCollateralLendingPremium(
Types.OptionSeries memory _optionSeries,
uint _amount,
int256 _optionDelta,
int256 _netDhvExposure,
uint256 _time,
uint256 _deltaBandIndex,
uint16 _tenorIndex,
int256 _remainder
) internal view returns (uint256 collateralLendingPremium) {
uint256 netShortContracts;
if (_netDhvExposure <= 0) {
netShortContracts = _amount;
} else {
netShortContracts = int256(_amount) - _netDhvExposure < 0
? 0
: _amount - uint256(_netDhvExposure);
}
if (_optionSeries.collateral == collateralAsset) {
uint256 collateralToLend = _getCollateralRequirements(_optionSeries, netShortContracts);
collateralLendingPremium =
((ONE_SCALE + (collateralLendingRate * ONE_SCALE) / SIX_DPS).pow(_time)).mul(collateralToLend) -
collateralToLend;
if (_optionDelta < 0) {
collateralLendingPremium = collateralLendingPremium.mul(
_interpolateSpreadCollateral(_tenorIndex, _remainder, true, _deltaBandIndex)
);
} else {
collateralLendingPremium = collateralLendingPremium.mul(
_interpolateSpreadCollateral(_tenorIndex, _remainder, false, _deltaBandIndex)
);
}
}
}
function _getDeltaBorrowPremium(
bool _isSell,
uint _amount,
int256 _optionDelta,
uint256 _time,
uint256 _deltaBandIndex,
uint256 _underlyingPrice,
uint16 _tenorIndex,
int256 _remainder
) internal view returns (int256 deltaBorrowPremium) {
int256 dollarDelta = int256(uint256(_optionDelta.abs()).mul(_amount).mul(_underlyingPrice));
if (_optionDelta < 0) {
deltaBorrowPremium =
dollarDelta.mul(
(ONE_SCALE_INT +
((_isSell ? deltaBorrowRates.sellLong : deltaBorrowRates.buyShort) * ONE_SCALE_INT) /
SIX_DPS_INT).pow(int(_time))
) -
dollarDelta;
deltaBorrowPremium = deltaBorrowPremium.mul(
_interpolateSpreadDelta(_tenorIndex, _remainder, true, _deltaBandIndex)
);
} else {
deltaBorrowPremium =
dollarDelta.mul(
(ONE_SCALE_INT +
((_isSell ? deltaBorrowRates.sellShort : deltaBorrowRates.buyLong) * ONE_SCALE_INT) /
SIX_DPS_INT).pow(int(_time))
) -
dollarDelta;
deltaBorrowPremium = deltaBorrowPremium.mul(
_interpolateSpreadDelta(_tenorIndex, _remainder, false, _deltaBandIndex)
);
}
}
function _getTenorIndex(
uint256 _expiration
) internal view returns (uint16 tenorIndex, int256 remainder) {
uint unroundedTenorIndex = (((((_expiration - block.timestamp) * 1e18).sqrt()) *
(numberOfTenors - 1)) / maxTenorValue);
require(unroundedTenorIndex / 1e18 <= 65535, "tenor index overflow");
tenorIndex = uint16(unroundedTenorIndex / 1e18);
remainder = int256(unroundedTenorIndex - tenorIndex * 1e18);
}
function _interpolateSlippageGradient(
uint16 _tenor,
int256 _remainder,
bool _isPut,
uint256 _deltaBand
) internal view returns (uint80 slippageGradientMultiplier) {
if (_isPut) {
int80 y1 = tenorPricingParams[_tenor].putSlippageGradientMultipliers[_deltaBand];
if (_remainder == 0) {
return uint80(y1);
}
int80 y2 = tenorPricingParams[_tenor + 1].putSlippageGradientMultipliers[_deltaBand];
return uint80(int80(y1 + _remainder.mul(y2 - y1)));
} else {
int80 y1 = tenorPricingParams[_tenor].callSlippageGradientMultipliers[_deltaBand];
if (_remainder == 0) {
return uint80(y1);
}
int80 y2 = tenorPricingParams[_tenor + 1].callSlippageGradientMultipliers[_deltaBand];
return uint80(int80(y1 + _remainder.mul(y2 - y1)));
}
}
function _interpolateSpreadCollateral(
uint16 _tenor,
int256 _remainder,
bool _isPut,
uint256 _deltaBand
) internal view returns (uint80 spreadCollateralMultiplier) {
if (_isPut) {
int80 y1 = tenorPricingParams[_tenor].putSpreadCollateralMultipliers[_deltaBand];
if (_remainder == 0) {
return uint80(y1);
}
int80 y2 = tenorPricingParams[_tenor + 1].putSpreadCollateralMultipliers[_deltaBand];
return uint80(int80(y1 + _remainder.mul(y2 - y1)));
} else {
int80 y1 = tenorPricingParams[_tenor].callSpreadCollateralMultipliers[_deltaBand];
if (_remainder == 0) {
return uint80(y1);
}
int80 y2 = tenorPricingParams[_tenor + 1].callSpreadCollateralMultipliers[_deltaBand];
return uint80(int80(y1 + _remainder.mul(y2 - y1)));
}
}
function _interpolateSpreadDelta(
uint16 _tenor,
int256 _remainder,
bool _isPut,
uint256 _deltaBand
) internal view returns (int80 spreadDeltaMultiplier) {
if (_isPut) {
int80 y1 = tenorPricingParams[_tenor].putSpreadDeltaMultipliers[_deltaBand];
if (_remainder == 0) {
return y1;
}
int80 y2 = tenorPricingParams[_tenor + 1].putSpreadDeltaMultipliers[_deltaBand];
return int80(y1 + _remainder.mul(y2 - y1));
} else {
int80 y1 = tenorPricingParams[_tenor].callSpreadDeltaMultipliers[_deltaBand];
if (_remainder == 0) {
return y1;
}
int80 y2 = tenorPricingParams[_tenor + 1].callSpreadDeltaMultipliers[_deltaBand];
return int80(y1 + _remainder.mul(y2 - y1));
}
}
function _getCollateralRequirements(
Types.OptionSeries memory _optionSeries,
uint256 _amount
) internal view returns (uint256) {
IMarginCalculator marginCalc = IMarginCalculator(addressBook.getMarginCalculator());
return
marginCalc.getNakedMarginRequired(
_optionSeries.underlying,
_optionSeries.strikeAsset,
_optionSeries.collateral,
_amount / SCALE_FROM,
_optionSeries.strike / SCALE_FROM,
IOracle(addressBook.getOracle()).getPrice(_optionSeries.underlying),
_optionSeries.expiration,
18,
_optionSeries.isPut
);
}
function _isExchangePaused() internal view {
if (!OptionExchange(protocol.optionExchange()).paused()) {
revert CustomErrors.ExchangeNotPaused();
}
}
}
文件 6 的 44:BlackScholes.sol
pragma solidity >=0.8.0;
import "prb-math/contracts/PRBMathSD59x18.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
import { NormalDist } from "./NormalDist.sol";
library BlackScholes {
using PRBMathSD59x18 for int256;
using PRBMathSD59x18 for int8;
using PRBMathUD60x18 for uint256;
uint256 private constant ONE_YEAR_SECONDS = 31557600;
uint256 private constant ONE = 1000000000000000000;
uint256 private constant TWO = 2000000000000000000;
struct Intermediates {
uint256 d1Denominator;
int256 d1;
int256 eToNegRT;
}
function callOptionPrice(
int256 d1,
int256 d1Denominator,
int256 price,
int256 strike,
int256 eToNegRT
) public pure returns (uint256) {
int256 d2 = d1 - d1Denominator;
int256 cdfD1 = NormalDist.cdf(d1);
int256 cdfD2 = NormalDist.cdf(d2);
int256 priceCdf = price.mul(cdfD1);
int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2);
assert(priceCdf >= strikeBy);
return uint256(priceCdf - strikeBy);
}
function callOptionPriceGreeks(
int256 d1,
int256 d1Denominator,
int256 price,
int256 strike,
int256 eToNegRT
) public pure returns (uint256 quote, int256 delta) {
int256 d2 = d1 - d1Denominator;
int256 cdfD1 = NormalDist.cdf(d1);
int256 cdfD2 = NormalDist.cdf(d2);
int256 priceCdf = price.mul(cdfD1);
int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2);
assert(priceCdf >= strikeBy);
quote = uint256(priceCdf - strikeBy);
delta = cdfD1;
}
function putOptionPriceGreeks(
int256 d1,
int256 d1Denominator,
int256 price,
int256 strike,
int256 eToNegRT
) public pure returns (uint256 quote, int256 delta) {
int256 d2 = d1Denominator - d1;
int256 cdfD1 = NormalDist.cdf(-d1);
int256 cdfD2 = NormalDist.cdf(d2);
int256 priceCdf = price.mul(cdfD1);
int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2);
assert(strikeBy >= priceCdf);
quote = uint256(strikeBy - priceCdf);
delta = -cdfD1;
}
function putOptionPrice(
int256 d1,
int256 d1Denominator,
int256 price,
int256 strike,
int256 eToNegRT
) public pure returns (uint256) {
int256 d2 = d1Denominator - d1;
int256 cdfD1 = NormalDist.cdf(-d1);
int256 cdfD2 = NormalDist.cdf(d2);
int256 priceCdf = price.mul(cdfD1);
int256 strikeBy = strike.mul(eToNegRT).mul(cdfD2);
assert(strikeBy >= priceCdf);
return uint256(strikeBy - priceCdf);
}
function getTimeStamp() private view returns (uint256) {
return block.timestamp;
}
function getD1(
uint256 price,
uint256 strike,
uint256 time,
uint256 vol,
uint256 rfr
) private pure returns (int256 d1, uint256 d1Denominator) {
uint256 d1Right = (vol.mul(vol).div(TWO) + rfr).mul(time);
int256 d1Left = int256(price.div(strike)).ln();
int256 d1Numerator = d1Left + int256(d1Right);
d1Denominator = vol.mul(time.sqrt());
d1 = d1Numerator.div(int256(d1Denominator));
}
function getIntermediates(
uint256 price,
uint256 strike,
uint256 time,
uint256 vol,
uint256 rfr
) private pure returns (Intermediates memory) {
(int256 d1, uint256 d1Denominator) = getD1(price, strike, time, vol, rfr);
return
Intermediates({
d1Denominator: d1Denominator,
d1: d1,
eToNegRT: (int256(rfr).mul(int256(time)).mul(-int256(ONE))).exp()
});
}
function blackScholesCalc(
uint256 price,
uint256 strike,
uint256 expiration,
uint256 vol,
uint256 rfr,
bool isPut
) public view returns (uint256) {
uint256 time = (expiration - getTimeStamp()).div(ONE_YEAR_SECONDS);
Intermediates memory i = getIntermediates(price, strike, time, vol, rfr);
if (!isPut) {
return
callOptionPrice(
int256(i.d1),
int256(i.d1Denominator),
int256(price),
int256(strike),
i.eToNegRT
);
} else {
return
putOptionPrice(
int256(i.d1),
int256(i.d1Denominator),
int256(price),
int256(strike),
i.eToNegRT
);
}
}
function blackScholesCalcGreeks(
uint256 price,
uint256 strike,
uint256 expiration,
uint256 vol,
uint256 rfr,
bool isPut
) public view returns (uint256 quote, int256 delta) {
uint256 time = (expiration - getTimeStamp()).div(ONE_YEAR_SECONDS);
Intermediates memory i = getIntermediates(price, strike, time, vol, rfr);
if (!isPut) {
return
callOptionPriceGreeks(
int256(i.d1),
int256(i.d1Denominator),
int256(price),
int256(strike),
i.eToNegRT
);
} else {
return
putOptionPriceGreeks(
int256(i.d1),
int256(i.d1Denominator),
int256(price),
int256(strike),
i.eToNegRT
);
}
}
function getDelta(
uint256 price,
uint256 strike,
uint256 expiration,
uint256 vol,
uint256 rfr,
bool isPut
) public view returns (int256) {
uint256 time = (expiration - getTimeStamp()).div(ONE_YEAR_SECONDS);
(int256 d1, ) = getD1(price, strike, time, vol, rfr);
if (!isPut) {
return NormalDist.cdf(d1);
} else {
return -NormalDist.cdf(-d1);
}
}
}
文件 7 的 44:CombinedActions.sol
pragma solidity >=0.8.4;
import "./Types.sol";
import "./RyskActions.sol";
import { IController } from "../interfaces/GammaInterface.sol";
library CombinedActions {
enum OperationType {
OPYN,
RYSK
}
struct OperationProcedures {
OperationType operation;
CombinedActions.ActionArgs[] operationQueue;
}
struct ActionArgs {
uint256 actionType;
address owner;
address secondAddress;
address asset;
uint256 vaultId;
uint256 amount;
Types.OptionSeries optionSeries;
uint256 indexOrAcceptablePremium;
bytes data;
}
function _parseOpynArgs(ActionArgs memory _args) internal pure returns (IController.ActionArgs memory) {
return IController.ActionArgs({
actionType: IController.ActionType(_args.actionType),
owner: _args.owner,
secondAddress: _args.secondAddress,
asset: _args.asset,
vaultId: _args.vaultId,
amount: _args.amount,
index: _args.indexOrAcceptablePremium,
data: _args.data
});
}
function _parseRyskArgs(ActionArgs memory _args) internal pure returns (RyskActions.ActionArgs memory) {
return RyskActions.ActionArgs({
actionType: RyskActions.ActionType(_args.actionType),
secondAddress: _args.secondAddress,
asset: _args.asset,
vaultId: _args.vaultId,
amount: _args.amount,
optionSeries: _args.optionSeries,
acceptablePremium: _args.indexOrAcceptablePremium,
data: _args.data
});
}
}
文件 8 的 44:Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
文件 9 的 44:CustomErrors.sol
pragma solidity >=0.8.0;
interface CustomErrors {
error NotKeeper();
error IVNotFound();
error NotHandler();
error NotUpdater();
error VaultExpired();
error InvalidInput();
error InvalidPrice();
error InvalidBuyer();
error InvalidOrder();
error OrderExpired();
error InvalidExpiry();
error InvalidAmount();
error TradingPaused();
error InvalidAddress();
error IssuanceFailed();
error EpochNotClosed();
error NoPositionsOpen();
error InvalidDecimals();
error InActivePosition();
error NoActivePosition();
error TradingNotPaused();
error NotLiquidityPool();
error UnauthorizedExit();
error UnapprovedSeries();
error SeriesNotBuyable();
error ExchangeNotPaused();
error DeltaNotDecreased();
error NonExistentOtoken();
error SeriesNotSellable();
error InvalidGmxCallback();
error GmxCallbackPending();
error OrderExpiryTooLong();
error InvalidShareAmount();
error ExistingWithdrawal();
error TotalSupplyReached();
error StrikeAssetInvalid();
error InsufficientBalance();
error OptionStrikeInvalid();
error OptionExpiryInvalid();
error RangeOrderNotFilled();
error NoExistingWithdrawal();
error SpotMovedBeyondRange();
error ReactorAlreadyExists();
error UnauthorizedFulfill();
error NonWhitelistedOtoken();
error CollateralAssetInvalid();
error UnderlyingAssetInvalid();
error CollateralAmountInvalid();
error WithdrawExceedsLiquidity();
error InsufficientShareBalance();
error MaxLiquidityBufferReached();
error LiabilitiesGreaterThanAssets();
error CustomOrderInsufficientPrice();
error CustomOrderInvalidDeltaValue();
error DeltaQuoteError(uint256 quote, int256 delta);
error TimeDeltaExceedsThreshold(uint256 timeDelta);
error PriceDeltaExceedsThreshold(uint256 priceDelta);
error StrikeAmountExceedsLiquidity(uint256 strikeAmount, uint256 strikeLiquidity);
error MinStrikeAmountExceedsLiquidity(uint256 strikeAmount, uint256 strikeAmountMin);
error UnderlyingAmountExceedsLiquidity(uint256 underlyingAmount, uint256 underlyingLiquidity);
error MinUnderlyingAmountExceedsLiquidity(uint256 underlyingAmount, uint256 underlyingAmountMin);
}
文件 10 的 44:ERC20.sol
pragma solidity >=0.8.0;
abstract contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
string public name;
string public symbol;
uint8 public immutable decimals;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
),
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
文件 11 的 44:EnumerableSet.sol
pragma solidity ^0.8.0;
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping(bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
set._values[toDeleteIndex] = lastValue;
set._indexes[lastValue] = valueIndex;
}
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
}
文件 12 的 44:GammaInterface.sol
pragma solidity >=0.8.4;
library GammaTypes {
struct Vault {
address[] shortOtokens;
address[] longOtokens;
address[] collateralAssets;
uint256[] shortAmounts;
uint256[] longAmounts;
uint256[] collateralAmounts;
}
struct VaultLiquidationDetails {
address series;
uint128 shortAmount;
uint128 collateralAmount;
}
}
interface IOtoken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
}
interface IOtokenFactory {
function getOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
function createOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external returns (address);
function getTargetOtokenAddress(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
event OtokenCreated(
address tokenAddress,
address creator,
address indexed underlying,
address indexed strike,
address indexed collateral,
uint256 strikePrice,
uint256 expiry,
bool isPut
);
}
interface IController {
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
ActionType actionType;
address owner;
address secondAddress;
address asset;
uint256 vaultId;
uint256 amount;
uint256 index;
bytes data;
}
struct RedeemArgs {
address receiver;
address otoken;
uint256 amount;
}
function setOperator(address _operator, bool _isOperator) external;
function getPayout(address _otoken, uint256 _amount) external view returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner) external view returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId)
external
view
returns (GammaTypes.Vault memory);
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256);
function isOperator(address _owner, address _operator) external view returns (bool);
function isSettlementAllowed(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool);
function clearVaultLiquidationDetails(uint256 _vaultId) external;
function getVaultLiquidationDetails(address _owner, uint256 _vaultId)
external
view
returns (
address,
uint256,
uint256
);
}
文件 13 的 44:IAccounting.sol
pragma solidity >=0.8.9;
interface IAccounting {
struct DepositReceipt {
uint128 epoch;
uint128 amount;
uint256 unredeemedShares;
}
struct WithdrawalReceipt {
uint128 epoch;
uint128 shares;
}
function deposit(address depositor, uint256 _amount)
external
returns (uint256 depositAmount, uint256 unredeemedShares);
function redeem(address redeemer, uint256 shares)
external
returns (uint256 toRedeem, DepositReceipt memory depositReceipt);
function initiateWithdraw(address withdrawer, uint256 shares)
external
returns (WithdrawalReceipt memory withdrawalReceipt);
function completeWithdraw(address withdrawer)
external
returns (
uint256 withdrawalAmount,
uint256 withdrawalShares,
WithdrawalReceipt memory withdrawalReceipt
);
function executeEpochCalculation(
uint256 totalSupply,
uint256 assets,
int256 liabilities
)
external
view
returns (
uint256 newPricePerShareDeposit,
uint256 newPricePerShareWithdrawal,
uint256 sharesToMint,
uint256 totalWithdrawAmount,
uint256 amountNeeded
);
function sharesForAmount(uint256 _amount, uint256 assetPerShare)
external
view
returns (uint256 shares);
}
文件 14 的 44:IAlphaPortfolioValuesFeed.sol
pragma solidity 0.8.9;
import "../libraries/Types.sol";
import "../AlphaPortfolioValuesFeed.sol";
interface IAlphaPortfolioValuesFeed {
function requestPortfolioData(address _underlying, address _strike)
external
returns (bytes32 requestId);
function updateStores(Types.OptionSeries memory _optionSeries, int256 _shortExposure, int256 _longExposure, address _seriesAddress) external;
function netDhvExposure(bytes32 oHash) external view returns (int256);
function getPortfolioValues(address underlying, address strike)
external
view
returns (Types.PortfolioValues memory);
function storesForAddress(address seriesAddress) external view returns (AlphaPortfolioValuesFeed.OptionStores memory);
}
文件 15 的 44:IAuthority.sol
pragma solidity >=0.8.0;
interface IAuthority {
event GovernorPushed(address indexed from, address indexed to);
event GuardianPushed(address indexed to);
event ManagerPushed(address indexed from, address indexed to);
event GovernorPulled(address indexed from, address indexed to);
event GuardianRevoked(address indexed to);
event ManagerPulled(address indexed from, address indexed to);
function governor() external view returns (address);
function guardian(address _target) external view returns (bool);
function manager() external view returns (address);
function pullManager() external;
}
文件 16 的 44:IHedgingReactor.sol
pragma solidity >=0.8.9;
interface IHedgingReactor {
function hedgeDelta(int256 delta) external returns (int256);
function getDelta() external view returns (int256 delta);
function getPoolDenominatedValue() external view returns (uint256 value);
function withdraw(uint256 amount) external returns (uint256);
function update() external returns (uint256);
}
文件 17 的 44:ILiquidityPool.sol
pragma solidity >=0.8.9;
import { Types } from "../libraries/Types.sol";
import "../interfaces/IOptionRegistry.sol";
import "../interfaces/IAccounting.sol";
import "../interfaces/I_ERC20.sol";
interface ILiquidityPool is I_ERC20 {
function strikeAsset() external view returns (address);
function underlyingAsset() external view returns (address);
function collateralAsset() external view returns (address);
function collateralAllocated() external view returns (uint256);
function ephemeralLiabilities() external view returns (int256);
function ephemeralDelta() external view returns (int256);
function depositEpoch() external view returns (uint256);
function withdrawalEpoch() external view returns (uint256);
function depositEpochPricePerShare(uint256 epoch) external view returns (uint256 price);
function withdrawalEpochPricePerShare(uint256 epoch) external view returns (uint256 price);
function depositReceipts(address depositor)
external
view
returns (IAccounting.DepositReceipt memory);
function withdrawalReceipts(address withdrawer)
external
view
returns (IAccounting.WithdrawalReceipt memory);
function pendingDeposits() external view returns (uint256);
function pendingWithdrawals() external view returns (uint256);
function partitionedFunds() external view returns (uint256);
function bufferPercentage() external view returns (uint256);
function collateralCap() external view returns (uint256);
function adjustVariables(uint256 collateralAmount, uint256 optionsValue, int256 delta, bool isSale) external;
function handlerIssue(Types.OptionSeries memory optionSeries) external returns (address);
function resetEphemeralValues() external;
function rebalancePortfolioDelta(int256 delta, uint256 index) external;
function getAssets() external view returns (uint256);
function redeem(uint256) external returns (uint256);
function handlerWriteOption(
Types.OptionSeries memory optionSeries,
address seriesAddress,
uint256 amount,
IOptionRegistry optionRegistry,
uint256 premium,
int256 delta,
address recipient
) external returns (uint256);
function handlerBuybackOption(
Types.OptionSeries memory optionSeries,
uint256 amount,
IOptionRegistry optionRegistry,
address seriesAddress,
uint256 premium,
int256 delta,
address seller
) external returns (uint256);
function handlerIssueAndWriteOption(
Types.OptionSeries memory optionSeries,
uint256 amount,
uint256 premium,
int256 delta,
address recipient
) external returns (uint256, address);
function getPortfolioDelta() external view returns (int256);
function quotePriceWithUtilizationGreeks(
Types.OptionSeries memory optionSeries,
uint256 amount,
bool toBuy
) external view returns (uint256 quote, int256 delta);
function checkBuffer() external view returns (int256 bufferRemaining);
function getBalance(address asset) external view returns (uint256);
}
文件 18 的 44:IMarginCalculator.sol
pragma solidity 0.8.9;
interface IMarginCalculator {
function getNakedMarginRequired(
address _underlying,
address _strike,
address _collateral,
uint256 _shortAmount,
uint256 _strikePrice,
uint256 _underlyingPrice,
uint256 _shortExpiryTimestamp,
uint256 _collateralDecimals,
bool _isPut
) external view returns (uint256);
}
文件 19 的 44:IOptionRegistry.sol
pragma solidity >=0.8.9;
import { Types } from "../libraries/Types.sol";
interface IOptionRegistry {
function issue(Types.OptionSeries memory optionSeries) external returns (address);
function open(
address _series,
uint256 amount,
uint256 collateralAmount
) external returns (bool, uint256);
function close(address _series, uint256 amount) external returns (bool, uint256);
function settle(address _series)
external
returns (
bool success,
uint256 collatReturned,
uint256 collatLost,
uint256 amountShort
);
function getCollateral(Types.OptionSeries memory series, uint256 amount)
external
view
returns (uint256);
function getOtoken(
address underlying,
address strikeAsset,
uint256 expiration,
bool isPut,
uint256 strike,
address collateral
) external view returns (address);
function getSeriesInfo(address series) external view returns (Types.OptionSeries memory);
function getSeries(Types.OptionSeries memory _series) external view returns (address);
function vaultIds(address series) external view returns (uint256);
function addressBook() external view returns (address);
}
文件 20 的 44:IOracle.sol
pragma solidity >=0.8.0;
interface IOracle {
function getPrice(address _asset) external view returns (uint256);
function getExpiryPrice(address _asset, uint256 _expiryTimestamp)
external
view
returns (uint256, bool);
function isLockingPeriodOver(address _asset, uint256 _expiryTimestamp)
external
view
returns (bool);
}
文件 21 的 44:IPortfolioValuesFeed.sol
pragma solidity 0.8.9;
import "../libraries/Types.sol";
interface IPortfolioValuesFeed {
struct OptionStore {
Types.OptionSeries optionSeries;
int256 shortExposure;
int256 longExposure;
}
function requestPortfolioData(address _underlying, address _strike)
external
returns (bytes32 requestId);
function updateStores(Types.OptionSeries memory _optionSeries, int256 _shortExposure, int256 _longExposure, address _seriesAddress) external;
function getPortfolioValues(address underlying, address strike)
external
view
returns (Types.PortfolioValues memory);
}
文件 22 的 44:ISwapRouter.sol
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
文件 23 的 44:IUniswapV3SwapCallback.sol
pragma solidity >=0.5.0;
interface IUniswapV3SwapCallback {
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
文件 24 的 44:IWhitelist.sol
pragma solidity 0.8.9;
interface IWhitelist {
function addressBook() external view returns (address);
function isWhitelistedProduct(
address _underlying,
address _strike,
address _collateral,
bool _isPut
) external view returns (bool);
function isWhitelistedCollateral(address _collateral) external view returns (bool);
function isCoveredWhitelistedCollateral(
address _collateral,
address _underlying,
bool _isPut
) external view returns (bool);
function isNakedWhitelistedCollateral(
address _collateral,
address _underlying,
bool _isPut
) external view returns (bool);
function isWhitelistedOtoken(address _otoken) external view returns (bool);
}
文件 25 的 44:I_ERC20.sol
pragma solidity ^0.8.0;
interface I_ERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
文件 26 的 44:LiquidityPool.sol
pragma solidity >=0.8.0;
import "./Protocol.sol";
import "./PriceFeed.sol";
import "./VolatilityFeed.sol";
import "./tokens/ERC20.sol";
import "./utils/ReentrancyGuard.sol";
import "./libraries/BlackScholes.sol";
import "./libraries/CustomErrors.sol";
import "./libraries/AccessControl.sol";
import "./libraries/OptionsCompute.sol";
import "./libraries/SafeTransferLib.sol";
import "./interfaces/IAccounting.sol";
import "./interfaces/IOptionRegistry.sol";
import "./interfaces/IHedgingReactor.sol";
import "./interfaces/IPortfolioValuesFeed.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
contract LiquidityPool is ERC20, AccessControl, ReentrancyGuard, Pausable {
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
Protocol public immutable protocol;
address public immutable strikeAsset;
address public immutable underlyingAsset;
address public immutable collateralAsset;
uint256 public collateralAllocated;
int256 public ephemeralLiabilities;
int256 public ephemeralDelta;
uint256 public depositEpoch;
uint256 public withdrawalEpoch;
mapping(uint256 => uint256) public depositEpochPricePerShare;
mapping(uint256 => uint256) public withdrawalEpochPricePerShare;
mapping(address => IAccounting.DepositReceipt) public depositReceipts;
mapping(address => IAccounting.WithdrawalReceipt) public withdrawalReceipts;
uint256 public pendingDeposits;
uint256 public pendingWithdrawals;
uint256 public partitionedFunds;
uint256 public bufferPercentage = 5000;
address[] public hedgingReactors;
uint256 public collateralCap = type(uint256).max;
Types.OptionParams public optionParams;
uint256 public riskFreeRate;
mapping(address => bool) public handler;
bool public isTradingPaused;
uint256 public maxTimeDeviationThreshold = 600;
uint256 public maxPriceDeviationThreshold = 1e18;
mapping(address => bool) public keeper;
uint256 private constant MAX_BPS = 10_000;
event DepositEpochExecuted(uint256 epoch);
event WithdrawalEpochExecuted(uint256 epoch);
event Withdraw(address recipient, uint256 amount, uint256 shares);
event Deposit(address recipient, uint256 amount, uint256 epoch);
event Redeem(address recipient, uint256 amount, uint256 epoch);
event InitiateWithdraw(address recipient, uint256 amount, uint256 epoch);
event WriteOption(address series, uint256 amount, uint256 premium, uint256 escrow, address buyer);
event RebalancePortfolioDelta(int256 deltaChange);
event TradingPaused();
event TradingUnpaused();
event SettleVault(
address series,
uint256 collateralReturned,
uint256 collateralLost,
address closer
);
event BuybackOption(
address series,
uint256 amount,
uint256 premium,
uint256 escrowReturned,
address seller
);
constructor(
address _protocol,
address _strikeAsset,
address _underlyingAsset,
address _collateralAsset,
uint256 rfr,
string memory name,
string memory symbol,
Types.OptionParams memory _optionParams,
address _authority
) ERC20(name, symbol, 18) AccessControl(IAuthority(_authority)) {
if (ERC20(_collateralAsset).decimals() > 18) {
revert CustomErrors.InvalidDecimals();
}
strikeAsset = _strikeAsset;
riskFreeRate = rfr;
underlyingAsset = _underlyingAsset;
collateralAsset = _collateralAsset;
protocol = Protocol(_protocol);
optionParams = _optionParams;
depositEpochPricePerShare[0] = 1e18;
withdrawalEpochPricePerShare[0] = 1e18;
depositEpoch++;
withdrawalEpoch++;
}
function pause() external {
_onlyGuardian();
_pause();
}
function pauseUnpauseTrading(bool _pause) external {
_onlyGuardian();
isTradingPaused = _pause;
if (_pause) {
emit TradingPaused();
} else {
emit TradingUnpaused();
}
}
function unpause() external {
_onlyGuardian();
_unpause();
}
function setHedgingReactorAddress(address _reactorAddress) external {
_onlyGovernor();
if (_reactorAddress == address(0)) {
revert CustomErrors.InvalidAddress();
}
uint256 arrayLength = hedgingReactors.length;
for (uint256 i = 0; i < arrayLength; i++) {
if (hedgingReactors[i] == _reactorAddress) {
revert CustomErrors.ReactorAlreadyExists();
}
}
hedgingReactors.push(_reactorAddress);
SafeTransferLib.safeApprove(ERC20(collateralAsset), _reactorAddress, type(uint256).max);
}
function removeHedgingReactorAddress(uint256 _index, bool _override) external {
_onlyGovernor();
address[] memory hedgingReactors_ = hedgingReactors;
address reactorAddress = hedgingReactors_[_index];
if (!_override) {
IHedgingReactor reactor = IHedgingReactor(reactorAddress);
int256 delta = reactor.getDelta();
if (delta != 0) {
reactor.hedgeDelta(delta);
}
reactor.withdraw(type(uint256).max);
}
SafeTransferLib.safeApprove(ERC20(collateralAsset), reactorAddress, 0);
uint256 maxIndex = hedgingReactors_.length - 1;
for (uint256 i = _index; i < maxIndex; i++) {
hedgingReactors[i] = hedgingReactors_[i + 1];
}
hedgingReactors.pop();
}
function getHedgingReactors() external view returns (address[] memory) {
return hedgingReactors;
}
function setNewOptionParams(
uint128 _newMinCallStrike,
uint128 _newMaxCallStrike,
uint128 _newMinPutStrike,
uint128 _newMaxPutStrike,
uint128 _newMinExpiry,
uint128 _newMaxExpiry
) external {
_onlyManager();
optionParams.minCallStrikePrice = _newMinCallStrike;
optionParams.maxCallStrikePrice = _newMaxCallStrike;
optionParams.minPutStrikePrice = _newMinPutStrike;
optionParams.maxPutStrikePrice = _newMaxPutStrike;
optionParams.minExpiry = _newMinExpiry;
optionParams.maxExpiry = _newMaxExpiry;
}
function setCollateralCap(uint256 _collateralCap) external {
_onlyGovernor();
collateralCap = _collateralCap;
}
function setBufferPercentage(uint256 _bufferPercentage) external {
_onlyGovernor();
bufferPercentage = _bufferPercentage;
}
function setRiskFreeRate(uint256 _riskFreeRate) external {
_onlyGovernor();
riskFreeRate = _riskFreeRate;
}
function setMaxTimeDeviationThreshold(uint256 _maxTimeDeviationThreshold) external {
_onlyGovernor();
maxTimeDeviationThreshold = _maxTimeDeviationThreshold;
}
function setMaxPriceDeviationThreshold(uint256 _maxPriceDeviationThreshold) external {
_onlyGovernor();
maxPriceDeviationThreshold = _maxPriceDeviationThreshold;
}
function changeHandler(address _handler, bool auth) external {
_onlyGovernor();
if (_handler == address(0)) {
revert CustomErrors.InvalidAddress();
}
handler[_handler] = auth;
}
function setKeeper(address _keeper, bool _auth) external {
_onlyGovernor();
if (_keeper == address(0)) {
revert CustomErrors.InvalidAddress();
}
keeper[_keeper] = _auth;
}
function rebalancePortfolioDelta(int256 delta, uint256 reactorIndex) external {
_onlyManager();
IHedgingReactor(hedgingReactors[reactorIndex]).hedgeDelta(delta);
emit RebalancePortfolioDelta(delta);
}
function adjustCollateral(uint256 lpCollateralDifference, bool addToLpBalance) external {
IOptionRegistry optionRegistry = _getOptionRegistry();
require(msg.sender == address(optionRegistry));
if (addToLpBalance) {
collateralAllocated -= lpCollateralDifference;
} else {
SafeTransferLib.safeApprove(
ERC20(collateralAsset),
address(optionRegistry),
lpCollateralDifference
);
collateralAllocated += lpCollateralDifference;
}
}
function settleVault(address seriesAddress) external returns (uint256) {
_isKeeper();
(, uint256 collatReturned, uint256 collatLost, ) = _getOptionRegistry().settle(seriesAddress);
emit SettleVault(seriesAddress, collatReturned, collatLost, msg.sender);
_adjustVariables(collatReturned, collatLost, 0, false);
collateralAllocated -= collatLost;
return collatReturned;
}
function handlerIssue(Types.OptionSeries memory optionSeries) external returns (address) {
_isHandler();
return _issue(optionSeries, _getOptionRegistry());
}
function handlerWriteOption(
Types.OptionSeries memory optionSeries,
address seriesAddress,
uint256 amount,
IOptionRegistry optionRegistry,
uint256 premium,
int256 delta,
address recipient
) external returns (uint256) {
_isTradingNotPaused();
_isHandler();
return
_writeOption(
optionSeries,
seriesAddress,
amount,
optionRegistry,
premium,
delta,
checkBuffer(),
recipient
);
}
function handlerIssueAndWriteOption(
Types.OptionSeries memory optionSeries,
uint256 amount,
uint256 premium,
int256 delta,
address recipient
) external returns (uint256, address) {
_isTradingNotPaused();
_isHandler();
IOptionRegistry optionRegistry = _getOptionRegistry();
address seriesAddress = _issue(optionSeries, optionRegistry);
optionSeries = optionRegistry.getSeriesInfo(seriesAddress);
return (
_writeOption(
optionSeries,
seriesAddress,
amount,
optionRegistry,
premium,
delta,
checkBuffer(),
recipient
),
seriesAddress
);
}
function handlerBuybackOption(
Types.OptionSeries memory optionSeries,
uint256 amount,
IOptionRegistry optionRegistry,
address seriesAddress,
uint256 premium,
int256 delta,
address seller
) external returns (uint256) {
_isTradingNotPaused();
_isHandler();
return
_buybackOption(optionSeries, amount, optionRegistry, seriesAddress, premium, delta, seller);
}
function resetEphemeralValues() external {
require(msg.sender == address(_getPortfolioValuesFeed()));
delete ephemeralLiabilities;
delete ephemeralDelta;
}
function pauseTradingAndRequest() external returns (bytes32) {
_isKeeper();
isTradingPaused = true;
emit TradingPaused();
return _getPortfolioValuesFeed().requestPortfolioData(underlyingAsset, strikeAsset);
}
function executeEpochCalculation() external whenNotPaused {
_isKeeper();
if (!isTradingPaused) {
revert CustomErrors.TradingNotPaused();
}
(
uint256 newPricePerShareDeposit,
uint256 newPricePerShareWithdrawal,
uint256 sharesToMint,
uint256 totalWithdrawAmount,
uint256 amountNeeded
) = _getAccounting().executeEpochCalculation(totalSupply, _getAssets(), _getLiabilities());
depositEpochPricePerShare[depositEpoch] = newPricePerShareDeposit;
delete pendingDeposits;
emit DepositEpochExecuted(depositEpoch);
depositEpoch++;
isTradingPaused = false;
emit TradingUnpaused();
_mint(address(this), sharesToMint);
if (amountNeeded > 0) {
address[] memory hedgingReactors_ = hedgingReactors;
for (uint8 i = 0; i < hedgingReactors_.length; i++) {
amountNeeded -= IHedgingReactor(hedgingReactors_[i]).withdraw(amountNeeded);
if (amountNeeded <= 0) {
break;
}
}
if (amountNeeded > 0) {
return;
}
}
withdrawalEpochPricePerShare[withdrawalEpoch] = newPricePerShareWithdrawal;
partitionedFunds += totalWithdrawAmount;
emit WithdrawalEpochExecuted(withdrawalEpoch);
_burn(address(this), pendingWithdrawals);
delete pendingWithdrawals;
withdrawalEpoch++;
}
function deposit(uint256 _amount) external whenNotPaused nonReentrant returns (bool) {
if (_amount == 0) {
revert CustomErrors.InvalidAmount();
}
(uint256 depositAmount, uint256 unredeemedShares) = _getAccounting().deposit(msg.sender, _amount);
emit Deposit(msg.sender, _amount, depositEpoch);
depositReceipts[msg.sender] = IAccounting.DepositReceipt({
epoch: uint128(depositEpoch),
amount: uint128(depositAmount),
unredeemedShares: unredeemedShares
});
pendingDeposits += _amount;
SafeTransferLib.safeTransferFrom(collateralAsset, msg.sender, address(this), _amount);
return true;
}
function redeem(uint256 _shares) external nonReentrant returns (uint256) {
if (_shares == 0) {
revert CustomErrors.InvalidShareAmount();
}
return _redeem(_shares);
}
function initiateWithdraw(uint256 _shares) external whenNotPaused nonReentrant {
if (_shares == 0) {
revert CustomErrors.InvalidShareAmount();
}
IAccounting.DepositReceipt memory depositReceipt = depositReceipts[msg.sender];
if (depositReceipt.amount > 0 || depositReceipt.unredeemedShares > 0) {
_redeem(type(uint256).max);
}
IAccounting.WithdrawalReceipt memory withdrawalReceipt = _getAccounting().initiateWithdraw(
msg.sender,
_shares
);
withdrawalReceipts[msg.sender] = withdrawalReceipt;
pendingWithdrawals += _shares;
emit InitiateWithdraw(msg.sender, _shares, withdrawalEpoch);
transfer(address(this), _shares);
}
function completeWithdraw() external whenNotPaused nonReentrant returns (uint256) {
(
uint256 withdrawalAmount,
uint256 withdrawalShares,
IAccounting.WithdrawalReceipt memory withdrawalReceipt
) = _getAccounting().completeWithdraw(msg.sender);
withdrawalReceipts[msg.sender] = withdrawalReceipt;
emit Withdraw(msg.sender, withdrawalAmount, withdrawalShares);
partitionedFunds -= withdrawalAmount;
SafeTransferLib.safeTransfer(ERC20(collateralAsset), msg.sender, withdrawalAmount);
return withdrawalAmount;
}
function _getNormalizedBalance(address asset) internal view returns (uint256 normalizedBalance) {
normalizedBalance = OptionsCompute.convertFromDecimals(
ERC20(asset).balanceOf(address(this)) - partitionedFunds,
ERC20(asset).decimals()
);
}
function getBalance(address asset) public view returns (uint256) {
return ERC20(asset).balanceOf(address(this)) - partitionedFunds;
}
function getExternalDelta() public view returns (int256 externalDelta) {
address[] memory hedgingReactors_ = hedgingReactors;
for (uint8 i = 0; i < hedgingReactors_.length; i++) {
externalDelta += IHedgingReactor(hedgingReactors_[i]).getDelta();
}
}
function getPortfolioDelta() public view returns (int256) {
Types.PortfolioValues memory portfolioValues = _getPortfolioValuesFeed().getPortfolioValues(
underlyingAsset,
strikeAsset
);
OptionsCompute.validatePortfolioValues(
_getUnderlyingPrice(underlyingAsset, strikeAsset),
portfolioValues,
maxTimeDeviationThreshold,
maxPriceDeviationThreshold
);
return portfolioValues.delta + getExternalDelta() + ephemeralDelta;
}
function getImpliedVolatility(
bool isPut,
uint256 underlyingPrice,
uint256 strikePrice,
uint256 expiration
) public view returns (uint256) {
return getVolatilityFeed().getImpliedVolatility(isPut, underlyingPrice, strikePrice, expiration);
}
function getAssets() external view returns (uint256) {
return _getAssets();
}
function getNAV() external view returns (uint256) {
return _getNAV();
}
function _redeem(uint256 _shares) internal returns (uint256) {
(uint256 toRedeem, IAccounting.DepositReceipt memory depositReceipt) = _getAccounting().redeem(
msg.sender,
_shares
);
if (toRedeem == 0) {
return 0;
}
depositReceipts[msg.sender] = depositReceipt;
allowance[address(this)][msg.sender] = toRedeem;
emit Redeem(msg.sender, toRedeem, depositReceipt.epoch);
transferFrom(address(this), msg.sender, toRedeem);
return toRedeem;
}
function _getNAV() internal view returns (uint256) {
uint256 assets = _getAssets();
int256 liabilities = _getLiabilities();
if (int256(assets) < liabilities) {
revert CustomErrors.LiabilitiesGreaterThanAssets();
}
return uint256(int256(assets) - liabilities);
}
function _getAssets() internal view returns (uint256 assets) {
assets =
_getNormalizedBalance(collateralAsset) +
OptionsCompute.convertFromDecimals(collateralAllocated, ERC20(collateralAsset).decimals());
address[] memory hedgingReactors_ = hedgingReactors;
for (uint8 i = 0; i < hedgingReactors_.length; i++) {
assets += IHedgingReactor(hedgingReactors_[i]).getPoolDenominatedValue();
}
}
function _getLiabilities() internal view returns (int256 liabilities) {
Types.PortfolioValues memory portfolioValues = _getPortfolioValuesFeed().getPortfolioValues(
underlyingAsset,
strikeAsset
);
OptionsCompute.validatePortfolioValues(
_getUnderlyingPrice(underlyingAsset, strikeAsset),
portfolioValues,
maxTimeDeviationThreshold,
maxPriceDeviationThreshold
);
liabilities = portfolioValues.callPutsValue + ephemeralLiabilities;
}
function checkBuffer() public view returns (int256 bufferRemaining) {
uint256 collateralBalance = getBalance(collateralAsset);
uint256 collateralBuffer = (collateralAllocated * bufferPercentage) / MAX_BPS;
bufferRemaining = int256(collateralBalance) - int256(collateralBuffer);
}
function _issue(
Types.OptionSeries memory optionSeries,
IOptionRegistry optionRegistry
) internal returns (address series) {
if (optionSeries.collateral != collateralAsset) {
revert CustomErrors.CollateralAssetInvalid();
}
if (optionSeries.underlying != underlyingAsset) {
revert CustomErrors.UnderlyingAssetInvalid();
}
if (optionSeries.strikeAsset != strikeAsset) {
revert CustomErrors.StrikeAssetInvalid();
}
Types.OptionParams memory optionParams_ = optionParams;
if (
block.timestamp + optionParams_.minExpiry > optionSeries.expiration ||
optionSeries.expiration > block.timestamp + optionParams_.maxExpiry
) {
revert CustomErrors.OptionExpiryInvalid();
}
if (optionSeries.isPut) {
if (
optionParams_.minPutStrikePrice > optionSeries.strike ||
optionSeries.strike > optionParams_.maxPutStrikePrice
) {
revert CustomErrors.OptionStrikeInvalid();
}
} else {
if (
optionParams_.minCallStrikePrice > optionSeries.strike ||
optionSeries.strike > optionParams_.maxCallStrikePrice
) {
revert CustomErrors.OptionStrikeInvalid();
}
}
series = optionRegistry.issue(optionSeries);
if (series == address(0)) {
revert CustomErrors.IssuanceFailed();
}
}
function _writeOption(
Types.OptionSeries memory optionSeries,
address seriesAddress,
uint256 amount,
IOptionRegistry optionRegistry,
uint256 premium,
int256 delta,
int256 bufferRemaining,
address recipient
) internal returns (uint256) {
uint256 collateralAmount = optionRegistry.getCollateral(optionSeries, amount);
if (bufferRemaining < int256(collateralAmount)) {
revert CustomErrors.MaxLiquidityBufferReached();
}
ERC20(collateralAsset).approve(address(optionRegistry), collateralAmount);
(, collateralAmount) = optionRegistry.open(seriesAddress, amount, collateralAmount);
emit WriteOption(seriesAddress, amount, premium, collateralAmount, recipient);
optionSeries.strike = uint128(
OptionsCompute.convertFromDecimals(optionSeries.strike, ERC20(seriesAddress).decimals())
);
_adjustVariables(collateralAmount, premium, delta, true);
SafeTransferLib.safeTransfer(
ERC20(seriesAddress),
recipient,
OptionsCompute.convertToDecimals(amount, ERC20(seriesAddress).decimals())
);
return amount;
}
function _buybackOption(
Types.OptionSeries memory optionSeries,
uint256 amount,
IOptionRegistry optionRegistry,
address seriesAddress,
uint256 premium,
int256 delta,
address seller
) internal returns (uint256) {
SafeTransferLib.safeApprove(
ERC20(seriesAddress),
address(optionRegistry),
OptionsCompute.convertToDecimals(amount, ERC20(seriesAddress).decimals())
);
(, uint256 collateralReturned) = optionRegistry.close(seriesAddress, amount);
emit BuybackOption(seriesAddress, amount, premium, collateralReturned, seller);
optionSeries.strike = uint128(
OptionsCompute.convertFromDecimals(optionSeries.strike, ERC20(seriesAddress).decimals())
);
_adjustVariables(collateralReturned, premium, delta, false);
if (getBalance(collateralAsset) < premium) {
revert CustomErrors.WithdrawExceedsLiquidity();
}
SafeTransferLib.safeTransfer(ERC20(collateralAsset), seller, premium);
return amount;
}
function adjustVariables(
uint256 collateralAmount,
uint256 optionsValue,
int256 delta,
bool isSale
) external {
_isHandler();
_adjustVariables(collateralAmount, optionsValue, delta, isSale);
}
function _adjustVariables(
uint256 collateralAmount,
uint256 optionsValue,
int256 delta,
bool isSale
) internal {
if (isSale) {
collateralAllocated += collateralAmount;
ephemeralLiabilities += int256(
OptionsCompute.convertFromDecimals(optionsValue, ERC20(collateralAsset).decimals())
);
ephemeralDelta -= delta;
} else {
collateralAllocated -= collateralAmount;
ephemeralLiabilities -= int256(
OptionsCompute.convertFromDecimals(optionsValue, ERC20(collateralAsset).decimals())
);
ephemeralDelta += delta;
}
}
function getVolatilityFeed() public view returns (VolatilityFeed) {
return VolatilityFeed(protocol.volatilityFeed());
}
function _getPortfolioValuesFeed() internal view returns (IPortfolioValuesFeed) {
return IPortfolioValuesFeed(protocol.portfolioValuesFeed());
}
function _getAccounting() internal view returns (IAccounting) {
return IAccounting(protocol.accounting());
}
function _getOptionRegistry() internal view returns (IOptionRegistry) {
return IOptionRegistry(protocol.optionRegistry());
}
function _getUnderlyingPrice(
address underlying,
address _strikeAsset
) internal view returns (uint256) {
return PriceFeed(protocol.priceFeed()).getNormalizedRate(underlying, _strikeAsset);
}
function _isTradingNotPaused() internal view {
if (isTradingPaused) {
revert CustomErrors.TradingPaused();
}
}
function _isHandler() internal view {
if (!handler[msg.sender]) {
revert CustomErrors.NotHandler();
}
}
function _isKeeper() internal view {
if (
!keeper[msg.sender] && msg.sender != authority.governor() && msg.sender != authority.manager()
) {
revert CustomErrors.NotKeeper();
}
}
}
文件 27 的 44:NormalDist.sol
pragma solidity >=0.8.0;
import "prb-math/contracts/PRBMathSD59x18.sol";
library NormalDist {
using PRBMathSD59x18 for int256;
int256 private constant ONE = 1000000000000000000;
int256 private constant ONE_HALF = 500000000000000000;
int256 private constant SQRT_TWO = 1414213562373095048;
int256 private constant A1 = 254829592000000000;
int256 private constant A2 = -284496736000000000;
int256 private constant A3 = 1421413741000000000;
int256 private constant A4 = -1453152027000000000;
int256 private constant A5 = 1061405429000000000;
int256 private constant P = 327591100000000000;
function cdf(int256 x) public pure returns (int256) {
int256 phiParam = x.div(SQRT_TWO);
int256 onePlusPhi = ONE + (phi(phiParam));
return ONE_HALF.mul(onePlusPhi);
}
function phi(int256 x) public pure returns (int256) {
int256 sign = x >= 0 ? ONE : -ONE;
int256 abs = x.abs();
int256 t = ONE.div(ONE + (P.mul(abs)));
int256 scoresByT = getScoresFromT(t);
int256 eToXs = abs.mul(-ONE).mul(abs).exp();
int256 y = ONE - (scoresByT.mul(eToXs));
return sign.mul(y);
}
function getScoresFromT(int256 t) public pure returns (int256) {
int256 byA5T = A5.mul(t);
int256 byA4T = (byA5T + A4).mul(t);
int256 byA3T = (byA4T + A3).mul(t);
int256 byA2T = (byA3T + A2).mul(t);
int256 byA1T = (byA2T + A1).mul(t);
return byA1T;
}
}
文件 28 的 44:OptionCatalogue.sol
pragma solidity >=0.8.9;
import "./tokens/ERC20.sol";
import "./libraries/Types.sol";
import "./libraries/CustomErrors.sol";
import "./libraries/AccessControl.sol";
import "./libraries/OptionsCompute.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
contract OptionCatalogue is AccessControl {
using PRBMathSD59x18 for int256;
address public immutable collateralAsset;
mapping(bytes32 => OptionStores) public optionStores;
uint64[] public expirations;
mapping(uint256 => mapping(bool => uint128[])) public optionDetails;
uint8 private constant OPYN_DECIMALS = 8;
uint8 private constant CONVERSION_DECIMALS = 18 - OPYN_DECIMALS;
struct OptionStores {
bool approvedOption;
bool isBuyable;
bool isSellable;
}
event SeriesApproved(
bytes32 indexed optionHash,
uint64 expiration,
uint128 strike,
bool isPut,
bool isBuyable,
bool isSellable
);
event SeriesAltered(
bytes32 indexed optionHash,
uint64 expiration,
uint128 strike,
bool isPut,
bool isBuyable,
bool isSellable
);
constructor(address _authority, address _collateralAsset) AccessControl(IAuthority(_authority)) {
collateralAsset = _collateralAsset;
}
function issueNewSeries(Types.Option[] memory options) external {
_onlyManager();
uint256 addressLength = options.length;
for (uint256 i = 0; i < addressLength; i++) {
Types.Option memory o = options[i];
uint128 strike = uint128(
OptionsCompute.formatStrikePrice(o.strike, collateralAsset) * 10 ** (CONVERSION_DECIMALS)
);
if ((o.expiration - 28800) % 86400 != 0) {
revert CustomErrors.InvalidExpiry();
}
bytes32 optionHash = keccak256(abi.encodePacked(o.expiration, strike, o.isPut));
if (optionStores[optionHash].approvedOption) {
continue;
}
optionStores[optionHash] = OptionStores(
true,
o.isBuyable,
o.isSellable
);
if (
optionDetails[o.expiration][true].length == 0 && optionDetails[o.expiration][false].length == 0
) {
expirations.push(o.expiration);
}
optionDetails[o.expiration][o.isPut].push(strike);
emit SeriesApproved(optionHash, o.expiration, strike, o.isPut, o.isBuyable, o.isSellable);
}
}
function changeOptionBuyOrSell(Types.Option[] memory options) external {
_onlyManager();
uint256 adLength = options.length;
for (uint256 i = 0; i < adLength; i++) {
Types.Option memory o = options[i];
uint128 strike = uint128(
OptionsCompute.formatStrikePrice(o.strike, collateralAsset) * 10 ** (CONVERSION_DECIMALS)
);
bytes32 optionHash = keccak256(abi.encodePacked(o.expiration, strike, o.isPut));
if (optionStores[optionHash].approvedOption) {
optionStores[optionHash].isBuyable = o.isBuyable;
optionStores[optionHash].isSellable = o.isSellable;
emit SeriesAltered(optionHash, o.expiration, strike, o.isPut, o.isBuyable, o.isSellable);
} else {
revert CustomErrors.UnapprovedSeries();
}
}
}
function getExpirations() external view returns (uint64[] memory) {
return expirations;
}
function getOptionDetails(uint64 expiration, bool isPut) external view returns (uint128[] memory) {
return optionDetails[expiration][isPut];
}
function getOptionStores(bytes32 oHash) external view returns (OptionStores memory) {
return optionStores[oHash];
}
function isBuyable(bytes32 oHash) external view returns (bool) {
return optionStores[oHash].isBuyable;
}
function isSellable(bytes32 oHash) external view returns (bool) {
return optionStores[oHash].isSellable;
}
function approvedOptions(bytes32 oHash) external view returns (bool) {
return optionStores[oHash].approvedOption;
}
}
文件 29 的 44:OptionExchange.sol
pragma solidity >=0.8.9;
import "./Protocol.sol";
import "./PriceFeed.sol";
import "./BeyondPricer.sol";
import "./OptionCatalogue.sol";
import "./tokens/ERC20.sol";
import "./libraries/Types.sol";
import "./utils/ReentrancyGuard.sol";
import "./libraries/CustomErrors.sol";
import "./libraries/AccessControl.sol";
import "./libraries/OptionsCompute.sol";
import "./libraries/SafeTransferLib.sol";
import "./libraries/OpynInteractions.sol";
import "./interfaces/IWhitelist.sol";
import "./interfaces/ILiquidityPool.sol";
import "./interfaces/IHedgingReactor.sol";
import "./interfaces/IOptionRegistry.sol";
import "./interfaces/OtokenInterface.sol";
import "./interfaces/AddressBookInterface.sol";
import "./interfaces/IAlphaPortfolioValuesFeed.sol";
import "./libraries/RyskActions.sol";
import "./libraries/CombinedActions.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";
import { IOtoken, IController } from "./interfaces/GammaInterface.sol";
contract OptionExchange is Pausable, AccessControl, ReentrancyGuard, IHedgingReactor {
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
ILiquidityPool public immutable liquidityPool;
Protocol public immutable protocol;
address public immutable strikeAsset;
address public immutable underlyingAsset;
address public immutable collateralAsset;
AddressBookInterface public immutable addressbook;
ISwapRouter public immutable swapRouter;
BeyondPricer public pricer;
mapping(address => uint24) public poolFees;
address public feeRecipient;
OptionCatalogue public catalogue;
uint256 public maxTradeSize = 1000e18;
uint256 public minTradeSize = 1e17;
mapping(address => mapping(bool => bool)) public approvedCollateral;
mapping(address => address[]) internal tempTokenQueue;
mapping(address => mapping(address => uint256)) public heldTokens;
uint256 private constant MAX_BIPS = 10_000;
uint8 private constant OPYN_DECIMALS = 8;
uint8 private constant CONVERSION_DECIMALS = 10;
uint256 private constant MAX_UINT = 2 ** 256 - 1;
struct SellParams {
address seriesAddress;
Types.OptionSeries seriesToStore;
Types.OptionSeries optionSeries;
uint256 premium;
int256 delta;
uint256 fee;
uint256 amount;
uint256 tempHoldings;
uint256 transferAmount;
uint256 premiumSent;
}
struct BuyParams {
address seriesAddress;
Types.OptionSeries seriesToStore;
Types.OptionSeries optionSeries;
uint128 strikeDecimalConverted;
uint256 premium;
int256 delta;
uint256 fee;
}
event OptionsIssued(address indexed series);
event OptionsBought(
address indexed series,
address indexed buyer,
uint256 optionAmount,
uint256 premium,
uint256 fee
);
event OptionsSold(
address indexed series,
address indexed seller,
uint256 optionAmount,
uint256 premium,
uint256 fee
);
event OptionsRedeemed(
address indexed series,
uint256 optionAmount,
uint256 redeemAmount,
address redeemAsset
);
event RedemptionSent(uint256 redeemAmount, address redeemAsset, address recipient);
event OtokenMigrated(address newOptionExchange, address otoken, uint256 amount);
error TradeTooSmall();
error TradeTooLarge();
error PoolFeeNotSet();
error TokenImbalance();
error NothingToClose();
error PremiumTooSmall();
error ForbiddenAction();
error CloseSizeTooLarge();
error UnauthorisedSender();
error OperatorNotApproved();
error TooMuchSlippage();
constructor(
address _authority,
address _protocol,
address _liquidityPool,
address _pricer,
address _addressbook,
address _swapRouter,
address _feeRecipient,
address _catalogue
) AccessControl(IAuthority(_authority)) {
protocol = Protocol(_protocol);
liquidityPool = ILiquidityPool(_liquidityPool);
collateralAsset = liquidityPool.collateralAsset();
underlyingAsset = liquidityPool.underlyingAsset();
strikeAsset = liquidityPool.strikeAsset();
addressbook = AddressBookInterface(_addressbook);
swapRouter = ISwapRouter(_swapRouter);
pricer = BeyondPricer(_pricer);
catalogue = OptionCatalogue(_catalogue);
feeRecipient = _feeRecipient;
}
function pause() external {
_onlyGuardian();
_pause();
}
function unpause() external {
_onlyGuardian();
_unpause();
}
function setPricer(address _pricer) external {
_onlyGovernor();
pricer = BeyondPricer(_pricer);
}
function setOptionCatalogue(address _catalogue) external {
_onlyGovernor();
catalogue = OptionCatalogue(_catalogue);
}
function setFeeRecipient(address _feeRecipient) external {
_onlyGovernor();
feeRecipient = _feeRecipient;
}
function setPoolFee(address asset, uint24 fee) external {
_onlyGovernor();
poolFees[asset] = fee;
SafeTransferLib.safeApprove(ERC20(asset), address(swapRouter), MAX_UINT);
}
function setTradeSizeLimits(uint256 _minTradeSize, uint256 _maxTradeSize) external {
_onlyGovernor();
minTradeSize = _minTradeSize;
maxTradeSize = _maxTradeSize;
}
function changeApprovedCollateral(address collateral, bool isPut, bool isApproved) external {
_onlyGovernor();
approvedCollateral[collateral][isPut] = isApproved;
}
function withdraw(uint256 _amount) external returns (uint256) {
require(msg.sender == address(liquidityPool));
address _token = collateralAsset;
uint256 balance = ERC20(_token).balanceOf(address(this));
if (balance == 0) {
return 0;
}
if (_amount <= balance) {
SafeTransferLib.safeTransfer(ERC20(_token), msg.sender, _amount);
return _amount;
} else {
SafeTransferLib.safeTransfer(ERC20(_token), msg.sender, balance);
return balance;
}
}
function redeem(address[] memory _series, uint256[] memory amountOutMinimums) external {
_onlyManager();
uint256 adLength = _series.length;
if (adLength != amountOutMinimums.length) revert CustomErrors.InvalidInput();
for (uint256 i; i < adLength; i++) {
uint256 optionAmount = ERC20(_series[i]).balanceOf(address(this));
IOtoken otoken = IOtoken(_series[i]);
uint256 redeemAmount = OpynInteractions.redeemToAddress(
addressbook.getController(),
addressbook.getMarginPool(),
_series[i],
optionAmount,
address(this)
);
address otokenCollateralAsset = otoken.collateralAsset();
emit OptionsRedeemed(_series[i], optionAmount, redeemAmount, otokenCollateralAsset);
if (otokenCollateralAsset == collateralAsset) {
SafeTransferLib.safeTransfer(ERC20(collateralAsset), address(liquidityPool), redeemAmount);
emit RedemptionSent(redeemAmount, collateralAsset, address(liquidityPool));
} else {
uint256 redeemableCollateral = _swapExactInputSingle(
redeemAmount,
amountOutMinimums[i],
otokenCollateralAsset
);
SafeTransferLib.safeTransfer(
ERC20(collateralAsset),
address(liquidityPool),
redeemableCollateral
);
emit RedemptionSent(redeemableCollateral, collateralAsset, address(liquidityPool));
}
}
}
function transferOtokens(address newOptionExchange, address[] memory otokens) external {
_onlyGovernor();
uint256 len = otokens.length;
for (uint256 i = 0; i < len; i++) {
if (OtokenInterface(otokens[i]).underlyingAsset() != underlyingAsset) {
revert CustomErrors.NonWhitelistedOtoken();
}
uint256 balance = ERC20(otokens[i]).balanceOf(address(this));
SafeTransferLib.safeTransfer(ERC20(otokens[i]), newOptionExchange, balance);
emit OtokenMigrated(newOptionExchange, otokens[i], balance);
}
}
function createOtoken(Types.OptionSeries memory optionSeries) external returns (address series) {
uint128 formattedStrike = uint128(
OptionsCompute.formatStrikePrice(optionSeries.strike, collateralAsset)
);
series = OpynInteractions.getOrDeployOtoken(
address(addressbook.getOtokenFactory()),
optionSeries.collateral,
optionSeries.underlying,
optionSeries.strikeAsset,
formattedStrike,
optionSeries.expiration,
optionSeries.isPut
);
}
function operate(
CombinedActions.OperationProcedures[] memory _operationProcedures
) external nonReentrant whenNotPaused {
_runActions(_operationProcedures);
_verifyFinalState();
}
function _runActions(CombinedActions.OperationProcedures[] memory _operationProcedures) internal {
for (uint256 i = 0; i < _operationProcedures.length; i++) {
CombinedActions.OperationProcedures memory operationProcedure = _operationProcedures[i];
CombinedActions.OperationType operation = operationProcedure.operation;
if (operation == CombinedActions.OperationType.OPYN) {
_runOpynActions(operationProcedure.operationQueue);
} else if (operation == CombinedActions.OperationType.RYSK) {
_runRyskActions(operationProcedure.operationQueue);
}
}
}
function _verifyFinalState() internal {
address[] memory interactedTokens = tempTokenQueue[msg.sender];
uint256 arr = interactedTokens.length;
for (uint256 i = 0; i < arr; i++) {
uint256 tempTokens = heldTokens[msg.sender][interactedTokens[i]];
if (tempTokens != 0) {
if (interactedTokens[i] == collateralAsset) {
SafeTransferLib.safeTransfer(ERC20(collateralAsset), msg.sender, tempTokens);
heldTokens[msg.sender][interactedTokens[i]] = 0;
} else {
revert TokenImbalance();
}
}
}
delete tempTokenQueue[msg.sender];
}
function _runOpynActions(CombinedActions.ActionArgs[] memory _opynActions) internal {
IController controller = IController(addressbook.getController());
uint256 arr = _opynActions.length;
IController.ActionArgs[] memory _opynArgs = new IController.ActionArgs[](arr);
if (!controller.isOperator(msg.sender, address(this))) {
revert OperatorNotApproved();
}
for (uint256 i = 0; i < arr; i++) {
IController.ActionArgs memory action = CombinedActions._parseOpynArgs(_opynActions[i]);
IController.ActionType actionType = action.actionType;
if (action.owner != msg.sender) {
revert UnauthorisedSender();
}
if (actionType == IController.ActionType.DepositLongOption) {
if (action.secondAddress != msg.sender) {
revert UnauthorisedSender();
}
} else if (actionType == IController.ActionType.OpenVault) {
} else if (actionType == IController.ActionType.WithdrawLongOption) {
if (action.secondAddress == address(this)) {
_updateTempHoldings(action.asset, action.amount * 10 ** CONVERSION_DECIMALS);
}
} else if (actionType == IController.ActionType.DepositCollateral) {
if (action.secondAddress != msg.sender && action.secondAddress != address(this)) {
revert UnauthorisedSender();
}
if (action.secondAddress == address(this)) {
SafeTransferLib.safeTransferFrom(action.asset, msg.sender, address(this), action.amount);
SafeTransferLib.safeApprove(ERC20(action.asset), addressbook.getMarginPool(), action.amount);
}
} else if (actionType == IController.ActionType.MintShortOption) {
if (action.secondAddress == address(this)) {
_updateTempHoldings(action.asset, action.amount * 10 ** CONVERSION_DECIMALS);
}
} else if (actionType == IController.ActionType.BurnShortOption) {
if (action.secondAddress != msg.sender) {
revert UnauthorisedSender();
}
} else if (actionType == IController.ActionType.WithdrawCollateral) {
if (action.secondAddress != msg.sender) {
revert UnauthorisedSender();
}
} else if (actionType == IController.ActionType.SettleVault) {
if (action.secondAddress != msg.sender) {
revert UnauthorisedSender();
}
} else {
revert ForbiddenAction();
}
_opynArgs[i] = action;
}
controller.operate(_opynArgs);
}
function _runRyskActions(CombinedActions.ActionArgs[] memory _ryskActions) internal {
for (uint256 i = 0; i < _ryskActions.length; i++) {
RyskActions.ActionArgs memory action = CombinedActions._parseRyskArgs(_ryskActions[i]);
RyskActions.ActionType actionType = action.actionType;
if (actionType == RyskActions.ActionType.Issue) {
_issue(RyskActions._parseIssueArgs(action));
} else if (actionType == RyskActions.ActionType.BuyOption) {
_buyOption(RyskActions._parseBuyOptionArgs(action));
} else if (actionType == RyskActions.ActionType.SellOption) {
_sellOption(RyskActions._parseSellOptionArgs(action), false);
} else if (actionType == RyskActions.ActionType.CloseOption) {
_sellOption(RyskActions._parseSellOptionArgs(action), true);
}
}
}
function _issue(RyskActions.IssueArgs memory _args) internal returns (address series) {
uint128 strike = uint128(
OptionsCompute.formatStrikePrice(_args.optionSeries.strike, collateralAsset) *
10 ** CONVERSION_DECIMALS
);
bytes32 oHash = keccak256(
abi.encodePacked(_args.optionSeries.expiration, strike, _args.optionSeries.isPut)
);
OptionCatalogue.OptionStores memory optionStore = catalogue.getOptionStores(oHash);
if (!optionStore.approvedOption) {
revert CustomErrors.UnapprovedSeries();
}
if (!optionStore.isBuyable) {
revert CustomErrors.SeriesNotBuyable();
}
if (_args.optionSeries.strikeAsset != _args.optionSeries.collateral) {
revert CustomErrors.CollateralAssetInvalid();
}
series = liquidityPool.handlerIssue(_args.optionSeries);
emit OptionsIssued(series);
}
function _buyOption(RyskActions.BuyOptionArgs memory _args) internal {
if (_args.amount < minTradeSize) revert TradeTooSmall();
if (_args.amount > maxTradeSize) revert TradeTooLarge();
IOptionRegistry optionRegistry = getOptionRegistry();
IAlphaPortfolioValuesFeed portfolioValuesFeed = getPortfolioValuesFeed();
BuyParams memory buyParams;
bytes32 oHash;
(buyParams.seriesAddress, buyParams.seriesToStore, buyParams.optionSeries, oHash) = _preChecks(
_args.seriesAddress,
_args.optionSeries,
optionRegistry,
false
);
address recipient = _args.recipient;
(buyParams.premium, buyParams.delta, buyParams.fee) = pricer.quoteOptionPrice(
buyParams.seriesToStore,
_args.amount,
false,
portfolioValuesFeed.netDhvExposure(oHash)
);
if (buyParams.premium > _args.acceptablePremium) {
revert TooMuchSlippage();
}
_handlePremiumTransfer(buyParams.premium, buyParams.fee);
uint256 longExposure = ERC20(buyParams.seriesAddress).balanceOf(address(this)) *
10 ** CONVERSION_DECIMALS;
uint256 amount = _args.amount;
emit OptionsBought(buyParams.seriesAddress, recipient, amount, buyParams.premium, buyParams.fee);
if (longExposure > 0) {
uint256 boughtAmount = longExposure > amount ? amount : uint256(longExposure);
SafeTransferLib.safeTransfer(
ERC20(buyParams.seriesAddress),
recipient,
boughtAmount / (10 ** CONVERSION_DECIMALS)
);
portfolioValuesFeed.updateStores(
buyParams.seriesToStore,
0,
-int256(boughtAmount),
buyParams.seriesAddress
);
liquidityPool.adjustVariables(
0,
buyParams.premium.mul(boughtAmount).div(_args.amount),
buyParams.delta.mul(int256(boughtAmount)).div(int256(_args.amount)),
true
);
amount -= boughtAmount;
if (amount == 0) {
return;
}
}
if (buyParams.optionSeries.collateral != collateralAsset) {
revert CustomErrors.CollateralAssetInvalid();
}
portfolioValuesFeed.updateStores(
buyParams.seriesToStore,
int256(amount),
0,
buyParams.seriesAddress
);
liquidityPool.handlerWriteOption(
buyParams.optionSeries,
buyParams.seriesAddress,
amount,
optionRegistry,
buyParams.premium.mul(amount).div(_args.amount),
buyParams.delta.mul(int256(amount)).div(int256(_args.amount)),
recipient
);
}
function _sellOption(RyskActions.SellOptionArgs memory _args, bool isClose) internal {
if (_args.amount < minTradeSize) revert TradeTooSmall();
if (_args.amount > maxTradeSize) revert TradeTooLarge();
IOptionRegistry optionRegistry = getOptionRegistry();
IAlphaPortfolioValuesFeed portfolioValuesFeed = getPortfolioValuesFeed();
SellParams memory sellParams;
bytes32 oHash;
(sellParams.seriesAddress, sellParams.seriesToStore, sellParams.optionSeries, oHash) = _preChecks(
_args.seriesAddress,
_args.optionSeries,
optionRegistry,
true
);
(sellParams.premium, sellParams.delta, sellParams.fee) = pricer.quoteOptionPrice(
sellParams.seriesToStore,
_args.amount,
true,
portfolioValuesFeed.netDhvExposure(oHash)
);
if (sellParams.premium < _args.acceptablePremium) {
revert TooMuchSlippage();
}
sellParams.amount = _args.amount;
sellParams.tempHoldings = OptionsCompute.min(
heldTokens[msg.sender][sellParams.seriesAddress],
_args.amount
);
heldTokens[msg.sender][sellParams.seriesAddress] -= sellParams.tempHoldings;
int256 shortExposure = portfolioValuesFeed
.storesForAddress(sellParams.seriesAddress)
.shortExposure;
if (shortExposure > 0) {
if (isClose && OptionsCompute.toInt256(sellParams.amount) > shortExposure) {
revert CloseSizeTooLarge();
}
sellParams = _handleDHVBuyback(sellParams, shortExposure, optionRegistry);
} else if (isClose) {
revert NothingToClose();
}
if (!isClose && (sellParams.premium >> 3) <= sellParams.fee) {
revert PremiumTooSmall();
}
if (sellParams.amount > 0) {
if (sellParams.amount > sellParams.tempHoldings) {
SafeTransferLib.safeTransferFrom(
sellParams.seriesAddress,
msg.sender,
address(this),
OptionsCompute.convertToDecimals(
sellParams.amount - sellParams.tempHoldings,
ERC20(sellParams.seriesAddress).decimals()
)
);
}
portfolioValuesFeed.updateStores(
sellParams.seriesToStore,
0,
int256(sellParams.amount),
sellParams.seriesAddress
);
liquidityPool.adjustVariables(
0,
sellParams.premium.mul(sellParams.amount).div(_args.amount),
sellParams.delta.mul(int256(sellParams.amount)).div(int256(_args.amount)),
false
);
}
if (sellParams.premium > sellParams.premiumSent) {
if (ILiquidityPool(liquidityPool).checkBuffer() < int256((sellParams.premium - sellParams.premiumSent))) {
revert CustomErrors.MaxLiquidityBufferReached();
}
SafeTransferLib.safeTransferFrom(
collateralAsset,
address(liquidityPool),
address(this),
sellParams.premium - sellParams.premiumSent
);
}
if ((sellParams.premium >> 3) > sellParams.fee) {
SafeTransferLib.safeTransfer(ERC20(collateralAsset), feeRecipient, sellParams.fee);
} else {
sellParams.fee = sellParams.premium >> 3;
SafeTransferLib.safeTransfer(ERC20(collateralAsset), feeRecipient, sellParams.fee);
}
if (_args.recipient == address(this)) {
_updateTempHoldings(collateralAsset, sellParams.premium - sellParams.fee);
} else {
SafeTransferLib.safeTransfer(
ERC20(collateralAsset),
_args.recipient,
sellParams.premium - sellParams.fee
);
}
emit OptionsSold(
sellParams.seriesAddress,
_args.recipient,
_args.amount,
sellParams.premium,
sellParams.fee
);
}
function getOptionRegistry() internal view returns (IOptionRegistry) {
return IOptionRegistry(protocol.optionRegistry());
}
function getPortfolioValuesFeed() internal view returns (IAlphaPortfolioValuesFeed) {
return IAlphaPortfolioValuesFeed(protocol.portfolioValuesFeed());
}
function getDelta() external view returns (int256 delta) {
return 0;
}
function getPoolDenominatedValue() external view returns (uint256) {
return ERC20(collateralAsset).balanceOf(address(this));
}
function getOptionDetails(
address seriesAddress,
Types.OptionSeries memory optionSeries
) external view returns (address, Types.OptionSeries memory, uint128) {
return _getOptionDetails(seriesAddress, optionSeries, getOptionRegistry());
}
function checkHash(
Types.OptionSeries memory optionSeries,
uint128 strikeDecimalConverted,
bool isSell
) external view returns (bytes32 oHash) {
return _checkHash(optionSeries, strikeDecimalConverted, isSell);
}
function _getOptionDetails(
address seriesAddress,
Types.OptionSeries memory optionSeries,
IOptionRegistry optionRegistry
) internal view returns (address, Types.OptionSeries memory, uint128) {
if (seriesAddress == address(0)) {
seriesAddress = optionRegistry.getOtoken(
optionSeries.underlying,
optionSeries.strikeAsset,
optionSeries.expiration,
optionSeries.isPut,
optionSeries.strike,
optionSeries.collateral
);
optionSeries = Types.OptionSeries(
optionSeries.expiration,
uint128(OptionsCompute.formatStrikePrice(optionSeries.strike, collateralAsset)),
optionSeries.isPut,
optionSeries.underlying,
optionSeries.strikeAsset,
optionSeries.collateral
);
} else {
optionSeries = optionRegistry.getSeriesInfo(seriesAddress);
if (optionSeries.expiration == 0) {
IOtoken otoken = IOtoken(seriesAddress);
optionSeries = Types.OptionSeries(
uint64(otoken.expiryTimestamp()),
uint128(otoken.strikePrice()),
otoken.isPut(),
otoken.underlyingAsset(),
otoken.strikeAsset(),
otoken.collateralAsset()
);
}
}
if (seriesAddress == address(0)) {
revert CustomErrors.NonExistentOtoken();
}
if (optionSeries.expiration == 0) {
revert CustomErrors.NonExistentOtoken();
}
uint128 strikeDecimalConverted = uint128(optionSeries.strike * 10 ** CONVERSION_DECIMALS);
IWhitelist whitelist = IWhitelist(addressbook.getWhitelist());
if (!whitelist.isWhitelistedOtoken(seriesAddress)) {
revert CustomErrors.NonWhitelistedOtoken();
}
return (seriesAddress, optionSeries, strikeDecimalConverted);
}
function _checkHash(
Types.OptionSeries memory optionSeries,
uint128 strikeDecimalConverted,
bool isSell
) internal view returns (bytes32 oHash) {
oHash = keccak256(
abi.encodePacked(optionSeries.expiration, strikeDecimalConverted, optionSeries.isPut)
);
OptionCatalogue.OptionStores memory optionStore = catalogue.getOptionStores(oHash);
if (!optionStore.approvedOption) {
revert CustomErrors.UnapprovedSeries();
}
if (isSell) {
if (!optionStore.isSellable) {
revert CustomErrors.SeriesNotSellable();
}
} else {
if (!optionStore.isBuyable) {
revert CustomErrors.SeriesNotBuyable();
}
}
}
function _swapExactInputSingle(
uint256 _amountIn,
uint256 _amountOutMinimum,
address _assetIn
) internal returns (uint256) {
uint24 poolFee = poolFees[_assetIn];
if (poolFee == 0) {
revert PoolFeeNotSet();
}
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
tokenIn: _assetIn,
tokenOut: collateralAsset,
fee: poolFee,
recipient: address(this),
deadline: block.timestamp,
amountIn: _amountIn,
amountOutMinimum: _amountOutMinimum,
sqrtPriceLimitX96: 0
});
uint256 amountOut = swapRouter.exactInputSingle(params);
return amountOut;
}
function _updateTempHoldings(address asset, uint256 amount) internal {
if (heldTokens[msg.sender][asset] == 0) {
tempTokenQueue[msg.sender].push(asset);
}
heldTokens[msg.sender][asset] += amount;
}
function _handlePremiumTransfer(uint256 premium, uint256 fee) internal {
if (premium + fee > heldTokens[msg.sender][collateralAsset]) {
uint256 diff = premium + fee - heldTokens[msg.sender][collateralAsset];
heldTokens[msg.sender][collateralAsset] = 0;
SafeTransferLib.safeTransferFrom(collateralAsset, msg.sender, address(this), diff);
} else {
heldTokens[msg.sender][collateralAsset] -= premium + fee;
}
if (fee > 0) {
SafeTransferLib.safeTransfer(ERC20(collateralAsset), feeRecipient, fee);
}
SafeTransferLib.safeTransfer(ERC20(collateralAsset), address(liquidityPool), premium);
}
function _preChecks(
address _seriesAddress,
Types.OptionSeries memory _optionSeries,
IOptionRegistry _optionRegistry,
bool isSell
) internal view returns (address, Types.OptionSeries memory, Types.OptionSeries memory, bytes32) {
(
address seriesAddress,
Types.OptionSeries memory optionSeries,
uint128 strikeDecimalConverted
) = _getOptionDetails(_seriesAddress, _optionSeries, _optionRegistry);
bytes32 oHash = _checkHash(optionSeries, strikeDecimalConverted, isSell);
if (optionSeries.expiration <= block.timestamp) {
revert CustomErrors.OptionExpiryInvalid();
}
if (optionSeries.underlying != underlyingAsset) {
revert CustomErrors.UnderlyingAssetInvalid();
}
if (optionSeries.strikeAsset != strikeAsset) {
revert CustomErrors.StrikeAssetInvalid();
}
if (!approvedCollateral[optionSeries.collateral][optionSeries.isPut]) {
revert CustomErrors.CollateralAssetInvalid();
}
Types.OptionSeries memory seriesToStore = Types.OptionSeries(
optionSeries.expiration,
strikeDecimalConverted,
optionSeries.isPut,
underlyingAsset,
strikeAsset,
optionSeries.collateral
);
return (seriesAddress, seriesToStore, optionSeries, oHash);
}
function _handleDHVBuyback(
SellParams memory sellParams,
int256 shortExposure,
IOptionRegistry optionRegistry
) internal returns (SellParams memory) {
sellParams.transferAmount = OptionsCompute.min(uint256(shortExposure), sellParams.amount);
if (sellParams.tempHoldings > 0) {
SafeTransferLib.safeTransfer(
ERC20(sellParams.seriesAddress),
address(liquidityPool),
OptionsCompute.convertToDecimals(
OptionsCompute.min(sellParams.tempHoldings, sellParams.transferAmount),
ERC20(sellParams.seriesAddress).decimals()
)
);
}
if (sellParams.transferAmount > sellParams.tempHoldings) {
SafeTransferLib.safeTransferFrom(
sellParams.seriesAddress,
msg.sender,
address(liquidityPool),
OptionsCompute.convertToDecimals(
sellParams.transferAmount - sellParams.tempHoldings,
ERC20(sellParams.seriesAddress).decimals()
)
);
}
sellParams.premiumSent = sellParams.premium.mul(sellParams.transferAmount).div(sellParams.amount);
uint256 soldBackAmount = liquidityPool.handlerBuybackOption(
sellParams.optionSeries,
sellParams.transferAmount,
optionRegistry,
sellParams.seriesAddress,
sellParams.premiumSent,
sellParams.delta.mul(OptionsCompute.toInt256(sellParams.transferAmount)).div(
OptionsCompute.toInt256(sellParams.amount)
),
address(this)
);
getPortfolioValuesFeed().updateStores(
sellParams.seriesToStore,
-int256(soldBackAmount),
0,
sellParams.seriesAddress
);
sellParams.amount -= soldBackAmount;
sellParams.tempHoldings -= OptionsCompute.min(sellParams.tempHoldings, sellParams.transferAmount);
return sellParams;
}
function update() external pure returns (uint256) {
return 0;
}
function hedgeDelta(int256 _delta) external returns (int256) {
revert();
}
}
文件 30 的 44:OptionsCompute.sol
pragma solidity >=0.8.9;
import "./Types.sol";
import "./CustomErrors.sol";
import "./BlackScholes.sol";
import "../tokens/ERC20.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
library OptionsCompute {
using PRBMathUD60x18 for uint256;
using PRBMathSD59x18 for int256;
uint8 private constant SCALE_DECIMALS = 18;
uint256 private constant SCALE_UP = 10 ** 18;
uint8 private constant OPYN_DECIMALS = 8;
uint8 private constant OPYN_CONVERSION_DECIMAL = 10;
function convertToDecimals(uint256 value, uint256 decimals) internal pure returns (uint256) {
if (decimals > SCALE_DECIMALS) {
revert();
}
uint256 difference = SCALE_DECIMALS - decimals;
return value / (10 ** difference);
}
function convertFromDecimals(
uint256 value,
uint256 decimals
) internal pure returns (uint256 difference) {
if (decimals > SCALE_DECIMALS) {
revert();
}
difference = SCALE_DECIMALS - decimals;
return value * (10 ** difference);
}
function convertFromDecimals(
uint256 value,
uint8 decimalsA,
uint8 decimalsB
) internal pure returns (uint256) {
uint8 difference;
if (decimalsA > decimalsB) {
difference = decimalsA - decimalsB;
return value / (10 ** difference);
}
difference = decimalsB - decimalsA;
return value * (10 ** difference);
}
function convertToCollateralDenominated(
uint256 quote,
uint256 underlyingPrice,
Types.OptionSeries memory optionSeries
) internal pure returns (uint256 convertedQuote) {
if (optionSeries.strikeAsset != optionSeries.collateral) {
return (quote * SCALE_UP) / underlyingPrice;
} else {
return quote;
}
}
function calculatePercentageChange(uint256 n, uint256 o) internal pure returns (uint256 pC) {
if (n > o) {
pC = (n - o).div(o);
} else {
pC = (o - n).div(o);
}
}
function validatePortfolioValues(
uint256 spotPrice,
Types.PortfolioValues memory portfolioValues,
uint256 maxTimeDeviationThreshold,
uint256 maxPriceDeviationThreshold
) public view {
uint256 timeDelta = block.timestamp - portfolioValues.timestamp;
if (timeDelta > maxTimeDeviationThreshold) {
revert CustomErrors.TimeDeltaExceedsThreshold(timeDelta);
}
uint256 priceDelta = calculatePercentageChange(spotPrice, portfolioValues.spotPrice);
if (priceDelta > maxPriceDeviationThreshold) {
revert CustomErrors.PriceDeltaExceedsThreshold(priceDelta);
}
}
function formatStrikePrice(uint256 strikePrice, address collateral) public view returns (uint256) {
uint256 price = strikePrice / (10 ** OPYN_CONVERSION_DECIMAL);
uint256 collateralDecimals = ERC20(collateral).decimals();
if (collateralDecimals >= OPYN_DECIMALS) return price;
uint256 difference = OPYN_DECIMALS - collateralDecimals;
return (price / (10 ** difference)) * (10 ** difference);
}
function quotePriceGreeks(
Types.OptionSeries memory optionSeries,
bool isBuying,
uint256 bidAskIVSpread,
uint256 riskFreeRate,
uint256 iv,
uint256 underlyingPrice,
bool overrideIV
) internal view returns (uint256 quote, int256 delta) {
if (iv == 0) {
revert CustomErrors.IVNotFound();
}
if (isBuying && !overrideIV) {
iv = (iv * (SCALE_UP - (bidAskIVSpread))) / SCALE_UP;
}
if (optionSeries.expiration <= block.timestamp) {
revert CustomErrors.OptionExpiryInvalid();
}
(quote, delta) = BlackScholes.blackScholesCalcGreeks(
underlyingPrice,
optionSeries.strike,
optionSeries.expiration,
iv,
riskFreeRate,
optionSeries.isPut
);
}
function min(uint256 v1, uint256 v2) internal pure returns (uint256) {
return v1 > v2 ? v2 : v1;
}
function max(int256 v1, int256 v2) internal pure returns (int256) {
return v1 > v2 ? v1 : v2;
}
function toInt256(uint256 value) internal pure returns (int256) {
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
文件 31 的 44:OpynInteractions.sol
pragma solidity >=0.8.4;
import "./SafeTransferLib.sol";
import { Types } from "./Types.sol";
import { IOtokenFactory, IOtoken, IController, GammaTypes } from "../interfaces/GammaInterface.sol";
library OpynInteractions {
uint256 private constant SCALE_FROM = 10**10;
error NoShort();
function getOrDeployOtoken(
address oTokenFactory,
address collateral,
address underlying,
address strikeAsset,
uint256 strike,
uint256 expiration,
bool isPut
) external returns (address) {
IOtokenFactory factory = IOtokenFactory(oTokenFactory);
address otokenFromFactory = factory.getOtoken(
underlying,
strikeAsset,
collateral,
strike,
expiration,
isPut
);
if (otokenFromFactory != address(0)) {
return otokenFromFactory;
}
address otoken = factory.createOtoken(
underlying,
strikeAsset,
collateral,
strike,
expiration,
isPut
);
return otoken;
}
function getOtoken(
address oTokenFactory,
address collateral,
address underlying,
address strikeAsset,
uint256 strike,
uint256 expiration,
bool isPut
) external view returns (address otokenFromFactory) {
IOtokenFactory factory = IOtokenFactory(oTokenFactory);
otokenFromFactory = factory.getOtoken(
underlying,
strikeAsset,
collateral,
strike,
expiration,
isPut
);
}
function createShort(
address gammaController,
address marginPool,
address oTokenAddress,
uint256 depositAmount,
uint256 vaultId,
uint256 amount,
uint256 vaultType
) external returns (uint256) {
IController controller = IController(gammaController);
amount = amount / SCALE_FROM;
IOtoken oToken = IOtoken(oTokenAddress);
address collateralAsset = oToken.collateralAsset();
ERC20 collateralToken = ERC20(collateralAsset);
SafeTransferLib.safeApprove(collateralToken, marginPool, depositAmount);
IController.ActionArgs[] memory actions = new IController.ActionArgs[](2);
uint256 newVaultID = (controller.getAccountVaultCounter(address(this))) + 1;
if (newVaultID == vaultId) {
actions = new IController.ActionArgs[](3);
actions[0] = IController.ActionArgs(
IController.ActionType.OpenVault,
address(this),
address(this),
address(0),
vaultId,
0,
0,
abi.encode(vaultType)
);
actions[1] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this),
address(this),
collateralAsset,
vaultId,
depositAmount,
0,
""
);
actions[2] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this),
address(this),
oTokenAddress,
vaultId,
amount,
0,
""
);
} else {
actions[0] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this),
address(this),
collateralAsset,
vaultId,
depositAmount,
0,
""
);
actions[1] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this),
address(this),
oTokenAddress,
vaultId,
amount,
0,
""
);
}
controller.operate(actions);
return amount;
}
function depositCollat(
address gammaController,
address marginPool,
address collateralAsset,
uint256 depositAmount,
uint256 vaultId
) external {
IController controller = IController(gammaController);
ERC20 collateralToken = ERC20(collateralAsset);
SafeTransferLib.safeApprove(collateralToken, marginPool, depositAmount);
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this),
address(this),
collateralAsset,
vaultId,
depositAmount,
0,
""
);
controller.operate(actions);
}
function withdrawCollat(
address gammaController,
address collateralAsset,
uint256 withdrawAmount,
uint256 vaultId
) external {
IController controller = IController(gammaController);
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.WithdrawCollateral,
address(this),
address(this),
collateralAsset,
vaultId,
withdrawAmount,
0,
""
);
controller.operate(actions);
}
function burnShort(
address gammaController,
address oTokenAddress,
uint256 burnAmount,
uint256 vaultId
) external returns (uint256) {
IController controller = IController(gammaController);
IOtoken oToken = IOtoken(oTokenAddress);
ERC20 collateralAsset = ERC20(oToken.collateralAsset());
uint256 startCollatBalance = collateralAsset.balanceOf(address(this));
GammaTypes.Vault memory vault = controller.getVault(address(this), vaultId);
IController.ActionArgs[] memory actions = new IController.ActionArgs[](2);
actions[0] = IController.ActionArgs(
IController.ActionType.BurnShortOption,
address(this),
address(this),
oTokenAddress,
vaultId,
burnAmount,
0,
""
);
actions[1] = IController.ActionArgs(
IController.ActionType.WithdrawCollateral,
address(this),
address(this),
address(collateralAsset),
vaultId,
(vault.collateralAmounts[0] * burnAmount) / vault.shortAmounts[0],
0,
""
);
controller.operate(actions);
return collateralAsset.balanceOf(address(this)) - startCollatBalance;
}
function settle(address gammaController, uint256 vaultId)
external
returns (
uint256 collateralRedeemed,
uint256 collateralLost,
uint256 shortAmount
)
{
IController controller = IController(gammaController);
GammaTypes.Vault memory vault = controller.getVault(address(this), vaultId);
if (vault.shortOtokens.length == 0) {
revert NoShort();
}
ERC20 collateralToken = ERC20(vault.collateralAssets[0]);
uint256 startCollateralBalance = collateralToken.balanceOf(address(this));
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this),
address(this),
address(0),
vaultId,
0,
0,
""
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
collateralRedeemed = endCollateralBalance - startCollateralBalance;
return (
collateralRedeemed,
vault.collateralAmounts[0] - collateralRedeemed,
vault.shortAmounts[0]
);
}
function redeem(
address gammaController,
address marginPool,
address series,
uint256 amount
) external returns (uint256) {
IController controller = IController(gammaController);
address collateralAsset = IOtoken(series).collateralAsset();
uint256 startAssetBalance = ERC20(collateralAsset).balanceOf(msg.sender);
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.Redeem,
address(0),
msg.sender,
series,
0,
amount,
0,
""
);
SafeTransferLib.safeApprove(ERC20(series), marginPool, amount);
controller.operate(actions);
uint256 endAssetBalance = ERC20(collateralAsset).balanceOf(msg.sender);
return endAssetBalance - startAssetBalance;
}
function redeemToAddress(
address gammaController,
address marginPool,
address series,
uint256 amount,
address recipient
) external returns (uint256) {
IController controller = IController(gammaController);
address collateralAsset = IOtoken(series).collateralAsset();
uint256 startAssetBalance = ERC20(collateralAsset).balanceOf(recipient);
IController.ActionArgs[] memory actions = new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.Redeem,
address(0),
recipient,
series,
0,
amount,
0,
""
);
SafeTransferLib.safeApprove(ERC20(series), marginPool, amount);
controller.operate(actions);
uint256 endAssetBalance = ERC20(collateralAsset).balanceOf(recipient);
return endAssetBalance - startAssetBalance;
}
}
文件 32 的 44:OtokenInterface.sol
pragma solidity 0.8.9;
interface OtokenInterface {
function controller() external view returns (address);
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
function init(
address _addressBook,
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external;
function getOtokenDetails()
external
view
returns (
address,
address,
address,
uint256,
uint256,
bool
);
function mintOtoken(address account, uint256 amount) external;
function burnOtoken(address account, uint256 amount) external;
}
文件 33 的 44:PRBMath.sol
pragma solidity >=0.8.4;
error PRBMath__MulDivFixedPointOverflow(uint256 prod1);
error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);
error PRBMath__MulDivSignedInputTooSmall();
error PRBMath__MulDivSignedOverflow(uint256 rAbs);
error PRBMathSD59x18__AbsInputTooSmall();
error PRBMathSD59x18__CeilOverflow(int256 x);
error PRBMathSD59x18__DivInputTooSmall();
error PRBMathSD59x18__DivOverflow(uint256 rAbs);
error PRBMathSD59x18__ExpInputTooBig(int256 x);
error PRBMathSD59x18__Exp2InputTooBig(int256 x);
error PRBMathSD59x18__FloorUnderflow(int256 x);
error PRBMathSD59x18__FromIntOverflow(int256 x);
error PRBMathSD59x18__FromIntUnderflow(int256 x);
error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);
error PRBMathSD59x18__GmOverflow(int256 x, int256 y);
error PRBMathSD59x18__LogInputTooSmall(int256 x);
error PRBMathSD59x18__MulInputTooSmall();
error PRBMathSD59x18__MulOverflow(uint256 rAbs);
error PRBMathSD59x18__PowuOverflow(uint256 rAbs);
error PRBMathSD59x18__SqrtNegativeInput(int256 x);
error PRBMathSD59x18__SqrtOverflow(int256 x);
error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);
error PRBMathUD60x18__CeilOverflow(uint256 x);
error PRBMathUD60x18__ExpInputTooBig(uint256 x);
error PRBMathUD60x18__Exp2InputTooBig(uint256 x);
error PRBMathUD60x18__FromUintOverflow(uint256 x);
error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);
error PRBMathUD60x18__LogInputTooSmall(uint256 x);
error PRBMathUD60x18__SqrtOverflow(uint256 x);
error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);
library PRBMath {
struct SD59x18 {
int256 value;
}
struct UD60x18 {
uint256 value;
}
uint256 internal constant SCALE = 1e18;
uint256 internal constant SCALE_LPOTD = 262144;
uint256 internal constant SCALE_INVERSE =
78156646155174841979727994598816262306175212592076161876661_508869554232690281;
function exp2(uint256 x) internal pure returns (uint256 result) {
unchecked {
result = 0x800000000000000000000000000000000000000000000000;
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
result *= SCALE;
result >>= (191 - (x >> 64));
}
}
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
msb += 1;
}
}
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
return result;
}
if (prod1 >= denominator) {
revert PRBMath__MulDivOverflow(prod1, denominator);
}
uint256 remainder;
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
unchecked {
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
denominator := div(denominator, lpotdod)
prod0 := div(prod0, lpotdod)
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
prod0 |= prod1 * lpotdod;
uint256 inverse = (3 * denominator) ^ 2;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
inverse *= 2 - denominator * inverse;
result = prod0 * inverse;
return result;
}
}
function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 >= SCALE) {
revert PRBMath__MulDivFixedPointOverflow(prod1);
}
uint256 remainder;
uint256 roundUpUnit;
assembly {
remainder := mulmod(x, y, SCALE)
roundUpUnit := gt(remainder, 499999999999999999)
}
if (prod1 == 0) {
unchecked {
result = (prod0 / SCALE) + roundUpUnit;
return result;
}
}
assembly {
result := add(
mul(
or(
div(sub(prod0, remainder), SCALE_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))
),
SCALE_INVERSE
),
roundUpUnit
)
}
}
function mulDivSigned(
int256 x,
int256 y,
int256 denominator
) internal pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath__MulDivSignedInputTooSmall();
}
uint256 ax;
uint256 ay;
uint256 ad;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
uint256 sx;
uint256 sy;
uint256 sd;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
}
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) {
result <<= 1;
}
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
uint256 roundedDownResult = x / result;
return result >= roundedDownResult ? roundedDownResult : result;
}
}
}
文件 34 的 44:PRBMathSD59x18.sol
pragma solidity >=0.8.4;
import "./PRBMath.sol";
library PRBMathSD59x18 {
int256 internal constant LOG2_E = 1_442695040888963407;
int256 internal constant HALF_SCALE = 5e17;
int256 internal constant MAX_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_792003956564819967;
int256 internal constant MAX_WHOLE_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_000000000000000000;
int256 internal constant MIN_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_792003956564819968;
int256 internal constant MIN_WHOLE_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_000000000000000000;
int256 internal constant SCALE = 1e18;
function abs(int256 x) internal pure returns (int256 result) {
unchecked {
if (x == MIN_SD59x18) {
revert PRBMathSD59x18__AbsInputTooSmall();
}
result = x < 0 ? -x : x;
}
}
function avg(int256 x, int256 y) internal pure returns (int256 result) {
unchecked {
int256 sum = (x >> 1) + (y >> 1);
if (sum < 0) {
assembly {
result := add(sum, and(or(x, y), 1))
}
} else {
result = sum + (x & y & 1);
}
}
}
function ceil(int256 x) internal pure returns (int256 result) {
if (x > MAX_WHOLE_SD59x18) {
revert PRBMathSD59x18__CeilOverflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
result = x - remainder;
if (x > 0) {
result += SCALE;
}
}
}
}
function div(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__DivInputTooSmall();
}
uint256 ax;
uint256 ay;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
}
uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__DivOverflow(rAbs);
}
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
function e() internal pure returns (int256 result) {
result = 2_718281828459045235;
}
function exp(int256 x) internal pure returns (int256 result) {
if (x < -41_446531673892822322) {
return 0;
}
if (x >= 133_084258667509499441) {
revert PRBMathSD59x18__ExpInputTooBig(x);
}
unchecked {
int256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
function exp2(int256 x) internal pure returns (int256 result) {
if (x < 0) {
if (x < -59_794705707972522261) {
return 0;
}
unchecked {
result = 1e36 / exp2(-x);
}
} else {
if (x >= 192e18) {
revert PRBMathSD59x18__Exp2InputTooBig(x);
}
unchecked {
uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE);
result = int256(PRBMath.exp2(x192x64));
}
}
}
function floor(int256 x) internal pure returns (int256 result) {
if (x < MIN_WHOLE_SD59x18) {
revert PRBMathSD59x18__FloorUnderflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
result = x - remainder;
if (x < 0) {
result -= SCALE;
}
}
}
}
function frac(int256 x) internal pure returns (int256 result) {
unchecked {
result = x % SCALE;
}
}
function fromInt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < MIN_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntUnderflow(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntOverflow(x);
}
result = x * SCALE;
}
}
function gm(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
return 0;
}
unchecked {
int256 xy = x * y;
if (xy / x != y) {
revert PRBMathSD59x18__GmOverflow(x, y);
}
if (xy < 0) {
revert PRBMathSD59x18__GmNegativeProduct(x, y);
}
result = int256(PRBMath.sqrt(uint256(xy)));
}
}
function inv(int256 x) internal pure returns (int256 result) {
unchecked {
result = 1e36 / x;
}
}
function ln(int256 x) internal pure returns (int256 result) {
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
function log10(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
default {
result := MAX_SD59x18
}
}
if (result == MAX_SD59x18) {
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
function log2(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
unchecked {
int256 sign;
if (x >= SCALE) {
sign = 1;
} else {
sign = -1;
assembly {
x := div(1000000000000000000000000000000000000, x)
}
}
uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE));
result = int256(n) * SCALE;
int256 y = x >> n;
if (y == SCALE) {
return result * sign;
}
for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
if (y >= 2 * SCALE) {
result += delta;
y >>= 1;
}
}
result *= sign;
}
}
function mul(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__MulInputTooSmall();
}
unchecked {
uint256 ax;
uint256 ay;
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__MulOverflow(rAbs);
}
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
}
function pi() internal pure returns (int256 result) {
result = 3_141592653589793238;
}
function pow(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
result = y == 0 ? SCALE : int256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
function powu(int256 x, uint256 y) internal pure returns (int256 result) {
uint256 xAbs = uint256(abs(x));
uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE);
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs);
if (yAux & 1 > 0) {
rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs);
}
}
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__PowuOverflow(rAbs);
}
bool isNegative = x < 0 && y & 1 == 1;
result = isNegative ? -int256(rAbs) : int256(rAbs);
}
function scale() internal pure returns (int256 result) {
result = SCALE;
}
function sqrt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < 0) {
revert PRBMathSD59x18__SqrtNegativeInput(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__SqrtOverflow(x);
}
result = int256(PRBMath.sqrt(uint256(x * SCALE)));
}
}
function toInt(int256 x) internal pure returns (int256 result) {
unchecked {
result = x / SCALE;
}
}
}
文件 35 的 44:PRBMathUD60x18.sol
pragma solidity >=0.8.4;
import "./PRBMath.sol";
library PRBMathUD60x18 {
uint256 internal constant HALF_SCALE = 5e17;
uint256 internal constant LOG2_E = 1_442695040888963407;
uint256 internal constant MAX_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_584007913129639935;
uint256 internal constant MAX_WHOLE_UD60x18 =
115792089237316195423570985008687907853269984665640564039457_000000000000000000;
uint256 internal constant SCALE = 1e18;
function avg(uint256 x, uint256 y) internal pure returns (uint256 result) {
unchecked {
result = (x >> 1) + (y >> 1) + (x & y & 1);
}
}
function ceil(uint256 x) internal pure returns (uint256 result) {
if (x > MAX_WHOLE_UD60x18) {
revert PRBMathUD60x18__CeilOverflow(x);
}
assembly {
let remainder := mod(x, SCALE)
let delta := sub(SCALE, remainder)
result := add(x, mul(delta, gt(remainder, 0)))
}
}
function div(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = PRBMath.mulDiv(x, SCALE, y);
}
function e() internal pure returns (uint256 result) {
result = 2_718281828459045235;
}
function exp(uint256 x) internal pure returns (uint256 result) {
if (x >= 133_084258667509499441) {
revert PRBMathUD60x18__ExpInputTooBig(x);
}
unchecked {
uint256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
function exp2(uint256 x) internal pure returns (uint256 result) {
if (x >= 192e18) {
revert PRBMathUD60x18__Exp2InputTooBig(x);
}
unchecked {
uint256 x192x64 = (x << 64) / SCALE;
result = PRBMath.exp2(x192x64);
}
}
function floor(uint256 x) internal pure returns (uint256 result) {
assembly {
let remainder := mod(x, SCALE)
result := sub(x, mul(remainder, gt(remainder, 0)))
}
}
function frac(uint256 x) internal pure returns (uint256 result) {
assembly {
result := mod(x, SCALE)
}
}
function fromUint(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__FromUintOverflow(x);
}
result = x * SCALE;
}
}
function gm(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
unchecked {
uint256 xy = x * y;
if (xy / x != y) {
revert PRBMathUD60x18__GmOverflow(x, y);
}
result = PRBMath.sqrt(xy);
}
}
function inv(uint256 x) internal pure returns (uint256 result) {
unchecked {
result = 1e36 / x;
}
}
function ln(uint256 x) internal pure returns (uint256 result) {
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
function log10(uint256 x) internal pure returns (uint256 result) {
if (x < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(x);
}
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) }
default {
result := MAX_UD60x18
}
}
if (result == MAX_UD60x18) {
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
function log2(uint256 x) internal pure returns (uint256 result) {
if (x < SCALE) {
revert PRBMathUD60x18__LogInputTooSmall(x);
}
unchecked {
uint256 n = PRBMath.mostSignificantBit(x / SCALE);
result = n * SCALE;
uint256 y = x >> n;
if (y == SCALE) {
return result;
}
for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
if (y >= 2 * SCALE) {
result += delta;
y >>= 1;
}
}
}
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = PRBMath.mulDivFixedPoint(x, y);
}
function pi() internal pure returns (uint256 result) {
result = 3_141592653589793238;
}
function pow(uint256 x, uint256 y) internal pure returns (uint256 result) {
if (x == 0) {
result = y == 0 ? SCALE : uint256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
function powu(uint256 x, uint256 y) internal pure returns (uint256 result) {
result = y & 1 > 0 ? x : SCALE;
for (y >>= 1; y > 0; y >>= 1) {
x = PRBMath.mulDivFixedPoint(x, x);
if (y & 1 > 0) {
result = PRBMath.mulDivFixedPoint(result, x);
}
}
}
function scale() internal pure returns (uint256 result) {
result = SCALE;
}
function sqrt(uint256 x) internal pure returns (uint256 result) {
unchecked {
if (x > MAX_UD60x18 / SCALE) {
revert PRBMathUD60x18__SqrtOverflow(x);
}
result = PRBMath.sqrt(x * SCALE);
}
}
function toUint(uint256 x) internal pure returns (uint256 result) {
unchecked {
result = x / SCALE;
}
}
}
文件 36 的 44:Pausable.sol
pragma solidity ^0.8.0;
import "../utils/Context.sol";
abstract contract Pausable is Context {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() {
_paused = false;
}
modifier whenNotPaused() {
_requireNotPaused();
_;
}
modifier whenPaused() {
_requirePaused();
_;
}
function paused() public view virtual returns (bool) {
return _paused;
}
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
文件 37 的 44:PriceFeed.sol
pragma solidity >=0.8.9;
import "./interfaces/AggregatorV3Interface.sol";
import "./libraries/AccessControl.sol";
contract PriceFeed is AccessControl {
mapping(address => mapping(address => address)) public priceFeeds;
address public sequencerUptimeFeedAddress;
uint8 private constant SCALE_DECIMALS = 18;
uint32 private constant STALE_PRICE_DELAY = 3600;
uint32 private constant GRACE_PERIOD_TIME = 1800;
error SequencerDown();
error GracePeriodNotOver();
constructor(address _authority, address _sequencerUptimeFeedAddress)
AccessControl(IAuthority(_authority))
{
sequencerUptimeFeedAddress = _sequencerUptimeFeedAddress;
}
function addPriceFeed(
address underlying,
address strike,
address feed
) public {
_onlyGovernor();
priceFeeds[underlying][strike] = feed;
}
function setSequencerUptimeFeedAddress(address _sequencerUptimeFeedAddress) external {
_onlyGovernor();
sequencerUptimeFeedAddress = _sequencerUptimeFeedAddress;
}
function getRate(address underlying, address strike) external view returns (uint256) {
address feedAddress = priceFeeds[underlying][strike];
require(feedAddress != address(0), "Price feed does not exist");
AggregatorV3Interface feed = AggregatorV3Interface(feedAddress);
_checkSequencerUp();
(uint80 roundId, int256 rate, , uint256 timestamp, uint80 answeredInRound) = feed
.latestRoundData();
require(rate > 0, "ChainLinkPricer: price is lower than 0");
require(timestamp != 0, "ROUND_NOT_COMPLETE");
require(block.timestamp <= timestamp + STALE_PRICE_DELAY, "STALE_PRICE");
require(answeredInRound >= roundId, "STALE_PRICE");
return uint256(rate);
}
function getNormalizedRate(address underlying, address strike) external view returns (uint256) {
address feedAddress = priceFeeds[underlying][strike];
require(feedAddress != address(0), "Price feed does not exist");
AggregatorV3Interface feed = AggregatorV3Interface(feedAddress);
uint8 feedDecimals = feed.decimals();
_checkSequencerUp();
(uint80 roundId, int256 rate, , uint256 timestamp, uint80 answeredInRound) = feed
.latestRoundData();
require(rate > 0, "ChainLinkPricer: price is lower than 0");
require(timestamp != 0, "ROUND_NOT_COMPLETE");
require(block.timestamp <= timestamp + STALE_PRICE_DELAY, "STALE_PRICE");
require(answeredInRound >= roundId, "STALE_PRICE_ROUND");
uint8 difference;
if (SCALE_DECIMALS > feedDecimals) {
difference = SCALE_DECIMALS - feedDecimals;
return uint256(rate) * (10**difference);
}
difference = feedDecimals - SCALE_DECIMALS;
return uint256(rate) / (10**difference);
}
function _checkSequencerUp() internal view {
AggregatorV3Interface sequencerUptimeFeed = AggregatorV3Interface(sequencerUptimeFeedAddress);
(, int256 answer, uint256 startedAt, , ) = sequencerUptimeFeed.latestRoundData();
if (!(answer == 0)) {
revert SequencerDown();
}
uint256 timeSinceUp = block.timestamp - startedAt;
if (timeSinceUp <= GRACE_PERIOD_TIME) {
revert GracePeriodNotOver();
}
}
}
文件 38 的 44:Protocol.sol
pragma solidity >=0.8.0;
import "./libraries/AccessControl.sol";
contract Protocol is AccessControl {
address public optionRegistry;
address public volatilityFeed;
address public portfolioValuesFeed;
address public accounting;
address public priceFeed;
address public optionExchange;
constructor(address _authority) AccessControl(IAuthority(_authority)) {}
function changeVolatilityFeed(address _volFeed) external {
_onlyGovernor();
volatilityFeed = _volFeed;
}
function changePortfolioValuesFeed(address _portfolioValuesFeed) external {
_onlyGovernor();
portfolioValuesFeed = _portfolioValuesFeed;
}
function changeAccounting(address _accounting) external {
_onlyGovernor();
accounting = _accounting;
}
function changePriceFeed(address _priceFeed) external {
_onlyGovernor();
priceFeed = _priceFeed;
}
function changeOptionRegistry(address _optionRegistry) external {
_onlyGovernor();
optionRegistry = _optionRegistry;
}
function changeOptionExchange(address _optionExchange) external {
_onlyGovernor();
optionExchange = _optionExchange;
}
}
文件 39 的 44:ReentrancyGuard.sol
pragma solidity >=0.8.9;
contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
文件 40 的 44:RyskActions.sol
pragma solidity >=0.8.4;
import "./Types.sol";
library RyskActions {
enum ActionType {
Issue,
BuyOption,
SellOption,
CloseOption
}
struct ActionArgs {
ActionType actionType;
address secondAddress;
address asset;
uint256 vaultId;
uint256 amount;
Types.OptionSeries optionSeries;
uint256 acceptablePremium;
bytes data;
}
struct IssueArgs {
Types.OptionSeries optionSeries;
}
struct BuyOptionArgs {
Types.OptionSeries optionSeries;
address seriesAddress;
uint256 amount;
address recipient;
uint256 acceptablePremium;
}
struct SellOptionArgs {
Types.OptionSeries optionSeries;
address seriesAddress;
uint256 vaultId;
uint256 amount;
address recipient;
uint256 acceptablePremium;
}
function _parseIssueArgs(ActionArgs memory _args) internal pure returns (IssueArgs memory) {
require(_args.actionType == ActionType.Issue, "A2");
return IssueArgs({optionSeries: _args.optionSeries});
}
function _parseBuyOptionArgs(ActionArgs memory _args) internal pure returns (BuyOptionArgs memory) {
require(_args.actionType == ActionType.BuyOption, "A3");
return
BuyOptionArgs({
optionSeries: _args.optionSeries,
seriesAddress: _args.asset,
amount: _args.amount,
recipient: _args.secondAddress,
acceptablePremium: _args.acceptablePremium
});
}
function _parseSellOptionArgs(ActionArgs memory _args) internal pure returns (SellOptionArgs memory) {
require(_args.actionType == ActionType.SellOption || _args.actionType == ActionType.CloseOption, "A4");
return
SellOptionArgs({
optionSeries: _args.optionSeries,
seriesAddress: _args.asset,
vaultId: _args.vaultId,
amount: _args.amount,
recipient: _args.secondAddress,
acceptablePremium: _args.acceptablePremium
});
}
}
文件 41 的 44:SABR.sol
pragma solidity >=0.8.0;
import "prb-math/contracts/PRBMath.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
library SABR {
using PRBMathSD59x18 for int256;
int256 private constant eps = 1e11;
struct IntermediateVariables {
int256 a;
int256 b;
int256 c;
int256 d;
int256 v;
int256 w;
int256 z;
int256 k;
int256 f;
int256 t;
}
function lognormalVol(
int256 k,
int256 f,
int256 t,
int256 alpha,
int256 beta,
int256 rho,
int256 volvol
) internal pure returns (int256 iv) {
if (k <= 0 || f <= 0) {
return 0;
}
IntermediateVariables memory vars;
vars.k = k;
vars.f = f;
vars.t = t;
if (beta == 1e18) {
vars.a = 0;
vars.v = 0;
vars.w = 0;
} else {
vars.a = ((1e18 - beta).pow(2e18)).mul(alpha.pow(2e18)).div(
int256(24e18).mul(_fkbeta(vars.f, vars.k, beta))
);
vars.v = ((1e18 - beta).pow(2e18)).mul(_logfk(vars.f, vars.k).powu(2)).div(24e18);
vars.w = ((1e18 - beta).pow(4e18)).mul(_logfk(vars.f, vars.k).powu(4)).div(1920e18);
}
vars.b = int256(25e16).mul(rho).mul(beta).mul(volvol).mul(alpha).div(
_fkbeta(vars.f, vars.k, beta).sqrt()
);
vars.c = (2e18 - int256(3e18).mul(rho.powu(2))).mul(volvol.pow(2e18)).div(24e18);
vars.d = _fkbeta(vars.f, vars.k, beta).sqrt();
vars.z = volvol.mul(_fkbeta(vars.f, vars.k, beta).sqrt()).mul(_logfk(vars.f, vars.k)).div(alpha);
if (vars.z.abs() > eps) {
int256 vz = alpha.mul(vars.z).mul(1e18 + (vars.a + vars.b + vars.c).mul(vars.t)).div(
vars.d.mul(1e18 + vars.v + vars.w).mul(_x(rho, vars.z))
);
return vz;
} else {
int256 v0 = alpha.mul(1e18 + (vars.a + vars.b + vars.c).mul(vars.t)).div(
vars.d.mul(1e18 + vars.v + vars.w)
);
return v0;
}
}
function _logfk(int256 f, int256 k) internal pure returns (int256) {
return (f.div(k)).ln();
}
function _fkbeta(
int256 f,
int256 k,
int256 beta
) internal pure returns (int256) {
return (f.mul(k)).pow(1e18 - beta);
}
function _x(int256 rho, int256 z) internal pure returns (int256) {
int256 a = (1e18 - 2 * rho.mul(z) + z.powu(2)).sqrt() + z - rho;
int256 b = 1e18 - rho;
return (a.div(b)).ln();
}
}
文件 42 的 44:SafeTransferLib.sol
pragma solidity >=0.8.0;
import {ERC20} from "../tokens/ERC20.sol";
library SafeTransferLib {
function safeTransferETH(address to, uint256 amount) internal {
bool callStatus;
assembly {
callStatus := call(gas(), to, amount, 0, 0, 0, 0)
}
require(callStatus, "ETH_TRANSFER_FAILED");
}
function safeTransferFrom(
address tokenAddress,
address from,
address to,
uint256 amount
) internal {
ERC20 token = ERC20(tokenAddress);
bool callStatus;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 68), amount)
callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 36), amount)
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 36), amount)
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
}
function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {
assembly {
let returnDataSize := returndatasize()
if iszero(callStatus) {
returndatacopy(0, 0, returnDataSize)
revert(0, returnDataSize)
}
switch returnDataSize
case 32 {
returndatacopy(0, 0, returnDataSize)
success := iszero(iszero(mload(0)))
}
case 0 {
success := 1
}
default {
success := 0
}
}
}
}
文件 43 的 44:Types.sol
pragma solidity >=0.8.0;
library Types {
struct OptionSeries {
uint64 expiration;
uint128 strike;
bool isPut;
address underlying;
address strikeAsset;
address collateral;
}
struct PortfolioValues {
int256 delta;
int256 gamma;
int256 vega;
int256 theta;
int256 callPutsValue;
uint256 timestamp;
uint256 spotPrice;
}
struct Option {
uint64 expiration;
uint128 strike;
bool isPut;
bool isBuyable;
bool isSellable;
}
struct Order {
OptionSeries optionSeries;
uint256 amount;
uint256 price;
uint256 orderExpiry;
address buyer;
address seriesAddress;
uint128 lowerSpotMovementRange;
uint128 upperSpotMovementRange;
bool isBuyBack;
}
struct OptionParams {
uint128 minCallStrikePrice;
uint128 maxCallStrikePrice;
uint128 minPutStrikePrice;
uint128 maxPutStrikePrice;
uint128 minExpiry;
uint128 maxExpiry;
}
struct UtilizationState {
uint256 totalOptionPrice;
int256 totalDelta;
uint256 collateralToAllocate;
uint256 utilizationBefore;
uint256 utilizationAfter;
uint256 utilizationPrice;
bool isDecreased;
uint256 deltaTiltAmount;
uint256 underlyingPrice;
uint256 iv;
}
}
文件 44 的 44:VolatilityFeed.sol
pragma solidity >=0.8.9;
import "./libraries/AccessControl.sol";
import "./libraries/CustomErrors.sol";
import "./libraries/SABR.sol";
import "./Protocol.sol";
import "./OptionExchange.sol";
import "prb-math/contracts/PRBMathSD59x18.sol";
import "prb-math/contracts/PRBMathUD60x18.sol";
contract VolatilityFeed is AccessControl {
using PRBMathSD59x18 for int256;
using PRBMathUD60x18 for uint256;
mapping(uint256 => SABRParams) public sabrParams;
mapping(address => bool) public keeper;
uint256[] public expiries;
int256 private constant ONE_YEAR_SECONDS = 31557600;
int256 private constant BIPS_SCALE = 1e12;
int256 private constant BIPS = 1e6;
int256 private constant maxInterestRate = 200e18;
int256 private constant minInterestRate = -200e18;
Protocol public immutable protocol;
struct SABRParams {
int32 callAlpha;
int32 callBeta;
int32 callRho;
int32 callVolvol;
int32 putAlpha;
int32 putBeta;
int32 putRho;
int32 putVolvol;
int256 interestRate;
}
constructor(address _authority, address _protocol) AccessControl(IAuthority(_authority)) {
protocol = Protocol(_protocol);
}
error AlphaError();
error BetaError();
error RhoError();
error VolvolError();
error InterestRateError();
event SabrParamsSet(
uint256 indexed _expiry,
int32 callAlpha,
int32 callBeta,
int32 callRho,
int32 callVolvol,
int32 putAlpha,
int32 putBeta,
int32 putRho,
int32 putVolvol,
int256 interestRate
);
event KeeperUpdated(address keeper, bool auth);
function setSabrParameters(SABRParams memory _sabrParams, uint256 _expiry) external {
_isKeeper();
_isExchangePaused();
if (_sabrParams.callAlpha <= 0 || _sabrParams.putAlpha <= 0) {
revert AlphaError();
}
if (_sabrParams.callVolvol <= 0 || _sabrParams.putVolvol <= 0) {
revert VolvolError();
}
if (
_sabrParams.callBeta <= 0 ||
_sabrParams.callBeta > BIPS ||
_sabrParams.putBeta <= 0 ||
_sabrParams.putBeta > BIPS
) {
revert BetaError();
}
if (
_sabrParams.callRho <= -BIPS ||
_sabrParams.callRho >= BIPS ||
_sabrParams.putRho <= -BIPS ||
_sabrParams.putRho >= BIPS
) {
revert RhoError();
}
if (_sabrParams.interestRate > maxInterestRate || _sabrParams.interestRate < minInterestRate) {
revert InterestRateError();
}
if (sabrParams[_expiry].callAlpha == 0) {
expiries.push(_expiry);
}
sabrParams[_expiry] = _sabrParams;
emit SabrParamsSet(
_expiry,
_sabrParams.callAlpha,
_sabrParams.callBeta,
_sabrParams.callRho,
_sabrParams.callVolvol,
_sabrParams.putAlpha,
_sabrParams.putBeta,
_sabrParams.putRho,
_sabrParams.putVolvol,
_sabrParams.interestRate
);
}
function setKeeper(address _keeper, bool _auth) external {
_onlyGovernor();
keeper[_keeper] = _auth;
emit KeeperUpdated(_keeper, _auth);
}
function getImpliedVolatility(
bool isPut,
uint256 underlyingPrice,
uint256 strikePrice,
uint256 expiration
) external view returns (uint256 vol) {
(vol, ) = _getImpliedVolatility(isPut, underlyingPrice, strikePrice, expiration);
}
function getImpliedVolatilityWithForward(
bool isPut,
uint256 underlyingPrice,
uint256 strikePrice,
uint256 expiration
) external view returns (uint256 vol, uint256 forward) {
(vol, forward) = _getImpliedVolatility(isPut, underlyingPrice, strikePrice, expiration);
}
function _getImpliedVolatility(
bool isPut,
uint256 underlyingPrice,
uint256 strikePrice,
uint256 expiration
) internal view returns (uint256, uint256) {
int256 time = (int256(expiration) - int256(block.timestamp)).div(ONE_YEAR_SECONDS);
if (time <= 0) {
revert CustomErrors.OptionExpiryInvalid();
}
int256 vol;
SABRParams memory sabrParams_ = sabrParams[expiration];
if (sabrParams_.callAlpha == 0) {
revert CustomErrors.IVNotFound();
}
int256 forwardPrice = int256(underlyingPrice).mul(
(PRBMathSD59x18.exp(sabrParams_.interestRate.mul(time)))
);
if (!isPut) {
vol = SABR.lognormalVol(
int256(strikePrice),
forwardPrice,
time,
sabrParams_.callAlpha * BIPS_SCALE,
sabrParams_.callBeta * BIPS_SCALE,
sabrParams_.callRho * BIPS_SCALE,
sabrParams_.callVolvol * BIPS_SCALE
);
} else {
vol = SABR.lognormalVol(
int256(strikePrice),
forwardPrice,
time,
sabrParams_.putAlpha * BIPS_SCALE,
sabrParams_.putBeta * BIPS_SCALE,
sabrParams_.putRho * BIPS_SCALE,
sabrParams_.putVolvol * BIPS_SCALE
);
}
if (vol <= 0) {
revert CustomErrors.IVNotFound();
}
return (uint256(vol), uint256(forwardPrice));
}
function getExpiries() external view returns (uint256[] memory) {
return expiries;
}
function _isKeeper() internal view {
if (
!keeper[msg.sender] && msg.sender != authority.governor() && msg.sender != authority.manager()
) {
revert CustomErrors.NotKeeper();
}
}
function _isExchangePaused() internal view {
if (!OptionExchange(protocol.optionExchange()).paused()) {
revert CustomErrors.ExchangeNotPaused();
}
}
}
{
"compilationTarget": {
"contracts/LiquidityPool.sol": "LiquidityPool"
},
"evmVersion": "london",
"libraries": {
"contracts/libraries/OptionsCompute.sol:OptionsCompute": "0xcf263127e7dff09018af1f803bd3f9db58587a1c"
},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 100
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_protocol","type":"address"},{"internalType":"address","name":"_strikeAsset","type":"address"},{"internalType":"address","name":"_underlyingAsset","type":"address"},{"internalType":"address","name":"_collateralAsset","type":"address"},{"internalType":"uint256","name":"rfr","type":"uint256"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"components":[{"internalType":"uint128","name":"minCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minExpiry","type":"uint128"},{"internalType":"uint128","name":"maxExpiry","type":"uint128"}],"internalType":"struct Types.OptionParams","name":"_optionParams","type":"tuple"},{"internalType":"address","name":"_authority","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CollateralAssetInvalid","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidAmount","type":"error"},{"inputs":[],"name":"InvalidDecimals","type":"error"},{"inputs":[],"name":"InvalidShareAmount","type":"error"},{"inputs":[],"name":"IssuanceFailed","type":"error"},{"inputs":[],"name":"LiabilitiesGreaterThanAssets","type":"error"},{"inputs":[],"name":"MaxLiquidityBufferReached","type":"error"},{"inputs":[],"name":"NotHandler","type":"error"},{"inputs":[],"name":"NotKeeper","type":"error"},{"inputs":[],"name":"OptionExpiryInvalid","type":"error"},{"inputs":[],"name":"OptionStrikeInvalid","type":"error"},{"inputs":[],"name":"ReactorAlreadyExists","type":"error"},{"inputs":[],"name":"StrikeAssetInvalid","type":"error"},{"inputs":[],"name":"TradingNotPaused","type":"error"},{"inputs":[],"name":"TradingPaused","type":"error"},{"inputs":[],"name":"UNAUTHORIZED","type":"error"},{"inputs":[],"name":"UnderlyingAssetInvalid","type":"error"},{"inputs":[],"name":"WithdrawExceedsLiquidity","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract IAuthority","name":"authority","type":"address"}],"name":"AuthorityUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"series","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"premium","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"escrowReturned","type":"uint256"},{"indexed":false,"internalType":"address","name":"seller","type":"address"}],"name":"BuybackOption","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"DepositEpochExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"InitiateWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int256","name":"deltaChange","type":"int256"}],"name":"RebalancePortfolioDelta","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"series","type":"address"},{"indexed":false,"internalType":"uint256","name":"collateralReturned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collateralLost","type":"uint256"},{"indexed":false,"internalType":"address","name":"closer","type":"address"}],"name":"SettleVault","type":"event"},{"anonymous":false,"inputs":[],"name":"TradingPaused","type":"event"},{"anonymous":false,"inputs":[],"name":"TradingUnpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"}],"name":"Withdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"WithdrawalEpochExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"series","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"premium","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"escrow","type":"uint256"},{"indexed":false,"internalType":"address","name":"buyer","type":"address"}],"name":"WriteOption","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"lpCollateralDifference","type":"uint256"},{"internalType":"bool","name":"addToLpBalance","type":"bool"}],"name":"adjustCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"optionsValue","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"bool","name":"isSale","type":"bool"}],"name":"adjustVariables","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"authority","outputs":[{"internalType":"contract IAuthority","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bufferPercentage","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_handler","type":"address"},{"internalType":"bool","name":"auth","type":"bool"}],"name":"changeHandler","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"checkBuffer","outputs":[{"internalType":"int256","name":"bufferRemaining","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralAllocated","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralCap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"completeWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deposit","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"depositEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"depositEpochPricePerShare","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"depositReceipts","outputs":[{"internalType":"uint128","name":"epoch","type":"uint128"},{"internalType":"uint128","name":"amount","type":"uint128"},{"internalType":"uint256","name":"unredeemedShares","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ephemeralDelta","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ephemeralLiabilities","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"executeEpochCalculation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"}],"name":"getBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getExternalDelta","outputs":[{"internalType":"int256","name":"externalDelta","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHedgingReactors","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"uint256","name":"underlyingPrice","type":"uint256"},{"internalType":"uint256","name":"strikePrice","type":"uint256"},{"internalType":"uint256","name":"expiration","type":"uint256"}],"name":"getImpliedVolatility","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNAV","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPortfolioDelta","outputs":[{"internalType":"int256","name":"","type":"int256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getVolatilityFeed","outputs":[{"internalType":"contract VolatilityFeed","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"handler","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"contract IOptionRegistry","name":"optionRegistry","type":"address"},{"internalType":"address","name":"seriesAddress","type":"address"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"address","name":"seller","type":"address"}],"name":"handlerBuybackOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"}],"name":"handlerIssue","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"handlerIssueAndWriteOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint64","name":"expiration","type":"uint64"},{"internalType":"uint128","name":"strike","type":"uint128"},{"internalType":"bool","name":"isPut","type":"bool"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"address","name":"strikeAsset","type":"address"},{"internalType":"address","name":"collateral","type":"address"}],"internalType":"struct Types.OptionSeries","name":"optionSeries","type":"tuple"},{"internalType":"address","name":"seriesAddress","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"contract IOptionRegistry","name":"optionRegistry","type":"address"},{"internalType":"uint256","name":"premium","type":"uint256"},{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"handlerWriteOption","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"hedgingReactors","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"initiateWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isTradingPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"keeper","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxPriceDeviationThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTimeDeviationThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"optionParams","outputs":[{"internalType":"uint128","name":"minCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxCallStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"maxPutStrikePrice","type":"uint128"},{"internalType":"uint128","name":"minExpiry","type":"uint128"},{"internalType":"uint128","name":"maxExpiry","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"partitionedFunds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pauseTradingAndRequest","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"_pause","type":"bool"}],"name":"pauseUnpauseTrading","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingDeposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingWithdrawals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"protocol","outputs":[{"internalType":"contract Protocol","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"delta","type":"int256"},{"internalType":"uint256","name":"reactorIndex","type":"uint256"}],"name":"rebalancePortfolioDelta","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_shares","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_index","type":"uint256"},{"internalType":"bool","name":"_override","type":"bool"}],"name":"removeHedgingReactorAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resetEphemeralValues","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"riskFreeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract IAuthority","name":"_newAuthority","type":"address"}],"name":"setAuthority","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_bufferPercentage","type":"uint256"}],"name":"setBufferPercentage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_collateralCap","type":"uint256"}],"name":"setCollateralCap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_reactorAddress","type":"address"}],"name":"setHedgingReactorAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_keeper","type":"address"},{"internalType":"bool","name":"_auth","type":"bool"}],"name":"setKeeper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxPriceDeviationThreshold","type":"uint256"}],"name":"setMaxPriceDeviationThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxTimeDeviationThreshold","type":"uint256"}],"name":"setMaxTimeDeviationThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"_newMinCallStrike","type":"uint128"},{"internalType":"uint128","name":"_newMaxCallStrike","type":"uint128"},{"internalType":"uint128","name":"_newMinPutStrike","type":"uint128"},{"internalType":"uint128","name":"_newMaxPutStrike","type":"uint128"},{"internalType":"uint128","name":"_newMinExpiry","type":"uint128"},{"internalType":"uint128","name":"_newMaxExpiry","type":"uint128"}],"name":"setNewOptionParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_riskFreeRate","type":"uint256"}],"name":"setRiskFreeRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"seriesAddress","type":"address"}],"name":"settleVault","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"strikeAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlyingAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"withdrawalEpoch","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"withdrawalEpochPricePerShare","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"withdrawalReceipts","outputs":[{"internalType":"uint128","name":"epoch","type":"uint128"},{"internalType":"uint128","name":"shares","type":"uint128"}],"stateMutability":"view","type":"function"}]