Overview
S Balance
S Value
$0.00More Info
Private Name Tags
ContractCreator
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
ActionMarketAuxStatic
Compiler Version
v0.8.28+commit.7893614a
Optimization Enabled:
Yes with 0 runs
Other Settings:
shanghai EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.17; import "../../../interfaces/IPMarket.sol"; import "../../../interfaces/IPRouterStatic.sol"; import "./StorageLayout.sol"; import "./MarketApproxLibV1.sol"; contract ActionMarketAuxStatic is IPActionMarketAuxStatic { using MarketMathCore for MarketState; using PMath for int256; using PMath for uint256; using LogExpMath for int256; using PYIndexLib for PYIndex; using PYIndexLib for IPYieldToken; function getMarketState( address market ) public view returns ( address pt, address yt, address sy, int256 impliedYield, uint256 marketExchangeRateExcludeFee, MarketState memory state ) { (IStandardizedYield SY, IPPrincipalToken PT, IPYieldToken YT) = _readTokens(market); pt = address(PT); yt = address(YT); sy = address(SY); state = _readState(market); impliedYield = _getPtImpliedYield(market); marketExchangeRateExcludeFee = getTradeExchangeRateExcludeFee(market, state); } function getTradeExchangeRateExcludeFee(address market, MarketState memory state) public view returns (uint256) { if (IPMarket(market).isExpired()) return PMath.ONE; MarketPreCompute memory comp = state.getMarketPreCompute(_pyIndex(market), block.timestamp); int256 preFeeExchangeRate = MarketMathCore._getExchangeRate( state.totalPt, comp.totalAsset, comp.rateScalar, comp.rateAnchor, 0 ); return preFeeExchangeRate.Uint(); } function getTradeExchangeRateIncludeFee(address market, int256 netPtOut) public view returns (uint256) { if (IPMarket(market).isExpired()) return PMath.ONE; int256 netPtToAccount = netPtOut; MarketState memory state = _readState(market); MarketPreCompute memory comp = state.getMarketPreCompute(_pyIndex(market), block.timestamp); int256 preFeeExchangeRate = MarketMathCore._getExchangeRate( state.totalPt, comp.totalAsset, comp.rateScalar, comp.rateAnchor, netPtToAccount ); if (netPtToAccount > 0) { int256 postFeeExchangeRate = preFeeExchangeRate.divDown(comp.feeRate); if (postFeeExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(postFeeExchangeRate); return postFeeExchangeRate.Uint(); } else { return preFeeExchangeRate.mulDown(comp.feeRate).Uint(); } } function calcPriceImpactPt(address market, int256 netPtOut) public view returns (uint256 priceImpact) { uint256 preTradeRate = getTradeExchangeRateIncludeFee(market, _getSign(netPtOut)); uint256 tradedRate = getTradeExchangeRateIncludeFee(market, netPtOut); priceImpact = _calculateImpact(preTradeRate, tradedRate); } function calcPriceImpactYt(address market, int256 netPtOut) public view returns (uint256 priceImpact) { uint256 ytPreTradeRate = _calcVirtualYTPrice(getTradeExchangeRateIncludeFee(market, _getSign(netPtOut))); uint256 ytTradedRate = _calcVirtualYTPrice(getTradeExchangeRateIncludeFee(market, netPtOut)); priceImpact = _calculateImpact(ytPreTradeRate, ytTradedRate); } function calcPriceImpactPY(address market, int256 netPtOut) public view returns (uint256 priceImpact) { uint256 ptPreTradeRate = getTradeExchangeRateIncludeFee(market, _getSign(netPtOut)); uint256 ptTradeRate = getTradeExchangeRateIncludeFee(market, netPtOut); uint256 ptPreTradePrice = PMath.ONE.divDown(ptPreTradeRate); uint256 ptTradePrice = PMath.ONE.divDown(ptTradeRate); uint256 ytPreTradePrice = _calcVirtualYTPrice(ptPreTradeRate); uint256 ytTradePrice = _calcVirtualYTPrice(ptTradeRate); uint256 pyPreTradeRate = ytPreTradePrice.divDown(ptPreTradePrice); uint256 pyTradeRate = ytTradePrice.divDown(ptTradePrice); priceImpact = _calculateImpact(pyPreTradeRate, pyTradeRate); } /** * @notice get the rate of yieldToken & PT * @return yieldToken the address of yieldToken * @return netPtOut the amount of PT that can be swapped from 1 yieldToken (10**yieldToken.decimals()). If can't swap, return type(uint256).max * @return netYieldTokenOut the amount of yieldToken that can be swapped from 1 PT (10**PT.decimals()). If can't swap, return type(uint256).max */ function getYieldTokenAndPtRate( address market ) public view returns (address yieldToken, uint256 netPtOut, uint256 netYieldTokenOut) { (IStandardizedYield SY, IPPrincipalToken PT, ) = _readTokens(market); yieldToken = SY.yieldToken(); uint256 yieldDecimals = IERC20Metadata(yieldToken).decimals(); uint256 ptDecimals = PT.decimals(); try IPRouterStatic(address(this)).swapExactTokenForPtStatic(market, yieldToken, 10 ** yieldDecimals) returns ( uint256 netPtOutRet, uint256, uint256, uint256, uint256 ) { netPtOut = netPtOutRet; } catch { netPtOut = type(uint256).max; } try IPRouterStatic(address(this)).swapExactPtForTokenStatic(market, 10 ** ptDecimals, yieldToken) returns ( uint256 netYieldTokenOutRet, uint256, uint256, uint256, uint256 ) { netYieldTokenOut = netYieldTokenOutRet; } catch { netYieldTokenOut = type(uint256).max; } } /** * @notice get the rate of yieldToken & YT * @return yieldToken the address of yieldToken * @return netYtOut the amount of YT that can be swapped from 1 yieldToken (10**yieldToken.decimals()). If can't swap, return type(uint256).max * @return netYieldTokenOut the amount of yieldToken that can be swapped from 1 YT (10**YT.decimals()). If can't swap, return type(uint256).max */ function getYieldTokenAndYtRate( address market ) public view returns (address yieldToken, uint256 netYtOut, uint256 netYieldTokenOut) { (IStandardizedYield SY, , IPYieldToken YT) = _readTokens(market); yieldToken = SY.yieldToken(); uint256 yieldDecimals = IERC20Metadata(yieldToken).decimals(); uint256 ytDecimals = YT.decimals(); try IPRouterStatic(address(this)).swapExactTokenForYtStatic(market, yieldToken, 10 ** yieldDecimals) returns ( uint256 netYtOutRet, uint256, uint256, uint256, uint256 ) { netYtOut = netYtOutRet; } catch { netYtOut = type(uint256).max; } try IPRouterStatic(address(this)).swapExactYtForTokenStatic(market, 10 ** ytDecimals, yieldToken) returns ( uint256 netYieldTokenOutRet, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { netYieldTokenOut = netYieldTokenOutRet; } catch { netYieldTokenOut = type(uint256).max; } } function getLpToSyRate(address market) public view returns (uint256) { (IStandardizedYield SY, , ) = _readTokens(market); return getLpToAssetRate(market).divDown(SY.exchangeRate()); } function getPtToSyRate(address market) public view returns (uint256) { (IStandardizedYield SY, , ) = _readTokens(market); return getPtToAssetRate(market).divDown(SY.exchangeRate()); } function getYtToSyRate(address market) external view returns (uint256) { (IStandardizedYield SY, , ) = _readTokens(market); return getYtToAssetRate(market).divDown(SY.exchangeRate()); } function getLpToAssetRate(address market) public view returns (uint256) { MarketState memory state = _readState(market); PYIndex pyIndexCurrent = _pyIndex(market); int256 totalHypotheticalAsset; if (state.expiry <= block.timestamp) { // 1 PT = 1 Asset post-expiry totalHypotheticalAsset = state.totalPt + pyIndexCurrent.syToAsset(state.totalSy); } else { MarketPreCompute memory comp = state.getMarketPreCompute(pyIndexCurrent, block.timestamp); totalHypotheticalAsset = comp.totalAsset + state.totalPt.mulDown(int256(_getPtToAssetRate(market, state, pyIndexCurrent))); } return totalHypotheticalAsset.divDown(state.totalLp).Uint(); } function getPtToAssetRate(address market) public view returns (uint256) { MarketState memory state = _readState(market); return _getPtToAssetRate(market, state, _pyIndex(market)); } function getYtToAssetRate(address market) public view returns (uint256) { return PMath.ONE - getPtToAssetRate(market); } /// @param slippage A fixed-point number with 18 decimal places function swapExactSyForPtStaticAndGenerateApproxParams( address market, uint256 exactSyIn, uint256 slippage ) external view returns ( uint256 netPtOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, ApproxParams memory approxParams ) { (netPtOut, netSyFee, priceImpact, exchangeRateAfter) = IPActionMarketCoreStatic(address(this)) .swapExactSyForPtStatic(market, exactSyIn); approxParams = genApproxParamsToSwapExactSyForPt(market, netPtOut, slippage); } /// @param slippage A fixed-point number with 18 decimal places function swapExactTokenForPtStaticAndGenerateApproxParams( address market, address tokenIn, uint256 amountTokenIn, uint256 slippage ) external view returns ( uint256 netPtOut, uint256 netSyMinted, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, ApproxParams memory approxParams ) { (netPtOut, netSyMinted, netSyFee, priceImpact, exchangeRateAfter) = IPActionMarketCoreStatic(address(this)) .swapExactTokenForPtStatic(market, tokenIn, amountTokenIn); approxParams = genApproxParamsToSwapExactSyForPt(market, netPtOut, slippage); } /// @param slippage A fixed-point number with 18 decimal places function genApproxParamsToSwapExactSyForPt( address market, uint256 netPtOut, uint256 slippage ) public view returns (ApproxParams memory) { MarketState memory state = _readState(market); MarketPreCompute memory comp = state.getMarketPreCompute(_pyIndex(market), block.timestamp); uint256 guessLowerBound = 0; uint256 guessUpperBound = MarketApproxPtOutLibV1.calcMaxPtOut(comp, state.totalPt); return genApproxParamsPtOut(netPtOut, guessLowerBound, guessUpperBound, slippage); } /// @param slippage A fixed-point number with 18 decimal places function genApproxParamsPtOut( uint256 netPtOut, uint256 guessLowerBound, uint256 guessUpperBound, uint256 slippage ) internal pure returns (ApproxParams memory) { uint256 guessOffchain = netPtOut; uint256 MAX_ITERATION = 30; uint256 MIN_EPS_CAP = PMath.ONE / 10 ** 5; uint256 eps = PMath.min(slippage / 2, MIN_EPS_CAP); uint256 guessMin = PMath.max(guessLowerBound, netPtOut.tweakDown(slippage)); uint256 guessMax = PMath.min(guessUpperBound, netPtOut.tweakUp(5 * slippage)); return ApproxParams({ guessOffchain: guessOffchain, maxIteration: MAX_ITERATION, eps: eps, guessMin: guessMin, guessMax: guessMax }); } function _getPtToAssetRate( address market, MarketState memory state, PYIndex pyIndexCurrent ) internal view returns (uint256 ptToAssetRate) { if (state.expiry <= block.timestamp) { (IStandardizedYield SY, , ) = _readTokens(market); return (SY.exchangeRate().divDown(PYIndex.unwrap(pyIndexCurrent))); } uint256 timeToExpiry = state.expiry - block.timestamp; int256 assetToPtRate = MarketMathCore._getExchangeRateFromImpliedRate(state.lastLnImpliedRate, timeToExpiry); ptToAssetRate = uint256(PMath.IONE.divDown(assetToPtRate)); } function _getPtImpliedYield(address market) internal view returns (int256) { MarketState memory state = _readState(market); int256 lnImpliedRate = (state.lastLnImpliedRate).Int(); return lnImpliedRate.exp(); } function _calcVirtualYTPrice(uint256 ptAssetExchangeRate) private pure returns (uint256 ytAssetExchangeRate) { // 1 asset = EX pt // 1 pt = 1/EX Asset // 1 yt + 1/EX Asset = 1 Asset // 1 yt = 1 Asset - 1/EX Asset // 1 yt = (EX - 1) / EX Asset return (ptAssetExchangeRate - PMath.ONE).divDown(ptAssetExchangeRate); } function _readState(address market) internal view returns (MarketState memory) { return IPRouterStatic(address(this)).readMarketState(market); } function _readTokens( address market ) internal view returns (IStandardizedYield _SY, IPPrincipalToken _PT, IPYieldToken _YT) { return IPMarket(market).readTokens(); } function _getSign(int256 netPtOut) private pure returns (int256) { return netPtOut > 0 ? int256(1) : int256(-1); } function _calculateImpact(uint256 rateBefore, uint256 rateTraded) private pure returns (uint256 impact) { impact = (rateBefore.Int() - rateTraded.Int()).abs().divDown(rateBefore); } function _pyIndex(address market) private view returns (PYIndex) { return PYIndex.wrap(IPRouterStatic(address(this)).pyIndexCurrentViewMarket(market)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library Errors { // BulkSeller error BulkInsufficientSyForTrade(uint256 currentAmount, uint256 requiredAmount); error BulkInsufficientTokenForTrade(uint256 currentAmount, uint256 requiredAmount); error BulkInSufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut); error BulkInSufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut); error BulkInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance); error BulkNotMaintainer(); error BulkNotAdmin(); error BulkSellerAlreadyExisted(address token, address SY, address bulk); error BulkSellerInvalidToken(address token, address SY); error BulkBadRateTokenToSy(uint256 actualRate, uint256 currentRate, uint256 eps); error BulkBadRateSyToToken(uint256 actualRate, uint256 currentRate, uint256 eps); // APPROX error ApproxFail(); error ApproxParamsInvalid(uint256 guessMin, uint256 guessMax, uint256 eps); error ApproxBinarySearchInputInvalid( uint256 approxGuessMin, uint256 approxGuessMax, uint256 minGuessMin, uint256 maxGuessMax ); // MARKET + MARKET MATH CORE error MarketExpired(); error MarketZeroAmountsInput(); error MarketZeroAmountsOutput(); error MarketZeroLnImpliedRate(); error MarketInsufficientPtForTrade(int256 currentAmount, int256 requiredAmount); error MarketInsufficientPtReceived(uint256 actualBalance, uint256 requiredBalance); error MarketInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance); error MarketZeroTotalPtOrTotalAsset(int256 totalPt, int256 totalAsset); error MarketExchangeRateBelowOne(int256 exchangeRate); error MarketProportionMustNotEqualOne(); error MarketRateScalarBelowZero(int256 rateScalar); error MarketScalarRootBelowZero(int256 scalarRoot); error MarketProportionTooHigh(int256 proportion, int256 maxProportion); error OracleUninitialized(); error OracleTargetTooOld(uint32 target, uint32 oldest); error OracleZeroCardinality(); error MarketFactoryExpiredPt(); error MarketFactoryInvalidPt(); error MarketFactoryMarketExists(); error MarketFactoryLnFeeRateRootTooHigh(uint80 lnFeeRateRoot, uint256 maxLnFeeRateRoot); error MarketFactoryOverriddenFeeTooHigh(uint80 overriddenFee, uint256 marketLnFeeRateRoot); error MarketFactoryReserveFeePercentTooHigh(uint8 reserveFeePercent, uint8 maxReserveFeePercent); error MarketFactoryZeroTreasury(); error MarketFactoryInitialAnchorTooLow(int256 initialAnchor, int256 minInitialAnchor); error MFNotPendleMarket(address addr); // ROUTER error RouterInsufficientLpOut(uint256 actualLpOut, uint256 requiredLpOut); error RouterInsufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut); error RouterInsufficientPtOut(uint256 actualPtOut, uint256 requiredPtOut); error RouterInsufficientYtOut(uint256 actualYtOut, uint256 requiredYtOut); error RouterInsufficientPYOut(uint256 actualPYOut, uint256 requiredPYOut); error RouterInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut); error RouterInsufficientSyRepay(uint256 actualSyRepay, uint256 requiredSyRepay); error RouterInsufficientPtRepay(uint256 actualPtRepay, uint256 requiredPtRepay); error RouterNotAllSyUsed(uint256 netSyDesired, uint256 netSyUsed); error RouterTimeRangeZero(); error RouterCallbackNotPendleMarket(address caller); error RouterInvalidAction(bytes4 selector); error RouterInvalidFacet(address facet); error RouterKyberSwapDataZero(); error SimulationResults(bool success, bytes res); // YIELD CONTRACT error YCExpired(); error YCNotExpired(); error YieldContractInsufficientSy(uint256 actualSy, uint256 requiredSy); error YCNothingToRedeem(); error YCPostExpiryDataNotSet(); error YCNoFloatingSy(); // YieldFactory error YCFactoryInvalidExpiry(); error YCFactoryYieldContractExisted(); error YCFactoryZeroExpiryDivisor(); error YCFactoryZeroTreasury(); error YCFactoryInterestFeeRateTooHigh(uint256 interestFeeRate, uint256 maxInterestFeeRate); error YCFactoryRewardFeeRateTooHigh(uint256 newRewardFeeRate, uint256 maxRewardFeeRate); // SY error SYInvalidTokenIn(address token); error SYInvalidTokenOut(address token); error SYZeroDeposit(); error SYZeroRedeem(); error SYInsufficientSharesOut(uint256 actualSharesOut, uint256 requiredSharesOut); error SYInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut); // SY-specific error SYQiTokenMintFailed(uint256 errCode); error SYQiTokenRedeemFailed(uint256 errCode); error SYQiTokenRedeemRewardsFailed(uint256 rewardAccruedType0, uint256 rewardAccruedType1); error SYQiTokenBorrowRateTooHigh(uint256 borrowRate, uint256 borrowRateMax); error SYCurveInvalidPid(); error SYCurve3crvPoolNotFound(); error SYApeDepositAmountTooSmall(uint256 amountDeposited); error SYBalancerInvalidPid(); error SYInvalidRewardToken(address token); error SYStargateRedeemCapExceeded(uint256 amountLpDesired, uint256 amountLpRedeemable); error SYBalancerReentrancy(); error NotFromTrustedRemote(uint16 srcChainId, bytes path); error ApxETHNotEnoughBuffer(); // Liquidity Mining error VCInactivePool(address pool); error VCPoolAlreadyActive(address pool); error VCZeroVePendle(address user); error VCExceededMaxWeight(uint256 totalWeight, uint256 maxWeight); error VCEpochNotFinalized(uint256 wTime); error VCPoolAlreadyAddAndRemoved(address pool); error VEInvalidNewExpiry(uint256 newExpiry); error VEExceededMaxLockTime(); error VEInsufficientLockTime(); error VENotAllowedReduceExpiry(); error VEZeroAmountLocked(); error VEPositionNotExpired(); error VEZeroPosition(); error VEZeroSlope(uint128 bias, uint128 slope); error VEReceiveOldSupply(uint256 msgTime); error GCNotPendleMarket(address caller); error GCNotVotingController(address caller); error InvalidWTime(uint256 wTime); error ExpiryInThePast(uint256 expiry); error ChainNotSupported(uint256 chainId); error FDTotalAmountFundedNotMatch(uint256 actualTotalAmount, uint256 expectedTotalAmount); error FDEpochLengthMismatch(); error FDInvalidPool(address pool); error FDPoolAlreadyExists(address pool); error FDInvalidNewFinishedEpoch(uint256 oldFinishedEpoch, uint256 newFinishedEpoch); error FDInvalidStartEpoch(uint256 startEpoch); error FDInvalidWTimeFund(uint256 lastFunded, uint256 wTime); error FDFutureFunding(uint256 lastFunded, uint256 currentWTime); error BDInvalidEpoch(uint256 epoch, uint256 startTime); // Cross-Chain error MsgNotFromSendEndpoint(uint16 srcChainId, bytes path); error MsgNotFromReceiveEndpoint(address sender); error InsufficientFeeToSendMsg(uint256 currentFee, uint256 requiredFee); error ApproxDstExecutionGasNotSet(); error InvalidRetryData(); // GENERIC MSG error ArrayLengthMismatch(); error ArrayEmpty(); error ArrayOutOfBounds(); error ZeroAddress(); error FailedToSendEther(); error InvalidMerkleProof(); error OnlyLayerZeroEndpoint(); error OnlyYT(); error OnlyYCFactory(); error OnlyWhitelisted(); // Swap Aggregator error SAInsufficientTokenIn(address tokenIn, uint256 amountExpected, uint256 amountActual); error UnsupportedSelector(uint256 aggregatorType, bytes4 selector); }
// SPDX-License-Identifier: GPL-3.0-or-later // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the “Software”), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pragma solidity ^0.8.0; /* solhint-disable */ /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { unchecked { require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "Invalid exponent"); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { unchecked { // The real natural logarithm is not defined for negative numbers or zero. require(a > 0, "out of bounds"); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } } /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that r`esult. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. require(x < 2 ** 255, "x out of bounds"); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. require(y < MILD_EXPONENT_BOUND, "y out of bounds"); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, "product out of bounds" ); return uint256(exp(logx_times_y)); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { unchecked { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { unchecked { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } }
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.8.0; /* solhint-disable private-vars-leading-underscore, reason-string */ library PMath { uint256 internal constant ONE = 1e18; // 18 decimal places int256 internal constant IONE = 1e18; // 18 decimal places function subMax0(uint256 a, uint256 b) internal pure returns (uint256) { unchecked { return (a >= b ? a - b : 0); } } function subNoNeg(int256 a, int256 b) internal pure returns (int256) { require(a >= b, "negative"); return a - b; // no unchecked since if b is very negative, a - b might overflow } function mulDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 product = a * b; unchecked { return product / ONE; } } function mulDown(int256 a, int256 b) internal pure returns (int256) { int256 product = a * b; unchecked { return product / IONE; } } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { uint256 aInflated = a * ONE; unchecked { return aInflated / b; } } function divDown(int256 a, int256 b) internal pure returns (int256) { int256 aInflated = a * IONE; unchecked { return aInflated / b; } } function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } function rawDivUp(int256 a, int256 b) internal pure returns (int256) { return (a + b - 1) / b; } function tweakUp(uint256 a, uint256 factor) internal pure returns (uint256) { return mulDown(a, ONE + factor); } function tweakDown(uint256 a, uint256 factor) internal pure returns (uint256) { return mulDown(a, ONE - factor); } /// @return res = min(a + b, bound) /// @dev This function should handle arithmetic operation and bound check without overflow/underflow function addWithUpperBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) { unchecked { if (type(uint256).max - b < a) res = bound; else res = min(bound, a + b); } } /// @return res = max(a - b, bound) /// @dev This function should handle arithmetic operation and bound check without overflow/underflow function subWithLowerBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) { unchecked { if (b > a) res = bound; else res = max(a - b, bound); } } function clamp(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256 res) { res = x; if (x < lower) res = lower; else if (x > upper) res = upper; } // @author Uniswap function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function square(uint256 x) internal pure returns (uint256) { return x * x; } function squareDown(uint256 x) internal pure returns (uint256) { return mulDown(x, x); } function abs(int256 x) internal pure returns (uint256) { return uint256(x > 0 ? x : -x); } function neg(int256 x) internal pure returns (int256) { return x * (-1); } function neg(uint256 x) internal pure returns (int256) { return Int(x) * (-1); } function max(uint256 x, uint256 y) internal pure returns (uint256) { return (x > y ? x : y); } function max(int256 x, int256 y) internal pure returns (int256) { return (x > y ? x : y); } function min(uint256 x, uint256 y) internal pure returns (uint256) { return (x < y ? x : y); } function min(int256 x, int256 y) internal pure returns (int256) { return (x < y ? x : y); } /*/////////////////////////////////////////////////////////////// SIGNED CASTS //////////////////////////////////////////////////////////////*/ function Int(uint256 x) internal pure returns (int256) { require(x <= uint256(type(int256).max)); return int256(x); } function Int128(int256 x) internal pure returns (int128) { require(type(int128).min <= x && x <= type(int128).max); return int128(x); } function Int128(uint256 x) internal pure returns (int128) { return Int128(Int(x)); } /*/////////////////////////////////////////////////////////////// UNSIGNED CASTS //////////////////////////////////////////////////////////////*/ function Uint(int256 x) internal pure returns (uint256) { require(x >= 0); return uint256(x); } function Uint32(uint256 x) internal pure returns (uint32) { require(x <= type(uint32).max); return uint32(x); } function Uint64(uint256 x) internal pure returns (uint64) { require(x <= type(uint64).max); return uint64(x); } function Uint112(uint256 x) internal pure returns (uint112) { require(x <= type(uint112).max); return uint112(x); } function Uint96(uint256 x) internal pure returns (uint96) { require(x <= type(uint96).max); return uint96(x); } function Uint128(uint256 x) internal pure returns (uint128) { require(x <= type(uint128).max); return uint128(x); } function Uint192(uint256 x) internal pure returns (uint192) { require(x <= type(uint192).max); return uint192(x); } function Uint80(uint256 x) internal pure returns (uint80) { require(x <= type(uint80).max); return uint80(x); } function isAApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps); } function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { return a >= b && a <= mulDown(b, ONE + eps); } function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) { return a <= b && a >= mulDown(b, ONE - eps); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library MiniHelpers { function isCurrentlyExpired(uint256 expiry) internal view returns (bool) { return (expiry <= block.timestamp); } function isExpired(uint256 expiry, uint256 blockTime) internal pure returns (bool) { return (expiry <= blockTime); } function isTimeInThePast(uint256 timestamp) internal view returns (bool) { return (timestamp <= block.timestamp); // same definition as isCurrentlyExpired } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../libraries/math/PMath.sol"; import "../libraries/math/LogExpMath.sol"; import "../StandardizedYield/PYIndex.sol"; import "../libraries/MiniHelpers.sol"; import "../libraries/Errors.sol"; struct MarketState { int256 totalPt; int256 totalSy; int256 totalLp; address treasury; /// immutable variables /// int256 scalarRoot; uint256 expiry; /// fee data /// uint256 lnFeeRateRoot; uint256 reserveFeePercent; // base 100 /// last trade data /// uint256 lastLnImpliedRate; } // params that are expensive to compute, therefore we pre-compute them struct MarketPreCompute { int256 rateScalar; int256 totalAsset; int256 rateAnchor; int256 feeRate; } // solhint-disable ordering library MarketMathCore { using PMath for uint256; using PMath for int256; using LogExpMath for int256; using PYIndexLib for PYIndex; int256 internal constant MINIMUM_LIQUIDITY = 10 ** 3; int256 internal constant PERCENTAGE_DECIMALS = 100; uint256 internal constant DAY = 86400; uint256 internal constant IMPLIED_RATE_TIME = 365 * DAY; int256 internal constant MAX_MARKET_PROPORTION = (1e18 * 96) / 100; using PMath for uint256; using PMath for int256; /*/////////////////////////////////////////////////////////////// UINT FUNCTIONS TO PROXY TO CORE FUNCTIONS //////////////////////////////////////////////////////////////*/ function addLiquidity( MarketState memory market, uint256 syDesired, uint256 ptDesired, uint256 blockTime ) internal pure returns (uint256 lpToReserve, uint256 lpToAccount, uint256 syUsed, uint256 ptUsed) { (int256 _lpToReserve, int256 _lpToAccount, int256 _syUsed, int256 _ptUsed) = addLiquidityCore( market, syDesired.Int(), ptDesired.Int(), blockTime ); lpToReserve = _lpToReserve.Uint(); lpToAccount = _lpToAccount.Uint(); syUsed = _syUsed.Uint(); ptUsed = _ptUsed.Uint(); } function removeLiquidity( MarketState memory market, uint256 lpToRemove ) internal pure returns (uint256 netSyToAccount, uint256 netPtToAccount) { (int256 _syToAccount, int256 _ptToAccount) = removeLiquidityCore(market, lpToRemove.Int()); netSyToAccount = _syToAccount.Uint(); netPtToAccount = _ptToAccount.Uint(); } function swapExactPtForSy( MarketState memory market, PYIndex index, uint256 exactPtToMarket, uint256 blockTime ) internal pure returns (uint256 netSyToAccount, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore( market, index, exactPtToMarket.neg(), blockTime ); netSyToAccount = _netSyToAccount.Uint(); netSyFee = _netSyFee.Uint(); netSyToReserve = _netSyToReserve.Uint(); } function swapSyForExactPt( MarketState memory market, PYIndex index, uint256 exactPtToAccount, uint256 blockTime ) internal pure returns (uint256 netSyToMarket, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore( market, index, exactPtToAccount.Int(), blockTime ); netSyToMarket = _netSyToAccount.neg().Uint(); netSyFee = _netSyFee.Uint(); netSyToReserve = _netSyToReserve.Uint(); } /*/////////////////////////////////////////////////////////////// CORE FUNCTIONS //////////////////////////////////////////////////////////////*/ function addLiquidityCore( MarketState memory market, int256 syDesired, int256 ptDesired, uint256 blockTime ) internal pure returns (int256 lpToReserve, int256 lpToAccount, int256 syUsed, int256 ptUsed) { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (syDesired == 0 || ptDesired == 0) revert Errors.MarketZeroAmountsInput(); if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ if (market.totalLp == 0) { lpToAccount = PMath.sqrt((syDesired * ptDesired).Uint()).Int() - MINIMUM_LIQUIDITY; lpToReserve = MINIMUM_LIQUIDITY; syUsed = syDesired; ptUsed = ptDesired; } else { int256 netLpByPt = (ptDesired * market.totalLp) / market.totalPt; int256 netLpBySy = (syDesired * market.totalLp) / market.totalSy; if (netLpByPt < netLpBySy) { lpToAccount = netLpByPt; ptUsed = ptDesired; syUsed = (market.totalSy * lpToAccount).rawDivUp(market.totalLp); } else { lpToAccount = netLpBySy; syUsed = syDesired; ptUsed = (market.totalPt * lpToAccount).rawDivUp(market.totalLp); } } if (lpToAccount <= 0 || syUsed <= 0 || ptUsed <= 0) revert Errors.MarketZeroAmountsOutput(); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ market.totalSy += syUsed; market.totalPt += ptUsed; market.totalLp += lpToAccount + lpToReserve; } function removeLiquidityCore( MarketState memory market, int256 lpToRemove ) internal pure returns (int256 netSyToAccount, int256 netPtToAccount) { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (lpToRemove == 0) revert Errors.MarketZeroAmountsInput(); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ netSyToAccount = (lpToRemove * market.totalSy) / market.totalLp; netPtToAccount = (lpToRemove * market.totalPt) / market.totalLp; if (netSyToAccount == 0 && netPtToAccount == 0) revert Errors.MarketZeroAmountsOutput(); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ market.totalLp = market.totalLp.subNoNeg(lpToRemove); market.totalPt = market.totalPt.subNoNeg(netPtToAccount); market.totalSy = market.totalSy.subNoNeg(netSyToAccount); } function executeTradeCore( MarketState memory market, PYIndex index, int256 netPtToAccount, uint256 blockTime ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); if (market.totalPt <= netPtToAccount) revert Errors.MarketInsufficientPtForTrade(market.totalPt, netPtToAccount); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ MarketPreCompute memory comp = getMarketPreCompute(market, index, blockTime); (netSyToAccount, netSyFee, netSyToReserve) = calcTrade(market, comp, index, netPtToAccount); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ _setNewMarketStateTrade(market, comp, index, netPtToAccount, netSyToAccount, netSyToReserve, blockTime); } function getMarketPreCompute( MarketState memory market, PYIndex index, uint256 blockTime ) internal pure returns (MarketPreCompute memory res) { if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); uint256 timeToExpiry = market.expiry - blockTime; res.rateScalar = _getRateScalar(market, timeToExpiry); res.totalAsset = index.syToAsset(market.totalSy); if (market.totalPt == 0 || res.totalAsset == 0) revert Errors.MarketZeroTotalPtOrTotalAsset(market.totalPt, res.totalAsset); res.rateAnchor = _getRateAnchor( market.totalPt, market.lastLnImpliedRate, res.totalAsset, res.rateScalar, timeToExpiry ); res.feeRate = _getExchangeRateFromImpliedRate(market.lnFeeRateRoot, timeToExpiry); } function calcTrade( MarketState memory market, MarketPreCompute memory comp, PYIndex index, int256 netPtToAccount ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) { int256 preFeeExchangeRate = _getExchangeRate( market.totalPt, comp.totalAsset, comp.rateScalar, comp.rateAnchor, netPtToAccount ); int256 preFeeAssetToAccount = netPtToAccount.divDown(preFeeExchangeRate).neg(); int256 fee = comp.feeRate; if (netPtToAccount > 0) { int256 postFeeExchangeRate = preFeeExchangeRate.divDown(fee); if (postFeeExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(postFeeExchangeRate); fee = preFeeAssetToAccount.mulDown(PMath.IONE - fee); } else { fee = ((preFeeAssetToAccount * (PMath.IONE - fee)) / fee).neg(); } int256 netAssetToReserve = (fee * market.reserveFeePercent.Int()) / PERCENTAGE_DECIMALS; int256 netAssetToAccount = preFeeAssetToAccount - fee; netSyToAccount = netAssetToAccount < 0 ? index.assetToSyUp(netAssetToAccount) : index.assetToSy(netAssetToAccount); netSyFee = index.assetToSy(fee); netSyToReserve = index.assetToSy(netAssetToReserve); } function _setNewMarketStateTrade( MarketState memory market, MarketPreCompute memory comp, PYIndex index, int256 netPtToAccount, int256 netSyToAccount, int256 netSyToReserve, uint256 blockTime ) internal pure { uint256 timeToExpiry = market.expiry - blockTime; market.totalPt = market.totalPt.subNoNeg(netPtToAccount); market.totalSy = market.totalSy.subNoNeg(netSyToAccount + netSyToReserve); market.lastLnImpliedRate = _getLnImpliedRate( market.totalPt, index.syToAsset(market.totalSy), comp.rateScalar, comp.rateAnchor, timeToExpiry ); if (market.lastLnImpliedRate == 0) revert Errors.MarketZeroLnImpliedRate(); } function _getRateAnchor( int256 totalPt, uint256 lastLnImpliedRate, int256 totalAsset, int256 rateScalar, uint256 timeToExpiry ) internal pure returns (int256 rateAnchor) { int256 newExchangeRate = _getExchangeRateFromImpliedRate(lastLnImpliedRate, timeToExpiry); if (newExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(newExchangeRate); { int256 proportion = totalPt.divDown(totalPt + totalAsset); int256 lnProportion = _logProportion(proportion); rateAnchor = newExchangeRate - lnProportion.divDown(rateScalar); } } /// @notice Calculates the current market implied rate. /// @return lnImpliedRate the implied rate function _getLnImpliedRate( int256 totalPt, int256 totalAsset, int256 rateScalar, int256 rateAnchor, uint256 timeToExpiry ) internal pure returns (uint256 lnImpliedRate) { // This will check for exchange rates < PMath.IONE int256 exchangeRate = _getExchangeRate(totalPt, totalAsset, rateScalar, rateAnchor, 0); // exchangeRate >= 1 so its ln >= 0 uint256 lnRate = exchangeRate.ln().Uint(); lnImpliedRate = (lnRate * IMPLIED_RATE_TIME) / timeToExpiry; } /// @notice Converts an implied rate to an exchange rate given a time to expiry. The /// formula is E = e^rt function _getExchangeRateFromImpliedRate( uint256 lnImpliedRate, uint256 timeToExpiry ) internal pure returns (int256 exchangeRate) { uint256 rt = (lnImpliedRate * timeToExpiry) / IMPLIED_RATE_TIME; exchangeRate = LogExpMath.exp(rt.Int()); } function _getExchangeRate( int256 totalPt, int256 totalAsset, int256 rateScalar, int256 rateAnchor, int256 netPtToAccount ) internal pure returns (int256 exchangeRate) { int256 numerator = totalPt.subNoNeg(netPtToAccount); int256 proportion = (numerator.divDown(totalPt + totalAsset)); if (proportion > MAX_MARKET_PROPORTION) revert Errors.MarketProportionTooHigh(proportion, MAX_MARKET_PROPORTION); int256 lnProportion = _logProportion(proportion); exchangeRate = lnProportion.divDown(rateScalar) + rateAnchor; if (exchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(exchangeRate); } function _logProportion(int256 proportion) internal pure returns (int256 res) { if (proportion == PMath.IONE) revert Errors.MarketProportionMustNotEqualOne(); int256 logitP = proportion.divDown(PMath.IONE - proportion); res = logitP.ln(); } function _getRateScalar(MarketState memory market, uint256 timeToExpiry) internal pure returns (int256 rateScalar) { rateScalar = (market.scalarRoot * IMPLIED_RATE_TIME.Int()) / timeToExpiry.Int(); if (rateScalar <= 0) revert Errors.MarketRateScalarBelowZero(rateScalar); } function setInitialLnImpliedRate( MarketState memory market, PYIndex index, int256 initialAnchor, uint256 blockTime ) internal pure { /// ------------------------------------------------------------ /// CHECKS /// ------------------------------------------------------------ if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired(); /// ------------------------------------------------------------ /// MATH /// ------------------------------------------------------------ int256 totalAsset = index.syToAsset(market.totalSy); uint256 timeToExpiry = market.expiry - blockTime; int256 rateScalar = _getRateScalar(market, timeToExpiry); /// ------------------------------------------------------------ /// WRITE /// ------------------------------------------------------------ market.lastLnImpliedRate = _getLnImpliedRate( market.totalPt, totalAsset, rateScalar, initialAnchor, timeToExpiry ); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../interfaces/IPYieldToken.sol"; import "../../interfaces/IPPrincipalToken.sol"; import "./SYUtils.sol"; import "../libraries/math/PMath.sol"; type PYIndex is uint256; library PYIndexLib { using PMath for uint256; using PMath for int256; function newIndex(IPYieldToken YT) internal returns (PYIndex) { return PYIndex.wrap(YT.pyIndexCurrent()); } function syToAsset(PYIndex index, uint256 syAmount) internal pure returns (uint256) { return SYUtils.syToAsset(PYIndex.unwrap(index), syAmount); } function assetToSy(PYIndex index, uint256 assetAmount) internal pure returns (uint256) { return SYUtils.assetToSy(PYIndex.unwrap(index), assetAmount); } function assetToSyUp(PYIndex index, uint256 assetAmount) internal pure returns (uint256) { return SYUtils.assetToSyUp(PYIndex.unwrap(index), assetAmount); } function syToAssetUp(PYIndex index, uint256 syAmount) internal pure returns (uint256) { uint256 _index = PYIndex.unwrap(index); return SYUtils.syToAssetUp(_index, syAmount); } function syToAsset(PYIndex index, int256 syAmount) internal pure returns (int256) { int256 sign = syAmount < 0 ? int256(-1) : int256(1); return sign * (SYUtils.syToAsset(PYIndex.unwrap(index), syAmount.abs())).Int(); } function assetToSy(PYIndex index, int256 assetAmount) internal pure returns (int256) { int256 sign = assetAmount < 0 ? int256(-1) : int256(1); return sign * (SYUtils.assetToSy(PYIndex.unwrap(index), assetAmount.abs())).Int(); } function assetToSyUp(PYIndex index, int256 assetAmount) internal pure returns (int256) { int256 sign = assetAmount < 0 ? int256(-1) : int256(1); return sign * (SYUtils.assetToSyUp(PYIndex.unwrap(index), assetAmount.abs())).Int(); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; library SYUtils { uint256 internal constant ONE = 1e18; function syToAsset(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) { return (syAmount * exchangeRate) / ONE; } function syToAssetUp(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) { return (syAmount * exchangeRate + ONE - 1) / ONE; } function assetToSy(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) { return (assetAmount * ONE) / exchangeRate; } function assetToSyUp(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) { return (assetAmount * ONE + exchangeRate - 1) / exchangeRate; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPActionInfoStatic { struct TokenAmount { address token; uint256 amount; } struct UserSYInfo { TokenAmount syBalance; TokenAmount[] unclaimedRewards; } struct UserPYInfo { TokenAmount ptBalance; TokenAmount ytBalance; TokenAmount unclaimedInterest; TokenAmount[] unclaimedRewards; } struct UserMarketInfo { TokenAmount lpBalance; TokenAmount ptBalance; TokenAmount syBalance; TokenAmount[] unclaimedRewards; } function getPY(address py) external view returns (address pt, address yt); /// can be SY, PY or Market function getTokensInOut( address token ) external view returns (address[] memory tokensIn, address[] memory tokensOut); function getUserSYInfo(address sy, address user) external returns (UserSYInfo memory res); function getUserPYInfo(address py, address user) external returns (UserPYInfo memory res); function getUserMarketInfo(address market, address user) external returns (UserMarketInfo memory res); }
// SPDX-License-Identifier: None pragma solidity ^0.8.0; import "./IPMarket.sol"; import {ApproxParams} from "../router/math/MarketApproxLibV2.sol"; interface IPActionMarketAuxStatic { function calcPriceImpactPY(address market, int256 netPtOut) external view returns (uint256); function calcPriceImpactPt(address market, int256 netPtOut) external view returns (uint256); function calcPriceImpactYt(address market, int256 netPtOut) external view returns (uint256); function getMarketState( address market ) external view returns ( address pt, address yt, address sy, int256 impliedYield, uint256 marketExchangeRateExcludeFee, MarketState memory state ); function getTradeExchangeRateExcludeFee(address market, MarketState memory state) external view returns (uint256); function getTradeExchangeRateIncludeFee(address market, int256 netPtOut) external view returns (uint256); function getYieldTokenAndPtRate( address market ) external view returns (address yieldToken, uint256 netPtOut, uint256 netYieldTokenOut); function getYieldTokenAndYtRate( address market ) external view returns (address yieldToken, uint256 netYtOut, uint256 netYieldTokenOut); function getLpToSyRate(address market) external view returns (uint256); function getPtToSyRate(address market) external view returns (uint256); function getYtToSyRate(address market) external view returns (uint256); function getLpToAssetRate(address market) external view returns (uint256); function getPtToAssetRate(address market) external view returns (uint256); function getYtToAssetRate(address market) external view returns (uint256); /// @param slippage A fixed-point number with 18 decimal places function swapExactSyForPtStaticAndGenerateApproxParams( address market, uint256 exactSyIn, uint256 slippage ) external view returns ( uint256 netPtOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, ApproxParams memory approxParams ); /// @param slippage A fixed-point number with 18 decimal places function swapExactTokenForPtStaticAndGenerateApproxParams( address market, address tokenIn, uint256 amountTokenIn, uint256 slippage ) external view returns ( uint256 netPtOut, uint256 netSyMinted, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, ApproxParams memory approxParams ); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IPMarket.sol"; interface IPActionMarketCoreStatic { function addLiquidityDualSyAndPtStatic( address market, uint256 netSyDesired, uint256 netPtDesired ) external view returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed); function addLiquidityDualTokenAndPtStatic( address market, address tokenIn, uint256 netTokenDesired, uint256 netPtDesired ) external view returns (uint256 netLpOut, uint256 netTokenUsed, uint256 netPtUsed, uint256 netSyUsed, uint256 netSyDesired); function addLiquiditySinglePtStatic( address market, uint256 netPtIn ) external view returns ( uint256 netLpOut, uint256 netPtToSwap, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyFromSwap ); function addLiquiditySingleSyKeepYtStatic( address market, uint256 netSyIn ) external view returns (uint256 netLpOut, uint256 netYtOut, uint256 netSyToPY); function addLiquiditySingleSyStatic( address market, uint256 netSyIn ) external view returns ( uint256 netLpOut, uint256 netPtFromSwap, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyToSwap ); function addLiquiditySingleTokenKeepYtStatic( address market, address tokenIn, uint256 netTokenIn ) external view returns (uint256 netLpOut, uint256 netYtOut, uint256 netSyMinted, uint256 netSyToPY); function addLiquiditySingleTokenStatic( address market, address tokenIn, uint256 netTokenIn ) external view returns ( uint256 netLpOut, uint256 netPtFromSwap, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyMinted, uint256 netSyToSwap ); function removeLiquidityDualSyAndPtStatic( address market, uint256 netLpToRemove ) external view returns (uint256 netSyOut, uint256 netPtOut); function removeLiquidityDualTokenAndPtStatic( address market, uint256 netLpToRemove, address tokenOut ) external view returns (uint256 netTokenOut, uint256 netPtOut, uint256 netSyToRedeem); function removeLiquiditySinglePtStatic( address market, uint256 netLpToRemove ) external view returns ( uint256 netPtOut, uint256 netPtFromSwap, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyFromBurn, uint256 netPtFromBurn ); function removeLiquiditySingleSyStatic( address market, uint256 netLpToRemove ) external view returns ( uint256 netSyOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyFromBurn, uint256 netPtFromBurn, uint256 netSyFromSwap ); function removeLiquiditySingleTokenStatic( address market, uint256 netLpToRemove, address tokenOut ) external view returns ( uint256 netTokenOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyOut, uint256 netSyFromBurn, uint256 netPtFromBurn, uint256 netSyFromSwap ); function swapExactPtForSyStatic( address market, uint256 exactPtIn ) external view returns (uint256 netSyOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter); function swapExactPtForTokenStatic( address market, uint256 exactPtIn, address tokenOut ) external view returns ( uint256 netTokenOut, uint256 netSyToRedeem, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter ); function swapExactPtForYtStatic( address market, uint256 exactPtIn ) external view returns ( uint256 netYtOut, uint256 totalPtToSwap, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter ); function swapExactSyForPtStatic( address market, uint256 exactSyIn ) external view returns (uint256 netPtOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter); function swapExactSyForYtStatic( address market, uint256 exactSyIn ) external view returns (uint256 netYtOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter); function swapExactTokenForPtStatic( address market, address tokenIn, uint256 amountTokenIn ) external view returns ( uint256 netPtOut, uint256 netSyMinted, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter ); function swapExactTokenForYtStatic( address market, address tokenIn, uint256 amountTokenIn ) external view returns ( uint256 netYtOut, uint256 netSyMinted, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter ); function swapExactYtForPtStatic( address market, uint256 exactYtIn ) external view returns ( uint256 netPtOut, uint256 totalPtSwapped, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter ); function swapExactYtForSyStatic( address market, uint256 exactYtIn ) external view returns ( uint256 netSyOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyOwedInt, uint256 netPYToRepaySyOwedInt, uint256 netPYToRedeemSyOutInt ); function swapExactYtForTokenStatic( address market, uint256 exactYtIn, address tokenOut ) external view returns ( uint256 netTokenOut, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyOut, uint256 netSyOwedInt, uint256 netPYToRepaySyOwedInt, uint256 netPYToRedeemSyOutInt ); function swapPtForExactSyStatic( address market, uint256 exactSyOut ) external view returns (uint256 netPtIn, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter); function swapSyForExactPtStatic( address market, uint256 exactPtOut ) external view returns (uint256 netSyIn, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter); function swapSyForExactYtStatic( address market, uint256 exactYtOut ) external view returns ( uint256 netSyIn, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter, uint256 netSyReceivedInt, uint256 totalSyNeedInt ); function swapYtForExactSyStatic( address market, uint256 exactSyOut ) external view returns (uint256 netYtIn, uint256 netSyFee, uint256 priceImpact, uint256 exchangeRateAfter); function readMarketState(address market) external view returns (MarketState memory); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPActionMintRedeemStatic { function getAmountTokenToMintSy( address SY, address tokenIn, uint256 netSyOut ) external view returns (uint256 netTokenIn); function mintPyFromSyStatic(address YT, uint256 netSyToMint) external view returns (uint256 netPYOut); function mintPyFromTokenStatic( address YT, address tokenIn, uint256 netTokenIn ) external view returns (uint256 netPyOut); function mintSyFromTokenStatic( address SY, address tokenIn, uint256 netTokenIn ) external view returns (uint256 netSyOut); function redeemPyToSyStatic(address YT, uint256 netPYToRedeem) external view returns (uint256 netSyOut); function redeemPyToTokenStatic( address YT, uint256 netPYToRedeem, address tokenOut ) external view returns (uint256 netTokenOut); function redeemSyToTokenStatic( address SY, address tokenOut, uint256 netSyIn ) external view returns (uint256 netTokenOut); function pyIndexCurrentViewMarket(address market) external view returns (uint256); function pyIndexCurrentViewYt(address yt) external view returns (uint256); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../router/math/MarketApproxLibV2.sol"; import {IPAllEventsV3} from "./IPAllEventsV3.sol"; interface IPActionStorageStatic is IPAllEventsV3 { function setDefaultApproxParams(ApproxParams memory params) external; function getDefaultApproxParams() external view returns (ApproxParams memory); function getOwnerAndPendingOwner() external view returns (address _owner, address _pendingOwner); function transferOwnership(address newOwner, bool direct, bool renounce) external; function claimOwnership() external; }
// SPDX-License-Identifier: None pragma solidity ^0.8.0; interface IPActionVePendleStatic { function increaseLockPositionStatic( address user, uint128 additionalAmountToLock, uint128 newExpiry ) external view returns (uint128 newVeBalance); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../router/swap-aggregator/IPSwapAggregator.sol"; import "./IPLimitRouter.sol"; /* * NOTICE: * For detailed information on TokenInput, TokenOutput, ApproxParams, and LimitOrderData, * refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter * * It's recommended to use Pendle's Hosted SDK to generate these parameters for: * 1. Optimal liquidity and gas efficiency * 2. Access to deeper liquidity via limit orders * 3. Zapping in/out using any ERC20 token * * Else, to generate these parameters fully onchain, use the following functions: * - For TokenInput: Use createTokenInputSimple * - For TokenOutput: Use createTokenOutputSimple * - For ApproxParams: Use createDefaultApproxParams * - For LimitOrderData: Use createEmptyLimitOrderData * * These generated parameters can be directly passed into the respective function calls. * * Examples: * * addLiquiditySingleToken( * msg.sender, * MARKET_ADDRESS, * minLpOut, * createDefaultApproxParams(), * createTokenInputSimple(USDC_ADDRESS, 1000e6), * createEmptyLimitOrderData() * ) * * swapExactTokenForPt( * msg.sender, * MARKET_ADDRESS, * minPtOut, * createDefaultApproxParams(), * createTokenInputSimple(USDC_ADDRESS, 1000e6), * createEmptyLimitOrderData() * ) */ /// @dev Creates a TokenInput struct without using any swap aggregator /// @param tokenIn must be one of the SY's tokens in (obtain via `IStandardizedYield#getTokensIn`) /// @param netTokenIn amount of token in function createTokenInputSimple(address tokenIn, uint256 netTokenIn) pure returns (TokenInput memory) { return TokenInput({ tokenIn: tokenIn, netTokenIn: netTokenIn, tokenMintSy: tokenIn, pendleSwap: address(0), swapData: createSwapTypeNoAggregator() }); } /// @dev Creates a TokenOutput struct without using any swap aggregator /// @param tokenOut must be one of the SY's tokens out (obtain via `IStandardizedYield#getTokensOut`) /// @param minTokenOut minimum amount of token out function createTokenOutputSimple(address tokenOut, uint256 minTokenOut) pure returns (TokenOutput memory) { return TokenOutput({ tokenOut: tokenOut, minTokenOut: minTokenOut, tokenRedeemSy: tokenOut, pendleSwap: address(0), swapData: createSwapTypeNoAggregator() }); } function createEmptyLimitOrderData() pure returns (LimitOrderData memory) {} /// @dev Creates default ApproxParams for on-chain approximation function createDefaultApproxParams() pure returns (ApproxParams memory) { return ApproxParams({guessMin: 0, guessMax: type(uint256).max, guessOffchain: 0, maxIteration: 256, eps: 1e14}); } function createSwapTypeNoAggregator() pure returns (SwapData memory) {} struct TokenInput { address tokenIn; uint256 netTokenIn; address tokenMintSy; address pendleSwap; SwapData swapData; } struct TokenOutput { address tokenOut; uint256 minTokenOut; address tokenRedeemSy; address pendleSwap; SwapData swapData; } struct LimitOrderData { address limitRouter; uint256 epsSkipMarket; FillOrderParams[] normalFills; FillOrderParams[] flashFills; bytes optData; } struct ApproxParams { uint256 guessMin; uint256 guessMax; uint256 guessOffchain; uint256 maxIteration; uint256 eps; } struct ExitPreExpReturnParams { uint256 netPtFromRemove; uint256 netSyFromRemove; uint256 netPyRedeem; uint256 netSyFromRedeem; uint256 netPtSwap; uint256 netYtSwap; uint256 netSyFromSwap; uint256 netSyFee; uint256 totalSyOut; } struct ExitPostExpReturnParams { uint256 netPtFromRemove; uint256 netSyFromRemove; uint256 netPtRedeem; uint256 netSyFromRedeem; uint256 totalSyOut; } struct RedeemYtIncomeToTokenStruct { IPYieldToken yt; bool doRedeemInterest; bool doRedeemRewards; address tokenRedeemSy; uint256 minTokenRedeemOut; }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import {ExitPreExpReturnParams, ExitPostExpReturnParams} from "./IPAllActionTypeV3.sol"; interface IPActionAddRemoveLiqV3Events { event AddLiquidityDualSyAndPt( address indexed caller, address indexed market, address indexed receiver, uint256 netSyUsed, uint256 netPtUsed, uint256 netLpOut ); event AddLiquidityDualTokenAndPt( address indexed caller, address indexed market, address indexed tokenIn, address receiver, uint256 netTokenUsed, uint256 netPtUsed, uint256 netLpOut, uint256 netSyInterm ); event AddLiquiditySinglePt( address indexed caller, address indexed market, address indexed receiver, uint256 netPtIn, uint256 netLpOut ); event AddLiquiditySingleSy( address indexed caller, address indexed market, address indexed receiver, uint256 netSyIn, uint256 netLpOut ); event AddLiquiditySingleToken( address indexed caller, address indexed market, address indexed token, address receiver, uint256 netTokenIn, uint256 netLpOut, uint256 netSyInterm ); event AddLiquiditySingleSyKeepYt( address indexed caller, address indexed market, address indexed receiver, uint256 netSyIn, uint256 netSyMintPy, uint256 netLpOut, uint256 netYtOut ); event AddLiquiditySingleTokenKeepYt( address indexed caller, address indexed market, address indexed token, address receiver, uint256 netTokenIn, uint256 netLpOut, uint256 netYtOut, uint256 netSyMintPy, uint256 netSyInterm ); event RemoveLiquidityDualSyAndPt( address indexed caller, address indexed market, address indexed receiver, uint256 netLpToRemove, uint256 netPtOut, uint256 netSyOut ); event RemoveLiquidityDualTokenAndPt( address indexed caller, address indexed market, address indexed tokenOut, address receiver, uint256 netLpToRemove, uint256 netPtOut, uint256 netTokenOut, uint256 netSyInterm ); event RemoveLiquiditySinglePt( address indexed caller, address indexed market, address indexed receiver, uint256 netLpToRemove, uint256 netPtOut ); event RemoveLiquiditySingleSy( address indexed caller, address indexed market, address indexed receiver, uint256 netLpToRemove, uint256 netSyOut ); event RemoveLiquiditySingleToken( address indexed caller, address indexed market, address indexed token, address receiver, uint256 netLpToRemove, uint256 netTokenOut, uint256 netSyInterm ); } interface IPActionSwapPTV3Events { event SwapPtAndSy( address indexed caller, address indexed market, address indexed receiver, int256 netPtToAccount, int256 netSyToAccount ); event SwapPtAndToken( address indexed caller, address indexed market, address indexed token, address receiver, int256 netPtToAccount, int256 netTokenToAccount, uint256 netSyInterm ); } interface IPActionSwapYTV3Events { event SwapYtAndSy( address indexed caller, address indexed market, address indexed receiver, int256 netYtToAccount, int256 netSyToAccount ); event SwapYtAndToken( address indexed caller, address indexed market, address indexed token, address receiver, int256 netYtToAccount, int256 netTokenToAccount, uint256 netSyInterm ); } interface IPActionMiscV3Events { event MintSyFromToken( address indexed caller, address indexed tokenIn, address indexed SY, address receiver, uint256 netTokenIn, uint256 netSyOut ); event RedeemSyToToken( address indexed caller, address indexed tokenOut, address indexed SY, address receiver, uint256 netSyIn, uint256 netTokenOut ); event MintPyFromSy( address indexed caller, address indexed receiver, address indexed YT, uint256 netSyIn, uint256 netPyOut ); event RedeemPyToSy( address indexed caller, address indexed receiver, address indexed YT, uint256 netPyIn, uint256 netSyOut ); event MintPyFromToken( address indexed caller, address indexed tokenIn, address indexed YT, address receiver, uint256 netTokenIn, uint256 netPyOut, uint256 netSyInterm ); event RedeemPyToToken( address indexed caller, address indexed tokenOut, address indexed YT, address receiver, uint256 netPyIn, uint256 netTokenOut, uint256 netSyInterm ); event ExitPreExpToToken( address indexed caller, address indexed market, address indexed token, address receiver, uint256 netLpIn, uint256 totalTokenOut, ExitPreExpReturnParams params ); event ExitPreExpToSy( address indexed caller, address indexed market, address indexed receiver, uint256 netLpIn, ExitPreExpReturnParams params ); event ExitPostExpToToken( address indexed caller, address indexed market, address indexed token, address receiver, uint256 netLpIn, uint256 totalTokenOut, ExitPostExpReturnParams params ); event ExitPostExpToSy( address indexed caller, address indexed market, address indexed receiver, uint256 netLpIn, ExitPostExpReturnParams params ); } interface IPActionStorageEvents { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event SelectorToFacetSet(bytes4 indexed selector, address indexed facet); } interface IPAllEventsV3 is IPActionAddRemoveLiqV3Events, IPActionSwapPTV3Events, IPActionSwapYTV3Events, IPActionMiscV3Events, IPActionStorageEvents {}
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPGauge { function totalActiveSupply() external view returns (uint256); function activeBalance(address user) external view returns (uint256); // only available for newer factories. please check the verified contracts event RedeemRewards(address indexed user, uint256[] rewardsOut); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPInterestManagerYT { event CollectInterestFee(uint256 amountInterestFee); function userInterest(address user) external view returns (uint128 lastPYIndex, uint128 accruedInterest); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../core/StandardizedYield/PYIndex.sol"; interface IPLimitOrderType { enum OrderType { SY_FOR_PT, PT_FOR_SY, SY_FOR_YT, YT_FOR_SY } // Fixed-size order part with core information struct StaticOrder { uint256 salt; uint256 expiry; uint256 nonce; OrderType orderType; address token; address YT; address maker; address receiver; uint256 makingAmount; uint256 lnImpliedRate; uint256 failSafeRate; } struct FillResults { uint256 totalMaking; uint256 totalTaking; uint256 totalFee; uint256 totalNotionalVolume; uint256[] netMakings; uint256[] netTakings; uint256[] netFees; uint256[] notionalVolumes; } } struct Order { uint256 salt; uint256 expiry; uint256 nonce; IPLimitOrderType.OrderType orderType; address token; address YT; address maker; address receiver; uint256 makingAmount; uint256 lnImpliedRate; uint256 failSafeRate; bytes permit; } struct FillOrderParams { Order order; bytes signature; uint256 makingAmount; } interface IPLimitRouterCallback is IPLimitOrderType { function limitRouterCallback( uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory data ) external returns (bytes memory); } interface IPLimitRouter is IPLimitOrderType { struct OrderStatus { uint128 filledAmount; uint128 remaining; } event OrderCanceled(address indexed maker, bytes32 indexed orderHash); event OrderFilledV2( bytes32 indexed orderHash, OrderType indexed orderType, address indexed YT, address token, uint256 netInputFromMaker, uint256 netOutputToMaker, uint256 feeAmount, uint256 notionalVolume, address maker, address taker ); // event added on 2/1/2025 event LnFeeRateRootsSet(address[] YTs, uint256[] lnFeeRateRoots); // @dev actualMaking, actualTaking are in the SY form function fill( FillOrderParams[] memory params, address receiver, uint256 maxTaking, bytes calldata optData, bytes calldata callback ) external returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn); function feeRecipient() external view returns (address); function hashOrder(Order memory order) external view returns (bytes32); function cancelSingle(Order calldata order) external; function cancelBatch(Order[] calldata orders) external; function orderStatusesRaw( bytes32[] memory orderHashes ) external view returns (uint256[] memory remainingsRaw, uint256[] memory filledAmounts); function orderStatuses( bytes32[] memory orderHashes ) external view returns (uint256[] memory remainings, uint256[] memory filledAmounts); function DOMAIN_SEPARATOR() external view returns (bytes32); function simulate(address target, bytes calldata data) external payable; function WNATIVE() external view returns (address); function _checkSig( Order memory order, bytes memory signature ) external view returns ( bytes32, /*orderHash*/ uint256, /*remainingMakerAmount*/ uint256 ); /*filledMakerAmount*/ /* --- Deprecated events --- */ // deprecate on 7/1/2024, prior to official launch event OrderFilled( bytes32 indexed orderHash, OrderType indexed orderType, address indexed YT, address token, uint256 netInputFromMaker, uint256 netOutputToMaker, uint256 feeAmount, uint256 notionalVolume ); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./IPPrincipalToken.sol"; import "./IPYieldToken.sol"; import "./IStandardizedYield.sol"; import "./IPGauge.sol"; import "../core/Market/MarketMathCore.sol"; interface IPMarket is IERC20Metadata, IPGauge { event Mint(address indexed receiver, uint256 netLpMinted, uint256 netSyUsed, uint256 netPtUsed); event Burn( address indexed receiverSy, address indexed receiverPt, uint256 netLpBurned, uint256 netSyOut, uint256 netPtOut ); event Swap( address indexed caller, address indexed receiver, int256 netPtOut, int256 netSyOut, uint256 netSyFee, uint256 netSyToReserve ); event UpdateImpliedRate(uint256 indexed timestamp, uint256 lnLastImpliedRate); event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); function mint( address receiver, uint256 netSyDesired, uint256 netPtDesired ) external returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed); function burn( address receiverSy, address receiverPt, uint256 netLpToBurn ) external returns (uint256 netSyOut, uint256 netPtOut); function swapExactPtForSy( address receiver, uint256 exactPtIn, bytes calldata data ) external returns (uint256 netSyOut, uint256 netSyFee); function swapSyForExactPt( address receiver, uint256 exactPtOut, bytes calldata data ) external returns (uint256 netSyIn, uint256 netSyFee); function redeemRewards(address user) external returns (uint256[] memory); function readState(address router) external view returns (MarketState memory market); function observe(uint32[] memory secondsAgos) external view returns (uint216[] memory lnImpliedRateCumulative); function increaseObservationsCardinalityNext(uint16 cardinalityNext) external; function readTokens() external view returns (IStandardizedYield _SY, IPPrincipalToken _PT, IPYieldToken _YT); function getRewardTokens() external view returns (address[] memory); function isExpired() external view returns (bool); function expiry() external view returns (uint256); function observations( uint256 index ) external view returns (uint32 blockTimestamp, uint216 lnImpliedRateCumulative, bool initialized); function _storage() external view returns ( int128 totalPt, int128 totalSy, uint96 lastLnImpliedRate, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext ); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IPMiniDiamond { struct SelectorsToFacet { address facet; bytes4[] selectors; } function setFacetForSelectors(SelectorsToFacet[] calldata arr) external; function facetAddress(bytes4 selector) external view returns (address); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IPPrincipalToken is IERC20Metadata { function burnByYT(address user, uint256 amount) external; function mintByYT(address user, uint256 amount) external; function initialize(address _YT) external; function SY() external view returns (address); function YT() external view returns (address); function factory() external view returns (address); function expiry() external view returns (uint256); function isExpired() external view returns (bool); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IPActionMarketAuxStatic.sol"; import "./IPActionMintRedeemStatic.sol"; import "./IPActionInfoStatic.sol"; import "./IPActionMarketCoreStatic.sol"; import "./IPActionVePendleStatic.sol"; import "./IPMiniDiamond.sol"; import "./IPActionStorageStatic.sol"; //solhint-disable-next-line no-empty-blocks interface IPRouterStatic is IPActionMintRedeemStatic, IPActionInfoStatic, IPActionMarketAuxStatic, IPActionMarketCoreStatic, IPActionVePendleStatic, IPMiniDiamond, IPActionStorageStatic {}
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./IRewardManager.sol"; import "./IPInterestManagerYT.sol"; interface IPYieldToken is IERC20Metadata, IRewardManager, IPInterestManagerYT { event NewInterestIndex(uint256 indexed newIndex); event Mint( address indexed caller, address indexed receiverPT, address indexed receiverYT, uint256 amountSyToMint, uint256 amountPYOut ); event Burn(address indexed caller, address indexed receiver, uint256 amountPYToRedeem, uint256 amountSyOut); event RedeemRewards(address indexed user, uint256[] amountRewardsOut); event RedeemInterest(address indexed user, uint256 interestOut); event CollectRewardFee(address indexed rewardToken, uint256 amountRewardFee); function mintPY(address receiverPT, address receiverYT) external returns (uint256 amountPYOut); function redeemPY(address receiver) external returns (uint256 amountSyOut); function redeemPYMulti( address[] calldata receivers, uint256[] calldata amountPYToRedeems ) external returns (uint256[] memory amountSyOuts); function redeemDueInterestAndRewards( address user, bool redeemInterest, bool redeemRewards ) external returns (uint256 interestOut, uint256[] memory rewardsOut); function rewardIndexesCurrent() external returns (uint256[] memory); function pyIndexCurrent() external returns (uint256); function pyIndexStored() external view returns (uint256); function getRewardTokens() external view returns (address[] memory); function SY() external view returns (address); function PT() external view returns (address); function factory() external view returns (address); function expiry() external view returns (uint256); function isExpired() external view returns (bool); function doCacheIndexSameBlock() external view returns (bool); function pyIndexLastUpdatedBlock() external view returns (uint128); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; interface IRewardManager { function userReward(address token, address user) external view returns (uint128 index, uint128 accrued); }
// SPDX-License-Identifier: GPL-3.0-or-later /* * MIT License * =========== * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; interface IStandardizedYield is IERC20Metadata { /// @dev Emitted when any base tokens is deposited to mint shares event Deposit( address indexed caller, address indexed receiver, address indexed tokenIn, uint256 amountDeposited, uint256 amountSyOut ); /// @dev Emitted when any shares are redeemed for base tokens event Redeem( address indexed caller, address indexed receiver, address indexed tokenOut, uint256 amountSyToRedeem, uint256 amountTokenOut ); /// @dev check `assetInfo()` for more information enum AssetType { TOKEN, LIQUIDITY } /// @dev Emitted when (`user`) claims their rewards event ClaimRewards(address indexed user, address[] rewardTokens, uint256[] rewardAmounts); /** * @notice mints an amount of shares by depositing a base token. * @param receiver shares recipient address * @param tokenIn address of the base tokens to mint shares * @param amountTokenToDeposit amount of base tokens to be transferred from (`msg.sender`) * @param minSharesOut reverts if amount of shares minted is lower than this * @return amountSharesOut amount of shares minted * @dev Emits a {Deposit} event * * Requirements: * - (`tokenIn`) must be a valid base token. */ function deposit( address receiver, address tokenIn, uint256 amountTokenToDeposit, uint256 minSharesOut ) external payable returns (uint256 amountSharesOut); /** * @notice redeems an amount of base tokens by burning some shares * @param receiver recipient address * @param amountSharesToRedeem amount of shares to be burned * @param tokenOut address of the base token to be redeemed * @param minTokenOut reverts if amount of base token redeemed is lower than this * @param burnFromInternalBalance if true, burns from balance of `address(this)`, otherwise burns from `msg.sender` * @return amountTokenOut amount of base tokens redeemed * @dev Emits a {Redeem} event * * Requirements: * - (`tokenOut`) must be a valid base token. */ function redeem( address receiver, uint256 amountSharesToRedeem, address tokenOut, uint256 minTokenOut, bool burnFromInternalBalance ) external returns (uint256 amountTokenOut); /** * @notice exchangeRate * syBalance / 1e18 must return the asset balance of the account * @notice vice-versa, if a user uses some amount of tokens equivalent to X asset, the amount of sy he can mint must be X * exchangeRate / 1e18 * @dev SYUtils's assetToSy & syToAsset should be used instead of raw multiplication & division */ function exchangeRate() external view returns (uint256 res); /** * @notice claims reward for (`user`) * @param user the user receiving their rewards * @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens` * @dev * Emits a `ClaimRewards` event * See {getRewardTokens} for list of reward tokens */ function claimRewards(address user) external returns (uint256[] memory rewardAmounts); /** * @notice get the amount of unclaimed rewards for (`user`) * @param user the user to check for * @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens` */ function accruedRewards(address user) external view returns (uint256[] memory rewardAmounts); function rewardIndexesCurrent() external returns (uint256[] memory indexes); function rewardIndexesStored() external view returns (uint256[] memory indexes); /** * @notice returns the list of reward token addresses */ function getRewardTokens() external view returns (address[] memory); /** * @notice returns the address of the underlying yield token */ function yieldToken() external view returns (address); /** * @notice returns all tokens that can mint this SY */ function getTokensIn() external view returns (address[] memory res); /** * @notice returns all tokens that can be redeemed by this SY */ function getTokensOut() external view returns (address[] memory res); function isValidTokenIn(address token) external view returns (bool); function isValidTokenOut(address token) external view returns (bool); function previewDeposit( address tokenIn, uint256 amountTokenToDeposit ) external view returns (uint256 amountSharesOut); function previewRedeem( address tokenOut, uint256 amountSharesToRedeem ) external view returns (uint256 amountTokenOut); /** * @notice This function contains information to interpret what the asset is * @return assetType the type of the asset (0 for ERC20 tokens, 1 for AMM liquidity tokens, 2 for bridged yield bearing tokens like wstETH, rETH on Arbi whose the underlying asset doesn't exist on the chain) * @return assetAddress the address of the asset * @return assetDecimals the decimals of the asset */ function assetInfo() external view returns (AssetType assetType, address assetAddress, uint8 assetDecimals); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../../core/libraries/math/PMath.sol"; import "../../../core/Market/MarketMathCore.sol"; import {ApproxParams} from "../../../interfaces/IPAllActionTypeV3.sol"; /// Further explanation of the eps. Take swapExactSyForPt for example. To calc the corresponding amount of Pt to swap out, /// it's necessary to run an approximation algorithm, because by default there only exists the Pt to Sy formula /// To approx, the 5 values above will have to be provided, and the approx process will run as follows: /// mid = (guessMin + guessMax) / 2 // mid here is the current guess of the amount of Pt out /// netSyNeed = calcSwapSyForExactPt(mid) /// if (netSyNeed > exactSyIn) guessMax = mid - 1 // since the maximum Sy in can't exceed the exactSyIn /// else guessMin = mid (1) /// For the (1), since netSyNeed <= exactSyIn, the result might be usable. If the netSyNeed is within eps of /// exactSyIn (ex eps=0.1% => we have used 99.9% the amount of Sy specified), mid will be chosen as the final guess result /// for guessOffchain, this is to provide a shortcut to guessing. The offchain SDK can precalculate the exact result /// before the tx is sent. When the tx reaches the contract, the guessOffchain will be checked first, and if it satisfies the /// approximation, it will be used (and save all the guessing). It's expected that this shortcut will be used in most cases /// except in cases that there is a trade in the same market right before the tx library MarketApproxPtInLibV1 { using MarketMathCore for MarketState; using PYIndexLib for PYIndex; using PMath for uint256; using PMath for int256; using LogExpMath for int256; /** * @dev algorithm: * - Bin search the amount of PT to swap in * - Try swapping & get netSyOut * - Stop when netSyOut greater & approx minSyOut * - guess & approx is for netPtIn */ function approxSwapPtForExactSy( MarketState memory market, PYIndex index, uint256 minSyOut, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netPtIn*/ uint256, /*netSyOut*/ uint256 /*netSyFee*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { // no limit on min approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp)); validateApprox(approx); } for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess); if (netSyOut >= minSyOut) { if (PMath.isAGreaterApproxB(netSyOut, minSyOut, approx.eps)) { return (guess, netSyOut, netSyFee); } approx.guessMax = guess; } else { approx.guessMin = guess; } } revert("Slippage: APPROX_EXHAUSTED"); } /** * @dev algorithm: * - Bin search the amount of PT to swap in * - Flashswap the corresponding amount of SY out * - Pair those amount with exactSyIn SY to tokenize into PT & YT * - PT to repay the flashswap, YT transferred to user * - Stop when the amount of SY to be pulled to tokenize PT to repay loan approx the exactSyIn * - guess & approx is for netYtOut (also netPtIn) */ function approxSwapExactSyForYt( MarketState memory market, PYIndex index, uint256 exactSyIn, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netYtOut*/ uint256 /*netSyFee*/, uint256 /*iter*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { approx.guessMin = PMath.max(approx.guessMin, index.syToAsset(exactSyIn)); approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp)); validateApprox(approx); } // at minimum we will flashswap exactSyIn since we have enough SY to payback the PT loan for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess); uint256 netSyToTokenizePt = index.assetToSyUp(guess); // for sure netSyToTokenizePt >= netSyOut since we are swapping PT to SY uint256 netSyToPull = netSyToTokenizePt - netSyOut; if (netSyToPull <= exactSyIn) { if (PMath.isASmallerApproxB(netSyToPull, exactSyIn, approx.eps)) { return (guess, netSyFee, iter); } approx.guessMin = guess; } else { approx.guessMax = guess - 1; } } revert("Slippage: APPROX_EXHAUSTED"); } struct Args5 { MarketState market; PYIndex index; uint256 totalPtIn; uint256 netSyHolding; uint256 blockTime; ApproxParams approx; } /** * @dev algorithm: * - Bin search the amount of PT to swap to SY * - Swap PT to SY * - Pair the remaining PT with the SY to add liquidity * - Stop when the ratio of PT / totalPt & SY / totalSy is approx * - guess & approx is for netPtSwap */ function approxSwapPtToAddLiquidity( MarketState memory _market, PYIndex _index, uint256 _totalPtIn, uint256 _netSyHolding, uint256 _blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netPtSwap*/ uint256, /*netSyFromSwap*/ uint256, /*netSyFee*/ uint256 /*iter*/) { Args5 memory a = Args5(_market, _index, _totalPtIn, _netSyHolding, _blockTime, approx); MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime); if (approx.guessOffchain == 0) { // no limit on min approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(a.market, comp)); approx.guessMax = PMath.min(approx.guessMax, a.totalPtIn); validateApprox(approx); require(a.market.totalLp != 0, "no existing lp"); } for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, ) = calcNumerators( a.market, a.index, a.totalPtIn, a.netSyHolding, comp, guess ); if (PMath.isAApproxB(syNumerator, ptNumerator, approx.eps)) { return (guess, netSyOut, netSyFee, iter); } if (syNumerator <= ptNumerator) { // needs more SY --> swap more PT approx.guessMin = guess + 1; } else { // needs less SY --> swap less PT approx.guessMax = guess - 1; } } revert("Slippage: APPROX_EXHAUSTED"); } function calcNumerators( MarketState memory market, PYIndex index, uint256 totalPtIn, uint256 netSyHolding, MarketPreCompute memory comp, uint256 guess ) internal pure returns (uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve) { (netSyOut, netSyFee, netSyToReserve) = calcSyOut(market, comp, index, guess); uint256 newTotalPt = uint256(market.totalPt) + guess; uint256 newTotalSy = (uint256(market.totalSy) - netSyOut - netSyToReserve); // it is desired that // (netSyOut + netSyHolding) / newTotalSy = netPtRemaining / newTotalPt // which is equivalent to // (netSyOut + netSyHolding) * newTotalPt = netPtRemaining * newTotalSy syNumerator = (netSyOut + netSyHolding) * newTotalPt; ptNumerator = (totalPtIn - guess) * newTotalSy; } /** * @dev algorithm: * - Bin search the amount of PT to swap to SY * - Flashswap the corresponding amount of SY out * - Tokenize all the SY into PT + YT * - PT to repay the flashswap, YT transferred to user * - Stop when the additional amount of PT to pull to repay the loan approx the exactPtIn * - guess & approx is for totalPtToSwap */ function approxSwapExactPtForYt( MarketState memory market, PYIndex index, uint256 exactPtIn, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netYtOut*/ uint256, /*totalPtToSwap*/ uint256 /*netSyFee*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { approx.guessMin = PMath.max(approx.guessMin, exactPtIn); approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp)); validateApprox(approx); } for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess); uint256 netAssetOut = index.syToAsset(netSyOut); // guess >= netAssetOut since we are swapping PT to SY uint256 netPtToPull = guess - netAssetOut; if (netPtToPull <= exactPtIn) { if (PMath.isASmallerApproxB(netPtToPull, exactPtIn, approx.eps)) { return (netAssetOut, guess, netSyFee); } approx.guessMin = guess; } else { approx.guessMax = guess - 1; } } revert("Slippage: APPROX_EXHAUSTED"); } //////////////////////////////////////////////////////////////////////////////// function calcSyOut( MarketState memory market, MarketPreCompute memory comp, PYIndex index, uint256 netPtIn ) internal pure returns (uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyOut, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, -int256(netPtIn)); netSyOut = uint256(_netSyOut); netSyFee = uint256(_netSyFee); netSyToReserve = uint256(_netSyToReserve); } function nextGuess(ApproxParams memory approx, uint256 iter) internal pure returns (uint256) { if (iter == 0 && approx.guessOffchain != 0) return approx.guessOffchain; if (approx.guessMin <= approx.guessMax) return (approx.guessMin + approx.guessMax) / 2; revert("Slippage: guessMin > guessMax"); } /// INTENDED TO BE CALLED BY WHEN GUESS.OFFCHAIN == 0 ONLY /// function validateApprox(ApproxParams memory approx) internal pure { if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) revert("Internal: INVALID_APPROX_PARAMS"); } function calcMaxPtIn(MarketState memory market, MarketPreCompute memory comp) internal pure returns (uint256) { uint256 low = 0; uint256 hi = uint256(comp.totalAsset) - 1; while (low != hi) { uint256 mid = (low + hi + 1) / 2; if (calcSlope(comp, market.totalPt, int256(mid)) < 0) hi = mid - 1; else low = mid; } low = PMath.min( low, (MarketMathCore.MAX_MARKET_PROPORTION.mulDown(market.totalPt + comp.totalAsset) - market.totalPt).Uint() ); return low; } function calcSlope(MarketPreCompute memory comp, int256 totalPt, int256 ptToMarket) internal pure returns (int256) { int256 diffAssetPtToMarket = comp.totalAsset - ptToMarket; int256 sumPt = ptToMarket + totalPt; require(diffAssetPtToMarket > 0 && sumPt > 0, "invalid ptToMarket"); int256 part1 = (ptToMarket * (totalPt + comp.totalAsset)).divDown(sumPt * diffAssetPtToMarket); int256 part2 = sumPt.divDown(diffAssetPtToMarket).ln(); int256 part3 = PMath.IONE.divDown(comp.rateScalar); return comp.rateAnchor - (part1 - part2).mulDown(part3); } } library MarketApproxPtOutLibV1 { using MarketMathCore for MarketState; using PYIndexLib for PYIndex; using PMath for uint256; using PMath for int256; using LogExpMath for int256; /** * @dev algorithm: * - Bin search the amount of PT to swapExactOut * - Calculate the amount of SY needed * - Stop when the netSyIn is smaller approx exactSyIn * - guess & approx is for netSyIn */ function approxSwapExactSyForPt( MarketState memory market, PYIndex index, uint256 exactSyIn, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netPtOut*/ uint256 /*netSyFee*/, uint256 /*iter*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { // no limit on min approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt)); validateApprox(approx); } for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 netSyIn, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess); if (netSyIn <= exactSyIn) { if (PMath.isASmallerApproxB(netSyIn, exactSyIn, approx.eps)) { return (guess, netSyFee, iter); } approx.guessMin = guess; } else { approx.guessMax = guess - 1; } } revert("Slippage: APPROX_EXHAUSTED"); } /** * @dev algorithm: * - Bin search the amount of PT to swapExactOut * - Flashswap that amount of PT & pair with YT to redeem SY * - Use the SY to repay the flashswap debt and the remaining is transferred to user * - Stop when the netSyOut is greater approx the minSyOut * - guess & approx is for netSyOut */ function approxSwapYtForExactSy( MarketState memory market, PYIndex index, uint256 minSyOut, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netYtIn*/ uint256, /*netSyOut*/ uint256 /*netSyFee*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { // no limit on min approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt)); validateApprox(approx); } for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 netSyOwed, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess); uint256 netAssetToRepay = index.syToAssetUp(netSyOwed); uint256 netSyOut = index.assetToSy(guess - netAssetToRepay); if (netSyOut >= minSyOut) { if (PMath.isAGreaterApproxB(netSyOut, minSyOut, approx.eps)) { return (guess, netSyOut, netSyFee); } approx.guessMax = guess; } else { approx.guessMin = guess + 1; } } revert("Slippage: APPROX_EXHAUSTED"); } struct Args6 { MarketState market; PYIndex index; uint256 totalSyIn; uint256 netPtHolding; uint256 blockTime; ApproxParams approx; } /** * @dev algorithm: * - Bin search the amount of PT to swapExactOut * - Swap that amount of PT out * - Pair the remaining PT with the SY to add liquidity * - Stop when the ratio of PT / totalPt & SY / totalSy is approx * - guess & approx is for netPtFromSwap */ function approxSwapSyToAddLiquidity( MarketState memory _market, PYIndex _index, uint256 _totalSyIn, uint256 _netPtHolding, uint256 _blockTime, ApproxParams memory _approx ) internal pure returns (uint256, /*netPtFromSwap*/ uint256, /*netSySwap*/ uint256, /*netSyFee*/ uint256 /*iter*/) { Args6 memory a = Args6(_market, _index, _totalSyIn, _netPtHolding, _blockTime, _approx); MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime); if (a.approx.guessOffchain == 0) { // no limit on min a.approx.guessMax = PMath.min(a.approx.guessMax, calcMaxPtOut(comp, a.market.totalPt)); validateApprox(a.approx); require(a.market.totalLp != 0, "no existing lp"); } for (uint256 iter = 0; iter < a.approx.maxIteration; ++iter) { uint256 guess = nextGuess(a.approx, iter); (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) = calcSyIn(a.market, comp, a.index, guess); if (netSyIn > a.totalSyIn) { a.approx.guessMax = guess - 1; continue; } uint256 syNumerator; uint256 ptNumerator; { uint256 newTotalPt = uint256(a.market.totalPt) - guess; uint256 netTotalSy = uint256(a.market.totalSy) + netSyIn - netSyToReserve; // it is desired that // (netPtFromSwap + netPtHolding) / newTotalPt = netSyRemaining / netTotalSy // which is equivalent to // (netPtFromSwap + netPtHolding) * netTotalSy = netSyRemaining * newTotalPt ptNumerator = (guess + a.netPtHolding) * netTotalSy; syNumerator = (a.totalSyIn - netSyIn) * newTotalPt; } if (PMath.isAApproxB(ptNumerator, syNumerator, a.approx.eps)) { return (guess, netSyIn, netSyFee, iter); } if (ptNumerator <= syNumerator) { // needs more PT a.approx.guessMin = guess + 1; } else { // needs less PT a.approx.guessMax = guess - 1; } } revert("Slippage: APPROX_EXHAUSTED"); } /** * @dev algorithm: * - Bin search the amount of PT to swapExactOut * - Flashswap that amount of PT out * - Pair all the PT with the YT to redeem SY * - Use the SY to repay the flashswap debt * - Stop when the amount of YT required to pair with PT is approx exactYtIn * - guess & approx is for netPtFromSwap */ function approxSwapExactYtForPt( MarketState memory market, PYIndex index, uint256 exactYtIn, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netPtOut*/ uint256, /*totalPtSwapped*/ uint256 /*netSyFee*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { approx.guessMin = PMath.max(approx.guessMin, exactYtIn); approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt)); validateApprox(approx); } for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { uint256 guess = nextGuess(approx, iter); (uint256 netSyOwed, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess); uint256 netYtToPull = index.syToAssetUp(netSyOwed); if (netYtToPull <= exactYtIn) { if (PMath.isASmallerApproxB(netYtToPull, exactYtIn, approx.eps)) { return (guess - netYtToPull, guess, netSyFee); } approx.guessMin = guess; } else { approx.guessMax = guess - 1; } } revert("Slippage: APPROX_EXHAUSTED"); } //////////////////////////////////////////////////////////////////////////////// function calcSyIn( MarketState memory market, MarketPreCompute memory comp, PYIndex index, uint256 netPtOut ) internal pure returns (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyIn, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, int256(netPtOut)); // all safe since totalPt and totalSy is int128 netSyIn = uint256(-_netSyIn); netSyFee = uint256(_netSyFee); netSyToReserve = uint256(_netSyToReserve); } function calcMaxPtOut(MarketPreCompute memory comp, int256 totalPt) internal pure returns (uint256) { int256 logitP = (comp.feeRate - comp.rateAnchor).mulDown(comp.rateScalar).exp(); int256 proportion = logitP.divDown(logitP + PMath.IONE); int256 numerator = proportion.mulDown(totalPt + comp.totalAsset); int256 maxPtOut = totalPt - numerator; // only get 99.9% of the theoretical max to accommodate some precision issues return (uint256(maxPtOut) * 999) / 1000; } function nextGuess(ApproxParams memory approx, uint256 iter) internal pure returns (uint256) { if (iter == 0 && approx.guessOffchain != 0) return approx.guessOffchain; if (approx.guessMin <= approx.guessMax) return (approx.guessMin + approx.guessMax) / 2; revert("Slippage: guessMin > guessMax"); } function validateApprox(ApproxParams memory approx) internal pure { if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) revert("Internal: INVALID_APPROX_PARAMS"); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.17; import "./MarketApproxLibV1.sol"; abstract contract StorageLayout { address internal owner; address internal pendingOwner; mapping(bytes4 => address) internal selectorToFacet; ApproxParams internal defaultApproxParams; address internal _deprecated_bulkSellerFactory; modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../../core/libraries/math/PMath.sol"; import "../../core/Market/MarketMathCore.sol"; import {ApproxParams} from "../../interfaces/IPAllActionTypeV3.sol"; uint256 constant QUICK_CALC_MAX_ITER = 50; uint256 constant CUT_OFF_SCALE_CLAMP = 2; uint256 constant QUICK_CALC_TRIGGER_EPS = 1e17; library MarketApproxPtInLibV2 { using MarketMathCore for MarketState; using PYIndexLib for PYIndex; using PMath for uint256; using PMath for int256; using LogExpMath for int256; function approxSwapExactSyForYtV2( MarketState memory market, PYIndex index, uint256 exactSyIn, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netYtOut*/ uint256 /*netSyFee*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { approx.guessMin = PMath.max(approx.guessMin, index.syToAsset(exactSyIn)); approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp)); validateApprox(approx); } // at minimum we will flashswap exactSyIn since we have enough SY to payback the PT loan uint256 guess = getFirstGuess(approx); for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess); uint256 netSyToTokenizePt = index.assetToSyUp(guess); // for sure netSyToTokenizePt >= netSyOut since we are swapping PT to SY uint256 netSyToPull = netSyToTokenizePt - netSyOut; if (netSyToPull <= exactSyIn) { if (PMath.isASmallerApproxB(netSyToPull, exactSyIn, approx.eps)) { return (guess, netSyFee); } if (approx.guessMin == guess) { break; } approx.guessMin = guess; } else { approx.guessMax = guess - 1; } if (iter <= CUT_OFF_SCALE_CLAMP) { guess = scaleClamp(guess, exactSyIn, netSyToPull, approx); } else { guess = calcMidpoint(approx); } } revert("Slippage: APPROX_EXHAUSTED"); } struct Args5 { MarketState market; PYIndex index; uint256 totalPtIn; uint256 netSyHolding; uint256 blockTime; ApproxParams approx; } function approxSwapPtToAddLiquidityV2( MarketState memory _market, PYIndex _index, uint256 _totalPtIn, uint256 _netSyHolding, uint256 _blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netPtSwap*/ uint256, /*netSyFromSwap*/ uint256 /*netSyFee*/) { Args5 memory a = Args5(_market, _index, _totalPtIn, _netSyHolding, _blockTime, approx); MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime); if (approx.guessOffchain == 0) { // no limit on min approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(a.market, comp)); approx.guessMax = PMath.min(approx.guessMax, a.totalPtIn); validateApprox(approx); require(a.market.totalLp != 0, "no existing lp"); } uint256 guess = getFirstGuess(approx); bool quickCalcRan = false; for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { ( uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve ) = calcNumerators(a.market, a.index, a.totalPtIn, a.netSyHolding, comp, guess); if (PMath.isAApproxB(syNumerator, ptNumerator, approx.eps)) { return (guess, netSyOut, netSyFee); } if (syNumerator <= ptNumerator) { // needs more SY --> swap more PT if (approx.guessMin == guess) { break; } approx.guessMin = guess; } else { // needs less SY --> swap less PT approx.guessMax = guess - 1; } if (!quickCalcRan && PMath.isAApproxB(syNumerator, ptNumerator, QUICK_CALC_TRIGGER_EPS)) { quickCalcRan = true; guess = quickCalc(a, guess, netSyOut, netSyToReserve); if (guess <= a.approx.guessMin || guess >= a.approx.guessMax) guess = calcMidpoint(a.approx); } else { guess = calcMidpoint(a.approx); } } revert("Slippage: APPROX_EXHAUSTED"); } function quickCalc( Args5 memory a, uint256 _guess, uint256 _netSyOut, uint256 _netSyToReserve ) internal pure returns (uint256) { unchecked { uint256 low = a.approx.guessMin; uint256 high = a.approx.guessMax; for (uint256 i = 0; i < QUICK_CALC_MAX_ITER; i++) { uint256 mid = (low + high) / 2; uint256 thisNetSyOut = (_netSyOut * mid) / _guess; uint256 thisNetSyToReserve = (_netSyToReserve * mid) / _guess; uint256 newTotalPt = uint256(a.market.totalPt) + mid; uint256 newTotalSy = (uint256(a.market.totalSy) - thisNetSyOut - thisNetSyToReserve); uint256 syNumerator = (thisNetSyOut + a.netSyHolding) * newTotalPt; uint256 ptNumerator = (a.totalPtIn - mid) * newTotalSy; if (isAApproxBUnchecked(syNumerator, ptNumerator, a.approx.eps)) { return mid; } if (syNumerator <= ptNumerator) { if (low == mid) { break; } low = mid; } else { high = mid - 1; } if (low > high) return mid; } return (low + high) / 2; } } function calcNumerators( MarketState memory market, PYIndex index, uint256 totalPtIn, uint256 netSyHolding, MarketPreCompute memory comp, uint256 guess ) internal pure returns (uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve) { (netSyOut, netSyFee, netSyToReserve) = calcSyOut(market, comp, index, guess); uint256 newTotalPt = uint256(market.totalPt) + guess; uint256 newTotalSy = (uint256(market.totalSy) - netSyOut - netSyToReserve); // it is desired that // (netSyOut + netSyHolding) / newTotalSy = netPtRemaining / newTotalPt // which is equivalent to // (netSyOut + netSyHolding) * newTotalPt = netPtRemaining * newTotalSy syNumerator = (netSyOut + netSyHolding) * newTotalPt; ptNumerator = (totalPtIn - guess) * newTotalSy; } //////////////////////////////////////////////////////////////////////////////// function calcSyOut( MarketState memory market, MarketPreCompute memory comp, PYIndex index, uint256 netPtIn ) internal pure returns (uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyOut, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, -int256(netPtIn)); netSyOut = uint256(_netSyOut); netSyFee = uint256(_netSyFee); netSyToReserve = uint256(_netSyToReserve); } /// INTENDED TO BE CALLED BY WHEN GUESS.OFFCHAIN == 0 ONLY /// function validateApprox(ApproxParams memory approx) internal pure { if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) revert("Internal: INVALID_APPROX_PARAMS"); } function calcMaxPtIn(MarketState memory market, MarketPreCompute memory comp) internal pure returns (uint256) { uint256 low = 0; uint256 hi = uint256(comp.totalAsset) - 1; while (low != hi) { uint256 mid = (low + hi + 1) / 2; if (calcSlope(comp, market.totalPt, int256(mid)) < 0) hi = mid - 1; else low = mid; } low = PMath.min( low, (MarketMathCore.MAX_MARKET_PROPORTION.mulDown(market.totalPt + comp.totalAsset) - market.totalPt).Uint() ); return low; } function calcSlope(MarketPreCompute memory comp, int256 totalPt, int256 ptToMarket) internal pure returns (int256) { int256 diffAssetPtToMarket = comp.totalAsset - ptToMarket; int256 sumPt = ptToMarket + totalPt; require(diffAssetPtToMarket > 0 && sumPt > 0, "invalid ptToMarket"); int256 part1 = (ptToMarket * (totalPt + comp.totalAsset)).divDown(sumPt * diffAssetPtToMarket); int256 part2 = sumPt.divDown(diffAssetPtToMarket).ln(); int256 part3 = PMath.IONE.divDown(comp.rateScalar); return comp.rateAnchor - (part1 - part2).mulDown(part3); } } library MarketApproxPtOutLibV2 { using MarketMathCore for MarketState; using PYIndexLib for PYIndex; using PMath for uint256; using PMath for int256; using LogExpMath for int256; function approxSwapExactSyForPtV2( MarketState memory market, PYIndex index, uint256 exactSyIn, uint256 blockTime, ApproxParams memory approx ) internal pure returns (uint256, /*netPtOut*/ uint256 /*netSyFee*/) { MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime); if (approx.guessOffchain == 0) { // no limit on min approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt)); validateApprox(approx); } uint256 guess = getFirstGuess(approx); for (uint256 iter = 0; iter < approx.maxIteration; ++iter) { (uint256 netSyIn, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess); if (netSyIn <= exactSyIn) { if (PMath.isASmallerApproxB(netSyIn, exactSyIn, approx.eps)) { return (guess, netSyFee); } if (guess == approx.guessMin) { break; } approx.guessMin = guess; } else { approx.guessMax = guess - 1; } if (iter <= CUT_OFF_SCALE_CLAMP) { guess = scaleClamp(guess, exactSyIn, netSyIn, approx); } else { guess = calcMidpoint(approx); } } revert("Slippage: APPROX_EXHAUSTED"); } struct Args6 { MarketState market; PYIndex index; uint256 totalSyIn; uint256 netPtHolding; uint256 blockTime; ApproxParams approx; } function approxSwapSyToAddLiquidityV2( MarketState memory _market, PYIndex _index, uint256 _totalSyIn, uint256 _netPtHolding, uint256 _blockTime, ApproxParams memory _approx ) internal pure returns (uint256, /*netPtFromSwap*/ uint256, /*netSySwap*/ uint256 /*netSyFee*/) { Args6 memory a = Args6(_market, _index, _totalSyIn, _netPtHolding, _blockTime, _approx); MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime); if (a.approx.guessOffchain == 0) { // no limit on min a.approx.guessMax = PMath.min(a.approx.guessMax, calcMaxPtOut(comp, a.market.totalPt)); validateApprox(a.approx); require(a.market.totalLp != 0, "no existing lp"); } uint256 guess = getFirstGuess(a.approx); bool quickCalcRan = false; for (uint256 iter = 0; iter < a.approx.maxIteration; ++iter) { (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) = calcSyIn(a.market, comp, a.index, guess); if (netSyIn > a.totalSyIn) { a.approx.guessMax = guess - 1; guess = calcMidpoint(a.approx); continue; } uint256 syNumerator; uint256 ptNumerator; { uint256 newTotalPt = uint256(a.market.totalPt) - guess; uint256 netTotalSy = uint256(a.market.totalSy) + netSyIn - netSyToReserve; // it is desired that // (netPtFromSwap + netPtHolding) / newTotalPt = netSyRemaining / netTotalSy // which is equivalent to // (netPtFromSwap + netPtHolding) * netTotalSy = netSyRemaining * newTotalPt ptNumerator = (guess + a.netPtHolding) * netTotalSy; syNumerator = (a.totalSyIn - netSyIn) * newTotalPt; } if (PMath.isAApproxB(syNumerator, ptNumerator, a.approx.eps)) { return (guess, netSyIn, netSyFee); } if (ptNumerator <= syNumerator) { if (a.approx.guessMin == guess) { break; } a.approx.guessMin = guess; } else { a.approx.guessMax = guess - 1; } if (!quickCalcRan && PMath.isAApproxB(syNumerator, ptNumerator, QUICK_CALC_TRIGGER_EPS)) { quickCalcRan = true; guess = quickCalc(a, guess, netSyIn, netSyToReserve); if (guess <= a.approx.guessMin || guess >= a.approx.guessMax) guess = calcMidpoint(a.approx); } else { guess = calcMidpoint(a.approx); } } revert("Slippage: APPROX_EXHAUSTED"); } function quickCalc( Args6 memory a, uint256 _guess, uint256 _netSyIn, uint256 _netSyToReserve ) internal pure returns (uint256) { uint256 low = a.approx.guessMin; uint256 high = a.approx.guessMax; unchecked { for (uint256 i = 0; i < QUICK_CALC_MAX_ITER; i++) { uint256 mid = (low + high) / 2; uint256 newTotalPt = uint256(a.market.totalPt) - mid; uint256 thisNetSyIn = (_netSyIn * mid) / _guess; uint256 thisNetSyToReserve = (_netSyToReserve * mid) / _guess; if (thisNetSyIn > a.totalSyIn) { high = mid - 1; if (low > high) return mid; continue; } uint256 netTotalSy = uint256(a.market.totalSy) + thisNetSyIn - thisNetSyToReserve; uint256 ptNumerator = (mid + a.netPtHolding) * netTotalSy; uint256 syNumerator = (a.totalSyIn - thisNetSyIn) * newTotalPt; if (isAApproxBUnchecked(syNumerator, ptNumerator, a.approx.eps)) { return mid; } if (ptNumerator <= syNumerator) { low = mid; } else { high = mid - 1; } if (low > high) return mid; } return (low + high) / 2; } } //////////////////////////////////////////////////////////////////////////////// function calcSyIn( MarketState memory market, MarketPreCompute memory comp, PYIndex index, uint256 netPtOut ) internal pure returns (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) { (int256 _netSyIn, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, int256(netPtOut)); // all safe since totalPt and totalSy is int128 netSyIn = uint256(-_netSyIn); netSyFee = uint256(_netSyFee); netSyToReserve = uint256(_netSyToReserve); } function calcMaxPtOut(MarketPreCompute memory comp, int256 totalPt) internal pure returns (uint256) { int256 logitP = (comp.feeRate - comp.rateAnchor).mulDown(comp.rateScalar).exp(); int256 proportion = logitP.divDown(logitP + PMath.IONE); int256 numerator = proportion.mulDown(totalPt + comp.totalAsset); int256 maxPtOut = totalPt - numerator; // only get 99.9% of the theoretical max to accommodate some precision issues return (uint256(maxPtOut) * 999) / 1000; } function validateApprox(ApproxParams memory approx) internal pure { if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) revert("Internal: INVALID_APPROX_PARAMS"); } } function scaleClamp( uint256 original, uint256 target, uint256 current, ApproxParams memory approx ) pure returns (uint256) { uint256 scaled = (original * target) / current; if (scaled >= approx.guessMax) return calcMidpoint(approx); if (scaled <= approx.guessMin) return calcMidpoint(approx); return scaled; } function getFirstGuess(ApproxParams memory approx) pure returns (uint256) { return (approx.guessOffchain != 0) ? approx.guessOffchain : calcMidpoint(approx); } function calcMidpoint(ApproxParams memory approx) pure returns (uint256) { return (approx.guessMin + approx.guessMax + 1) / 2; } function isAApproxBUnchecked(uint256 a, uint256 b, uint256 eps) pure returns (bool) { unchecked { uint256 bLow = (b * (1e18 - eps)) / 1e18; uint256 bHigh = (b * (1e18 + eps)) / 1e18; return bLow <= a && a <= bHigh; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; struct SwapData { SwapType swapType; address extRouter; bytes extCalldata; bool needScale; } struct SwapDataExtra { address tokenIn; address tokenOut; uint256 minOut; SwapData swapData; } enum SwapType { NONE, KYBERSWAP, ODOS, // ETH_WETH not used in Aggregator ETH_WETH, OKX, ONE_INCH, RESERVE_1, RESERVE_2, RESERVE_3, RESERVE_4, RESERVE_5 } interface IPSwapAggregator { event SwapSingle(SwapType indexed swapType, address indexed tokenIn, uint256 amountIn); function swap(address tokenIn, uint256 amountIn, SwapData calldata swapData) external payable; }
{ "optimizer": { "enabled": true, "runs": 0 }, "viaIR": true, "evmVersion": "shanghai", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"int256","name":"exchangeRate","type":"int256"}],"name":"MarketExchangeRateBelowOne","type":"error"},{"inputs":[],"name":"MarketExpired","type":"error"},{"inputs":[],"name":"MarketProportionMustNotEqualOne","type":"error"},{"inputs":[{"internalType":"int256","name":"proportion","type":"int256"},{"internalType":"int256","name":"maxProportion","type":"int256"}],"name":"MarketProportionTooHigh","type":"error"},{"inputs":[{"internalType":"int256","name":"rateScalar","type":"int256"}],"name":"MarketRateScalarBelowZero","type":"error"},{"inputs":[{"internalType":"int256","name":"totalPt","type":"int256"},{"internalType":"int256","name":"totalAsset","type":"int256"}],"name":"MarketZeroTotalPtOrTotalAsset","type":"error"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"int256","name":"netPtOut","type":"int256"}],"name":"calcPriceImpactPY","outputs":[{"internalType":"uint256","name":"priceImpact","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"int256","name":"netPtOut","type":"int256"}],"name":"calcPriceImpactPt","outputs":[{"internalType":"uint256","name":"priceImpact","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"int256","name":"netPtOut","type":"int256"}],"name":"calcPriceImpactYt","outputs":[{"internalType":"uint256","name":"priceImpact","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"uint256","name":"netPtOut","type":"uint256"},{"internalType":"uint256","name":"slippage","type":"uint256"}],"name":"genApproxParamsToSwapExactSyForPt","outputs":[{"components":[{"internalType":"uint256","name":"guessMin","type":"uint256"},{"internalType":"uint256","name":"guessMax","type":"uint256"},{"internalType":"uint256","name":"guessOffchain","type":"uint256"},{"internalType":"uint256","name":"maxIteration","type":"uint256"},{"internalType":"uint256","name":"eps","type":"uint256"}],"internalType":"struct ApproxParams","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getLpToAssetRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getLpToSyRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getMarketState","outputs":[{"internalType":"address","name":"pt","type":"address"},{"internalType":"address","name":"yt","type":"address"},{"internalType":"address","name":"sy","type":"address"},{"internalType":"int256","name":"impliedYield","type":"int256"},{"internalType":"uint256","name":"marketExchangeRateExcludeFee","type":"uint256"},{"components":[{"internalType":"int256","name":"totalPt","type":"int256"},{"internalType":"int256","name":"totalSy","type":"int256"},{"internalType":"int256","name":"totalLp","type":"int256"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"int256","name":"scalarRoot","type":"int256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"lnFeeRateRoot","type":"uint256"},{"internalType":"uint256","name":"reserveFeePercent","type":"uint256"},{"internalType":"uint256","name":"lastLnImpliedRate","type":"uint256"}],"internalType":"struct MarketState","name":"state","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getPtToAssetRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getPtToSyRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"components":[{"internalType":"int256","name":"totalPt","type":"int256"},{"internalType":"int256","name":"totalSy","type":"int256"},{"internalType":"int256","name":"totalLp","type":"int256"},{"internalType":"address","name":"treasury","type":"address"},{"internalType":"int256","name":"scalarRoot","type":"int256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"lnFeeRateRoot","type":"uint256"},{"internalType":"uint256","name":"reserveFeePercent","type":"uint256"},{"internalType":"uint256","name":"lastLnImpliedRate","type":"uint256"}],"internalType":"struct MarketState","name":"state","type":"tuple"}],"name":"getTradeExchangeRateExcludeFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"int256","name":"netPtOut","type":"int256"}],"name":"getTradeExchangeRateIncludeFee","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getYieldTokenAndPtRate","outputs":[{"internalType":"address","name":"yieldToken","type":"address"},{"internalType":"uint256","name":"netPtOut","type":"uint256"},{"internalType":"uint256","name":"netYieldTokenOut","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getYieldTokenAndYtRate","outputs":[{"internalType":"address","name":"yieldToken","type":"address"},{"internalType":"uint256","name":"netYtOut","type":"uint256"},{"internalType":"uint256","name":"netYieldTokenOut","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getYtToAssetRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"}],"name":"getYtToSyRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"uint256","name":"exactSyIn","type":"uint256"},{"internalType":"uint256","name":"slippage","type":"uint256"}],"name":"swapExactSyForPtStaticAndGenerateApproxParams","outputs":[{"internalType":"uint256","name":"netPtOut","type":"uint256"},{"internalType":"uint256","name":"netSyFee","type":"uint256"},{"internalType":"uint256","name":"priceImpact","type":"uint256"},{"internalType":"uint256","name":"exchangeRateAfter","type":"uint256"},{"components":[{"internalType":"uint256","name":"guessMin","type":"uint256"},{"internalType":"uint256","name":"guessMax","type":"uint256"},{"internalType":"uint256","name":"guessOffchain","type":"uint256"},{"internalType":"uint256","name":"maxIteration","type":"uint256"},{"internalType":"uint256","name":"eps","type":"uint256"}],"internalType":"struct ApproxParams","name":"approxParams","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"market","type":"address"},{"internalType":"address","name":"tokenIn","type":"address"},{"internalType":"uint256","name":"amountTokenIn","type":"uint256"},{"internalType":"uint256","name":"slippage","type":"uint256"}],"name":"swapExactTokenForPtStaticAndGenerateApproxParams","outputs":[{"internalType":"uint256","name":"netPtOut","type":"uint256"},{"internalType":"uint256","name":"netSyMinted","type":"uint256"},{"internalType":"uint256","name":"netSyFee","type":"uint256"},{"internalType":"uint256","name":"priceImpact","type":"uint256"},{"internalType":"uint256","name":"exchangeRateAfter","type":"uint256"},{"components":[{"internalType":"uint256","name":"guessMin","type":"uint256"},{"internalType":"uint256","name":"guessMax","type":"uint256"},{"internalType":"uint256","name":"guessOffchain","type":"uint256"},{"internalType":"uint256","name":"maxIteration","type":"uint256"},{"internalType":"uint256","name":"eps","type":"uint256"}],"internalType":"struct ApproxParams","name":"approxParams","type":"tuple"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
60808060405234601557612399908161001a8239f35b5f80fdfe60806040526004361015610011575f80fd5b5f3560e01c806308b3523214610a1b5780630ac6aa691461097b5780630f8cb3211461095457806354b125a6146106fe5780635dc9bdbe1461066657806362576930146106315780636e22df2f1461060b5780636e4b3f20146105e5578063771a49c0146104f557806394f8c15b14610415578063955ee4e7146103f2578063a34560c6146103b6578063bcc454e214610349578063d1b087c9146102fc578063e7f317631461021a578063e8a89c76146101165763f2344deb146100d4575f80fd5b3461011257602036600319011261011257602061010a6100f2610c66565b6100fb81611543565b6101048261161c565b916118a7565b604051908152f35b5f80fd5b346101125760203660031901126101125761012f610c66565b61013761136a565b50610141816113ad565b61014d84929394611543565b9061010061015a84611543565b0151926001600160ff1b038411610112576101c0956101858461017f61010097611aa8565b93610fed565b926040519660018060a01b0316875260018060a01b0316602087015260018060a01b0316604086015260608501526080840152805160a0840152602081015160c0840152604081015160e084015260018060a01b0360608201511682840152608081015161012084015260a081015161014084015260c081015161016084015260e081015161018084015201516101a0820152f35b3461011257602036600319011261011257610233610c66565b61024b61023f826113ad565b5050916100fb81611543565b670de0b6b3a76400000390670de0b6b3a764000082116102e857604051633ba0b9a960e01b815290602090829060049082906001600160a01b03165afa9081156102dd575f916102aa575b602061010a836102a58661146e565b6114a5565b90506020813d6020116102d5575b816102c560209383610ce5565b8101031261011257516020610296565b3d91506102b8565b6040513d5f823e3d90fd5b634e487b7160e01b5f52601160045260245ffd5b3461011257604036600319011261011257602061010a61031a610c66565b61034361033860243561033d6103386103328361145d565b86610e1e565b6114dd565b93610e1e565b90611512565b3461011257602036600319011261011257610362610c66565b6004602061037a610372846113ad565b5050936112da565b604051633ba0b9a960e01b815290939092839182906001600160a01b03165afa9081156102dd575f916102aa57602061010a836102a58661146e565b3461011257604036600319011261011257602061010a6103d4610c66565b6103436024356103ec6103e68261145d565b84610e1e565b92610e1e565b3461011257602036600319011261011257602061010a610410610c66565b6112da565b346101125761042336610d08565b9061042c611107565b5060405163b1f3606560e01b81526001600160a01b03841660048201526024810191909152608081604481305afa9081156102dd575f925f945f925f946104a5575b50916104836104a39492866101209895611131565b926040519586526020860152604085015260608401526080830190610d32565bf35b955092509250506080833d6080116104ed575b816104c560809383610ce5565b810103126101125782516020840151604085015160609095015190949193909261048361046e565b3d91506104b8565b346101125760803660031901126101125761050e610c66565b602435906001600160a01b03821682036101125760a061055092610530611107565b50604051809481926326e44ccf60e01b8352604435908660048501610dc1565b0381305afa80156102dd57610140925f915f915f5f915f936105a5575b5061058085966104a39660643591611131565b93604051968752602087015260408601526060850152608084015260a0830190610d32565b9150506104a3935061058092506105d4915060a03d60a0116105de575b6105cc8183610ce5565b810190610d9a565b939550919361056d565b503d6105c2565b346101125760a06105fe6105f836610d08565b91611131565b6104a36040518092610d32565b3461011257602036600319011261011257602061010a61062c6100f2610c66565b6110de565b346101125760203660031901126101125761064a610c66565b6004602061037a61065a846113ad565b5050936100fb81611543565b346101125761014036600319011261011257610680610c66565b6101203660231901126101125760405161069981610c9a565b602435815260443560208201526064356040820152608435906001600160a01b03821682036101125760209261010a92606083015260a435608083015260c43560a083015260e43560c08301526101043560e083015261012435610100830152610fed565b34610112576020366003190112610112576020600461071b610c66565b610724816113ad565b506040516376d5de8560e01b815290949093909184919082906001600160a01b03165afa9182156102dd575f92610918575b5060405163313ce56760e01b8152926020846004816001600160a01b0387165afa9081156102dd576004945f926108f6575b5060405163313ce56760e01b81529460209186919082906001600160a01b03165afa9384156102dd575f946108b1575b5082916107e960a06107cd60ff829516610d8c565b604051809381926326e44ccf60e01b8352888760048501610dc1565b0381305afa5f918161088e575b50610882575061080b60ff5f19965b16610d8c565b6040516331562d0560e01b8152938492839261082b929160048501610de3565b0381305afa5f918161085d575b5061085457506108505f195b60405193849384610c7c565b0390f35b61085090610844565b61087791925060a03d60a0116105de576105cc8183610ce5565b505050509084610838565b60ff61080b9196610805565b6108a6919250843d86116105de576105cc8183610ce5565b5050505090876107f6565b60a0919450916107e9826107cd60ff6108e2889760203d6020116108ef575b6108da8183610ce5565b810190610d73565b98955050505050916107b8565b503d6108d0565b602091925061091190823d84116108ef576108da8183610ce5565b9190610788565b9091506020813d60201161094c575b8161093460209383610ce5565b810103126101125761094590610d5f565b9083610756565b3d9150610927565b3461011257604036600319011261011257602061010a610972610c66565b60243590610e1e565b3461011257604036600319011261011257610994610c66565b6109a66024356103ec6103e68261145d565b6a0c097ce7bc90715b34b9f160241b908215610a0757828204918115610a07576020936102a5610a0161010a956102a56109fb6109f1886103439804966109ec816110c8565b6114af565b976109ec816110c8565b9661146e565b9361146e565b634e487b7160e01b5f52601260045260245ffd5b346101125760203660031901126101125760206004610a38610c66565b610a41816113ad565b6040516376d5de8560e01b815290959094909285925082906001600160a01b03165afa9182156102dd575f92610c2a575b5060405163313ce56760e01b8152926020846004816001600160a01b0387165afa9081156102dd576004945f92610c08575b5060405163313ce56760e01b81529460209186919082906001600160a01b03165afa9384156102dd575f94610bd1575b508291610b0760a0610aeb60ff6101009516610d8c565b604051809381926374f669d960e11b8352888760048501610dc1565b0381305afa5f9181610bac575b50610ba05750610b2860ff5f199616610d8c565b604051631c3cb1ff60e21b81529384928392610b48929160048501610de3565b0381305afa5f9181610b6b575061085457506108505f1960405193849384610c7c565b909150610100813d8211610b98575b81610b886101009383610ce5565b8101031261011257519084610838565b3d9150610b7a565b60ff610b289196610805565b610bc691925060a03d60a0116105de576105cc8183610ce5565b505050509087610b14565b61010091945091610b0760a0610aeb60ff610bfb889760203d6020116108ef576108da8183610ce5565b9895505050505091610ad4565b6020919250610c2390823d84116108ef576108da8183610ce5565b9190610aa4565b9091506020813d602011610c5e575b81610c4660209383610ce5565b8101031261011257610c5790610d5f565b9083610a72565b3d9150610c39565b600435906001600160a01b038216820361011257565b604091949392606082019560018060a01b0316825260208201520152565b61012081019081106001600160401b03821117610cb657604052565b634e487b7160e01b5f52604160045260245ffd5b60a081019081106001600160401b03821117610cb657604052565b601f909101601f19168101906001600160401b03821190821017610cb657604052565b6060906003190112610112576004356001600160a01b038116810361011257906024359060443590565b60808091805184526020810151602085015260408101516040850152606081015160608501520151910152565b51906001600160a01b038216820361011257565b90816020910312610112575160ff811681036101125790565b604d81116102e857600a0a90565b908160a0910312610112578051916020820151916040810151916080606083015192015190565b6001600160a01b03918216815291166020820152604081019190915260600190565b6001600160a01b0391821681526020810192909252909116604082015260600190565b90816020910312610112575180151581036101125790565b604051630bc4ed8360e21b81529091906020816004816001600160a01b0387165afa9081156102dd575f91610fbe575b50610fb057610e70610e68610e6284611543565b9361161c565b429084611682565b91516020830151835190604085015192848112610f8057610ea7610ea1610eac93610e9b88856114fa565b936112bf565b9161182f565b61189d565b670d529ae9e86000008113610f6257610ed99291610ea7610ecf610ed493611a06565b61182f565b6112bf565b90670de0b6b3a76400008212610f4f575f1215610f2c57610ea76060610f019301519161182f565b670de0b6b3a76400008112610f1a575f81126101125790565b63329e322960e21b5f5260045260245ffd5b610f44906060670de0b6b3a764000093015190611853565b055f81126101125790565b5063329e322960e21b5f5260045260245ffd5b637e34684f60e11b5f52600452670d529ae9e860000060245260445ffd5b60405162461bcd60e51b81526020600482015260086024820152676e6567617469766560c01b6044820152606490fd5b5050670de0b6b3a764000090565b610fe0915060203d602011610fe6575b610fd88183610ce5565b810190610e06565b5f610e4e565b503d610fce565b604051630bc4ed8360e21b81529192916020816004816001600160a01b0386165afa9081156102dd575f916110a9575b5061109b57610e6861102e9161161c565b9151602083015160408451940151915f8112610f8057610ea7610ea161105893610e9b5f856114fa565b92670d529ae9e8600000841361107c57610ed490610ea7610ecf610f019596611a06565b83637e34684f60e11b5f52600452670d529ae9e860000060245260445ffd5b50670de0b6b3a76400009150565b6110c2915060203d602011610fe657610fd88183610ce5565b5f61101d565b670de0b6b3a763ffff198101919082116102e857565b670de0b6b3a76400000390670de0b6b3a764000082116102e857565b919082039182116102e857565b6040519061111482610cca565b5f6080838281528260208201528260408201528260608201520152565b611139611107565b5061115761114f61114983611543565b9261161c565b429083611682565b9051611189670de0b6b3a764000061118361117b60608601516040870151906114fa565b855190611853565b05611aa8565b670de0b6b3a76400008101670de0b6b3a764000081125f83129080158216911516176102e8576111e7936111da60206111d16111e094610ea7670de0b6b3a76400009761182f565b920151856112bf565b90611853565b05906114fa565b6103e78102908082046103e714901517156102e8576103e890049061120a611107565b508260011c6509184e72a00081105f146112b157915b670de0b6b3a764000061123b611235866110de565b84611492565b0493806005029060058204036102e857670de0b6b3a76400000180670de0b6b3a7640000116102e857611277670de0b6b3a76400009184611492565b04808210156112aa57505b6040519361128f85610cca565b845260208401526040830152601e6060830152608082015290565b9050611282565b506509184e72a00091611220565b9190915f83820193841291129080158216911516176102e857565b61132790610ea760406112ec83611543565b926112f68161161c565b60a085015142106113315761131d91506113178551916020870151906119a6565b906112bf565b925b01519161182f565b5f81126101125790565b670de0b6b3a764000061135d611364936111da602061135142878c611682565b015194898051936118a7565b05906112bf565b9261131f565b6040519061137782610c9a565b5f610100838281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e08201520152565b604051630b2339af60e21b81529190606090839060049082906001600160a01b03165afa9081156102dd575f5f935f936113e8575b50929190565b92505091506060813d606011611455575b8161140660609383610ce5565b81010312610112578051916001600160a01b0383168303610112576020820151916001600160a01b03831683036101125760400151926001600160a01b0384168403610112579192915f6113e2565b3d91506113f9565b5f121561146957600190565b5f1990565b90670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102e857565b818102929181159184041417156102e857565b8115610a07570490565b90670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102e8576114da916114a5565b90565b670de0b6b3a763ffff198101908082116102e8576114da916114af565b81810392915f1380158285131691841216176102e857565b6001600160ff1b038111610112576001600160ff1b038211610112576109ec61153e6114da93836114fa565b6119eb565b61154b61136a565b50604051639e48767360e01b81526001600160a01b03909116600482015261012081602481305afa9081156102dd575f91611584575090565b9050610120813d8211611614575b816115a06101209383610ce5565b8101031261011257610100604051916115b883610c9a565b8051835260208101516020840152604081015160408401526115dc60608201610d5f565b60608401526080810151608084015260a081015160a084015260c081015160c084015260e081015160e0840152015161010082015290565b3d9150611592565b6040516314ae175360e11b81526001600160a01b039091166004820152602081602481305afa9081156102dd575f91611653575090565b90506020813d60201161167a575b8161166e60209383610ce5565b81010312610112575190565b3d9150611661565b6040519293929190608083016001600160401b03811184821017610cb6576040525f835260208301905f8252604084015f815260608501945f8652809760a08401908082511115611820576116d791516110fa565b936080840151956116ed6301e133808098611853565b6001600160ff1b038711610112578615610a0757600160ff1b81145f198814166102e8578690055f81131561180e578352602085015161172c916119a6565b808252845180158015611806575b6117f1575050835161175a876102a5886101008901519551965195611492565b6001600160ff1b0381116101125761177190611aa8565b92670de0b6b3a764000084126117de57926117ad60c09593610ea7610ecf6117a886610ea7610ea16117bc9e9d9b6117b39a6112bf565b611a06565b906114fa565b90520151611492565b8115610a0757046001600160ff1b038111610112576117da90611aa8565b9052565b8363329e322960e21b5f5260045260245ffd5b63b1c4aefb60e01b5f5260045260245260445ffd5b50811561173a565b630e520c3b60e11b5f5260045260245ffd5b63b2094b5960e01b5f5260045ffd5b90670de0b6b3a7640000820291808305670de0b6b3a764000014901517156102e857565b81810292915f8212600160ff1b8214166102e85781840514901517156102e857565b8015610a07576a0c097ce7bc90715b34b9f160241b0590565b68056bc75e2d63100000900590565b8115610a07570590565b9160a0820190815142101561190a57506118d392506118cb610100914290516110fa565b910151611492565b6301e1338090046001600160ff1b038111610112576118f190611aa8565b6a0c097ce7bc90715b34b9f160241b8115610a07570590565b915050602061191a6004936113ad565b5050604051633ba0b9a960e01b815293849182906001600160a01b03165afa9182156102dd575f92611972575b50670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102e8576114da916114a5565b9091506020813d60201161199e575b8161198e60209383610ce5565b810103126101125751905f611947565b3d9150611981565b6119cc670de0b6b3a7640000915f84125f146119e4576119c75f19946119eb565b611492565b046001600160ff1b038111610112576114da91611853565b6119c76001945b5f8113156119f65790565b600160ff1b81146102e8575f0390565b670de0b6b3a76400008114611a5a5780670de0b6b3a764000003905f8112670de0b6b3a76400008312811690670de0b6b3a76400008413901516176102e8576114da91610ea7611a559261182f565b611e5a565b63a9c8b14d60e01b5f5260045ffd5b15611a7057565b60405162461bcd60e51b815260206004820152601060248201526f125b9d985b1a5908195e1c1bdb995b9d60821b6044820152606490fd5b680238fd42c5cf03ffff1981121580611e47575b611ac590611a69565b5f8112611e33576114da906806f05b59d3b20000008112611df25772195e54c5dd42177f53a27172fa9ec63026282760241b90611cb1906064906806f05b59d3b1ffffff19015b0268056bc75e2d631000009068ad78ebc5ac62000000811215611dcf575b6856bc75e2d631000000811215611da5575b682b5e3af16b18800000811215611d7d575b6815af1d78b58c400000811215611d55575b680ad78ebc5ac6200000811215611d2e575b68056bc75e2d63100000811215611d07575b6802b5e3af16b1880000811215611ce0575b68015af1d78b58c40000811215611cb9575b611bbd611bb682800261188e565b6002900590565b611bd2611bcb83830261188e565b6003900590565b611be7611be084830261188e565b6004900590565b611bfc611bf585830261188e565b6005900590565b611c11611c0a86830261188e565b6006900590565b611c26611c1f87830261188e565b6007900590565b90611c3c611c3588840261188e565b6008900590565b92611c52611c4b89860261188e565b6009900590565b9468056bc75e2d63100000611c72611c6b8b890261188e565b600a900590565b97611c88611c818c8b0261188e565b600b900590565b99611c9e611c978d8d0261188e565b600c900590565b9b0101010101010101010101010261188e565b026064900590565b68015af1d78b58c3ffff190190611cda906806f5f17757889379370261188e565b90611ba8565b6802b5e3af16b187ffff190190611d01906808f00f760a4b2db55d0261188e565b90611b96565b68056bc75e2d630fffff190190611d2890680ebc5fb417461211100261188e565b90611b84565b680ad78ebc5ac61fffff190190611d4f9068280e60114edb805d030261188e565b90611b72565b6815af1d78b58c3fffff190190611d7790690127fa27722cc06cc5e20261188e565b90611b60565b682b5e3af16b187fffff190190611d9f90693f1fce3da636ea5cf8500261188e565b90611b4e565b6856bc75e2d630ffffff190190611dc9906b02df0ab5a80a22c61ab5a7000261188e565b90611b3c565b6e01855144814a7ff805980ff0084000915068ad78ebc5ac61ffffff1901611b2a565b6803782dace9d90000008112611e26576803782dace9d8ffffff1901611cb160646b1425982cf597cd205cef738092611b0c565b611cb16064600192611b0c565b611e3e905f03611aa8565b6114da90611875565b5068070c1cc73b00c80000811315611abc565b5f811315611f3c5780670c7d713b49da00001280611f2b575b15611f2257670de0b6b3a764000090611eb39082026a0c097ce7bc90715b34b9f160241b818101916ec097ce7bc90715b34b9f0fffffffff19010261189d565b60036a0c097ce7bc90715b34b9f160241b828002819005808402829005928305909301600592840282900592830501600792840282900592830501600992840282900592830501600b92840282900592830501600d92840282900592830501600f9290930205050160011b0590565b6114da90611f71565b50670f43fc2c04ee00008112611e73565b60405162461bcd60e51b815260206004820152600d60248201526c6f7574206f6620626f756e647360981b6044820152606490fd5b670de0b6b3a7640000811261234d576114da905f775803bcc5cb9634ba4cfb2213f784019318ed4dcb6017880f60361b821215612324575b6f8bcc0026baae9e45e470190267a230cf60191b8212156122f7575b6120b2906064808492029302906e01855144814a7ff805980ff00840008212156122bd575b506b02df0ab5a80a22c61ab5a70081121561228a575b693f1fce3da636ea5cf850811215612259575b690127fa27722cc06cc5e2811215612228575b68280e60114edb805d038112156121f8575b680ebc5fb417461211108112156121d8575b6808f00f760a4b2db55d8112156121a8575b6806f5f1775788937937811215612178575b6806248f33704b286603811215612149575b6805c548670b9510e7ac81121561211a575b68056bc75e2d631000008181019168056bc75e2d630fffff19010261189d565b61210e611c816120c383800261188e565b612101816120f4816120e7816120da818b0261188e565b9960038b0501990261188e565b976005890501970261188e565b956007870501950261188e565b936009850501930261188e565b0160011b016064900590565b61214168056bc75e2d631000006756bc75e2d631000092026805c548670b9510e7ac900590565b920191612092565b61217068056bc75e2d6310000067ad78ebc5ac62000092026806248f33704b286603900590565b920191612080565b6121a068056bc75e2d6310000068015af1d78b58c4000092026806f5f1775788937937900590565b92019161206e565b6121d068056bc75e2d631000006802b5e3af16b188000092026808f00f760a4b2db55d900590565b92019161205c565b68056bc75e2d6310000092830192680ebc5fb4174612111091020561204a565b61222068056bc75e2d63100000680ad78ebc5ac6200000920268280e60114edb805d03900590565b920191612038565b61225168056bc75e2d631000006815af1d78b58c4000009202690127fa27722cc06cc5e2900590565b920191612026565b61228268056bc75e2d63100000682b5e3af16b188000009202693f1fce3da636ea5cf850900590565b920191612013565b6122b568056bc75e2d631000006856bc75e2d63100000092026b02df0ab5a80a22c61ab5a700900590565b920191612000565b68ad78ebc5ac62000000915069021e19e0c9bab24000006122ee91026e01855144814a7ff805980ff0084000900590565b9201915f611fea565b906803782dace9d900000061231b6120b2926b1425982cf597cd205cef7380900590565b92019050611fc5565b5072195e54c5dd42177f53a27172fa9ec63026282760241b90056806f05b59d3b2000000611fa9565b61235961235e91611875565b611f71565b5f039056fea2646970667358221220f27067449771f4cb05150e850e6ba3a00958a2b9557cf1c7f145c5f81e1f173964736f6c634300081c0033
Deployed Bytecode
0x60806040526004361015610011575f80fd5b5f3560e01c806308b3523214610a1b5780630ac6aa691461097b5780630f8cb3211461095457806354b125a6146106fe5780635dc9bdbe1461066657806362576930146106315780636e22df2f1461060b5780636e4b3f20146105e5578063771a49c0146104f557806394f8c15b14610415578063955ee4e7146103f2578063a34560c6146103b6578063bcc454e214610349578063d1b087c9146102fc578063e7f317631461021a578063e8a89c76146101165763f2344deb146100d4575f80fd5b3461011257602036600319011261011257602061010a6100f2610c66565b6100fb81611543565b6101048261161c565b916118a7565b604051908152f35b5f80fd5b346101125760203660031901126101125761012f610c66565b61013761136a565b50610141816113ad565b61014d84929394611543565b9061010061015a84611543565b0151926001600160ff1b038411610112576101c0956101858461017f61010097611aa8565b93610fed565b926040519660018060a01b0316875260018060a01b0316602087015260018060a01b0316604086015260608501526080840152805160a0840152602081015160c0840152604081015160e084015260018060a01b0360608201511682840152608081015161012084015260a081015161014084015260c081015161016084015260e081015161018084015201516101a0820152f35b3461011257602036600319011261011257610233610c66565b61024b61023f826113ad565b5050916100fb81611543565b670de0b6b3a76400000390670de0b6b3a764000082116102e857604051633ba0b9a960e01b815290602090829060049082906001600160a01b03165afa9081156102dd575f916102aa575b602061010a836102a58661146e565b6114a5565b90506020813d6020116102d5575b816102c560209383610ce5565b8101031261011257516020610296565b3d91506102b8565b6040513d5f823e3d90fd5b634e487b7160e01b5f52601160045260245ffd5b3461011257604036600319011261011257602061010a61031a610c66565b61034361033860243561033d6103386103328361145d565b86610e1e565b6114dd565b93610e1e565b90611512565b3461011257602036600319011261011257610362610c66565b6004602061037a610372846113ad565b5050936112da565b604051633ba0b9a960e01b815290939092839182906001600160a01b03165afa9081156102dd575f916102aa57602061010a836102a58661146e565b3461011257604036600319011261011257602061010a6103d4610c66565b6103436024356103ec6103e68261145d565b84610e1e565b92610e1e565b3461011257602036600319011261011257602061010a610410610c66565b6112da565b346101125761042336610d08565b9061042c611107565b5060405163b1f3606560e01b81526001600160a01b03841660048201526024810191909152608081604481305afa9081156102dd575f925f945f925f946104a5575b50916104836104a39492866101209895611131565b926040519586526020860152604085015260608401526080830190610d32565bf35b955092509250506080833d6080116104ed575b816104c560809383610ce5565b810103126101125782516020840151604085015160609095015190949193909261048361046e565b3d91506104b8565b346101125760803660031901126101125761050e610c66565b602435906001600160a01b03821682036101125760a061055092610530611107565b50604051809481926326e44ccf60e01b8352604435908660048501610dc1565b0381305afa80156102dd57610140925f915f915f5f915f936105a5575b5061058085966104a39660643591611131565b93604051968752602087015260408601526060850152608084015260a0830190610d32565b9150506104a3935061058092506105d4915060a03d60a0116105de575b6105cc8183610ce5565b810190610d9a565b939550919361056d565b503d6105c2565b346101125760a06105fe6105f836610d08565b91611131565b6104a36040518092610d32565b3461011257602036600319011261011257602061010a61062c6100f2610c66565b6110de565b346101125760203660031901126101125761064a610c66565b6004602061037a61065a846113ad565b5050936100fb81611543565b346101125761014036600319011261011257610680610c66565b6101203660231901126101125760405161069981610c9a565b602435815260443560208201526064356040820152608435906001600160a01b03821682036101125760209261010a92606083015260a435608083015260c43560a083015260e43560c08301526101043560e083015261012435610100830152610fed565b34610112576020366003190112610112576020600461071b610c66565b610724816113ad565b506040516376d5de8560e01b815290949093909184919082906001600160a01b03165afa9182156102dd575f92610918575b5060405163313ce56760e01b8152926020846004816001600160a01b0387165afa9081156102dd576004945f926108f6575b5060405163313ce56760e01b81529460209186919082906001600160a01b03165afa9384156102dd575f946108b1575b5082916107e960a06107cd60ff829516610d8c565b604051809381926326e44ccf60e01b8352888760048501610dc1565b0381305afa5f918161088e575b50610882575061080b60ff5f19965b16610d8c565b6040516331562d0560e01b8152938492839261082b929160048501610de3565b0381305afa5f918161085d575b5061085457506108505f195b60405193849384610c7c565b0390f35b61085090610844565b61087791925060a03d60a0116105de576105cc8183610ce5565b505050509084610838565b60ff61080b9196610805565b6108a6919250843d86116105de576105cc8183610ce5565b5050505090876107f6565b60a0919450916107e9826107cd60ff6108e2889760203d6020116108ef575b6108da8183610ce5565b810190610d73565b98955050505050916107b8565b503d6108d0565b602091925061091190823d84116108ef576108da8183610ce5565b9190610788565b9091506020813d60201161094c575b8161093460209383610ce5565b810103126101125761094590610d5f565b9083610756565b3d9150610927565b3461011257604036600319011261011257602061010a610972610c66565b60243590610e1e565b3461011257604036600319011261011257610994610c66565b6109a66024356103ec6103e68261145d565b6a0c097ce7bc90715b34b9f160241b908215610a0757828204918115610a07576020936102a5610a0161010a956102a56109fb6109f1886103439804966109ec816110c8565b6114af565b976109ec816110c8565b9661146e565b9361146e565b634e487b7160e01b5f52601260045260245ffd5b346101125760203660031901126101125760206004610a38610c66565b610a41816113ad565b6040516376d5de8560e01b815290959094909285925082906001600160a01b03165afa9182156102dd575f92610c2a575b5060405163313ce56760e01b8152926020846004816001600160a01b0387165afa9081156102dd576004945f92610c08575b5060405163313ce56760e01b81529460209186919082906001600160a01b03165afa9384156102dd575f94610bd1575b508291610b0760a0610aeb60ff6101009516610d8c565b604051809381926374f669d960e11b8352888760048501610dc1565b0381305afa5f9181610bac575b50610ba05750610b2860ff5f199616610d8c565b604051631c3cb1ff60e21b81529384928392610b48929160048501610de3565b0381305afa5f9181610b6b575061085457506108505f1960405193849384610c7c565b909150610100813d8211610b98575b81610b886101009383610ce5565b8101031261011257519084610838565b3d9150610b7a565b60ff610b289196610805565b610bc691925060a03d60a0116105de576105cc8183610ce5565b505050509087610b14565b61010091945091610b0760a0610aeb60ff610bfb889760203d6020116108ef576108da8183610ce5565b9895505050505091610ad4565b6020919250610c2390823d84116108ef576108da8183610ce5565b9190610aa4565b9091506020813d602011610c5e575b81610c4660209383610ce5565b8101031261011257610c5790610d5f565b9083610a72565b3d9150610c39565b600435906001600160a01b038216820361011257565b604091949392606082019560018060a01b0316825260208201520152565b61012081019081106001600160401b03821117610cb657604052565b634e487b7160e01b5f52604160045260245ffd5b60a081019081106001600160401b03821117610cb657604052565b601f909101601f19168101906001600160401b03821190821017610cb657604052565b6060906003190112610112576004356001600160a01b038116810361011257906024359060443590565b60808091805184526020810151602085015260408101516040850152606081015160608501520151910152565b51906001600160a01b038216820361011257565b90816020910312610112575160ff811681036101125790565b604d81116102e857600a0a90565b908160a0910312610112578051916020820151916040810151916080606083015192015190565b6001600160a01b03918216815291166020820152604081019190915260600190565b6001600160a01b0391821681526020810192909252909116604082015260600190565b90816020910312610112575180151581036101125790565b604051630bc4ed8360e21b81529091906020816004816001600160a01b0387165afa9081156102dd575f91610fbe575b50610fb057610e70610e68610e6284611543565b9361161c565b429084611682565b91516020830151835190604085015192848112610f8057610ea7610ea1610eac93610e9b88856114fa565b936112bf565b9161182f565b61189d565b670d529ae9e86000008113610f6257610ed99291610ea7610ecf610ed493611a06565b61182f565b6112bf565b90670de0b6b3a76400008212610f4f575f1215610f2c57610ea76060610f019301519161182f565b670de0b6b3a76400008112610f1a575f81126101125790565b63329e322960e21b5f5260045260245ffd5b610f44906060670de0b6b3a764000093015190611853565b055f81126101125790565b5063329e322960e21b5f5260045260245ffd5b637e34684f60e11b5f52600452670d529ae9e860000060245260445ffd5b60405162461bcd60e51b81526020600482015260086024820152676e6567617469766560c01b6044820152606490fd5b5050670de0b6b3a764000090565b610fe0915060203d602011610fe6575b610fd88183610ce5565b810190610e06565b5f610e4e565b503d610fce565b604051630bc4ed8360e21b81529192916020816004816001600160a01b0386165afa9081156102dd575f916110a9575b5061109b57610e6861102e9161161c565b9151602083015160408451940151915f8112610f8057610ea7610ea161105893610e9b5f856114fa565b92670d529ae9e8600000841361107c57610ed490610ea7610ecf610f019596611a06565b83637e34684f60e11b5f52600452670d529ae9e860000060245260445ffd5b50670de0b6b3a76400009150565b6110c2915060203d602011610fe657610fd88183610ce5565b5f61101d565b670de0b6b3a763ffff198101919082116102e857565b670de0b6b3a76400000390670de0b6b3a764000082116102e857565b919082039182116102e857565b6040519061111482610cca565b5f6080838281528260208201528260408201528260608201520152565b611139611107565b5061115761114f61114983611543565b9261161c565b429083611682565b9051611189670de0b6b3a764000061118361117b60608601516040870151906114fa565b855190611853565b05611aa8565b670de0b6b3a76400008101670de0b6b3a764000081125f83129080158216911516176102e8576111e7936111da60206111d16111e094610ea7670de0b6b3a76400009761182f565b920151856112bf565b90611853565b05906114fa565b6103e78102908082046103e714901517156102e8576103e890049061120a611107565b508260011c6509184e72a00081105f146112b157915b670de0b6b3a764000061123b611235866110de565b84611492565b0493806005029060058204036102e857670de0b6b3a76400000180670de0b6b3a7640000116102e857611277670de0b6b3a76400009184611492565b04808210156112aa57505b6040519361128f85610cca565b845260208401526040830152601e6060830152608082015290565b9050611282565b506509184e72a00091611220565b9190915f83820193841291129080158216911516176102e857565b61132790610ea760406112ec83611543565b926112f68161161c565b60a085015142106113315761131d91506113178551916020870151906119a6565b906112bf565b925b01519161182f565b5f81126101125790565b670de0b6b3a764000061135d611364936111da602061135142878c611682565b015194898051936118a7565b05906112bf565b9261131f565b6040519061137782610c9a565b5f610100838281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e08201520152565b604051630b2339af60e21b81529190606090839060049082906001600160a01b03165afa9081156102dd575f5f935f936113e8575b50929190565b92505091506060813d606011611455575b8161140660609383610ce5565b81010312610112578051916001600160a01b0383168303610112576020820151916001600160a01b03831683036101125760400151926001600160a01b0384168403610112579192915f6113e2565b3d91506113f9565b5f121561146957600190565b5f1990565b90670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102e857565b818102929181159184041417156102e857565b8115610a07570490565b90670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102e8576114da916114a5565b90565b670de0b6b3a763ffff198101908082116102e8576114da916114af565b81810392915f1380158285131691841216176102e857565b6001600160ff1b038111610112576001600160ff1b038211610112576109ec61153e6114da93836114fa565b6119eb565b61154b61136a565b50604051639e48767360e01b81526001600160a01b03909116600482015261012081602481305afa9081156102dd575f91611584575090565b9050610120813d8211611614575b816115a06101209383610ce5565b8101031261011257610100604051916115b883610c9a565b8051835260208101516020840152604081015160408401526115dc60608201610d5f565b60608401526080810151608084015260a081015160a084015260c081015160c084015260e081015160e0840152015161010082015290565b3d9150611592565b6040516314ae175360e11b81526001600160a01b039091166004820152602081602481305afa9081156102dd575f91611653575090565b90506020813d60201161167a575b8161166e60209383610ce5565b81010312610112575190565b3d9150611661565b6040519293929190608083016001600160401b03811184821017610cb6576040525f835260208301905f8252604084015f815260608501945f8652809760a08401908082511115611820576116d791516110fa565b936080840151956116ed6301e133808098611853565b6001600160ff1b038711610112578615610a0757600160ff1b81145f198814166102e8578690055f81131561180e578352602085015161172c916119a6565b808252845180158015611806575b6117f1575050835161175a876102a5886101008901519551965195611492565b6001600160ff1b0381116101125761177190611aa8565b92670de0b6b3a764000084126117de57926117ad60c09593610ea7610ecf6117a886610ea7610ea16117bc9e9d9b6117b39a6112bf565b611a06565b906114fa565b90520151611492565b8115610a0757046001600160ff1b038111610112576117da90611aa8565b9052565b8363329e322960e21b5f5260045260245ffd5b63b1c4aefb60e01b5f5260045260245260445ffd5b50811561173a565b630e520c3b60e11b5f5260045260245ffd5b63b2094b5960e01b5f5260045ffd5b90670de0b6b3a7640000820291808305670de0b6b3a764000014901517156102e857565b81810292915f8212600160ff1b8214166102e85781840514901517156102e857565b8015610a07576a0c097ce7bc90715b34b9f160241b0590565b68056bc75e2d63100000900590565b8115610a07570590565b9160a0820190815142101561190a57506118d392506118cb610100914290516110fa565b910151611492565b6301e1338090046001600160ff1b038111610112576118f190611aa8565b6a0c097ce7bc90715b34b9f160241b8115610a07570590565b915050602061191a6004936113ad565b5050604051633ba0b9a960e01b815293849182906001600160a01b03165afa9182156102dd575f92611972575b50670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102e8576114da916114a5565b9091506020813d60201161199e575b8161198e60209383610ce5565b810103126101125751905f611947565b3d9150611981565b6119cc670de0b6b3a7640000915f84125f146119e4576119c75f19946119eb565b611492565b046001600160ff1b038111610112576114da91611853565b6119c76001945b5f8113156119f65790565b600160ff1b81146102e8575f0390565b670de0b6b3a76400008114611a5a5780670de0b6b3a764000003905f8112670de0b6b3a76400008312811690670de0b6b3a76400008413901516176102e8576114da91610ea7611a559261182f565b611e5a565b63a9c8b14d60e01b5f5260045ffd5b15611a7057565b60405162461bcd60e51b815260206004820152601060248201526f125b9d985b1a5908195e1c1bdb995b9d60821b6044820152606490fd5b680238fd42c5cf03ffff1981121580611e47575b611ac590611a69565b5f8112611e33576114da906806f05b59d3b20000008112611df25772195e54c5dd42177f53a27172fa9ec63026282760241b90611cb1906064906806f05b59d3b1ffffff19015b0268056bc75e2d631000009068ad78ebc5ac62000000811215611dcf575b6856bc75e2d631000000811215611da5575b682b5e3af16b18800000811215611d7d575b6815af1d78b58c400000811215611d55575b680ad78ebc5ac6200000811215611d2e575b68056bc75e2d63100000811215611d07575b6802b5e3af16b1880000811215611ce0575b68015af1d78b58c40000811215611cb9575b611bbd611bb682800261188e565b6002900590565b611bd2611bcb83830261188e565b6003900590565b611be7611be084830261188e565b6004900590565b611bfc611bf585830261188e565b6005900590565b611c11611c0a86830261188e565b6006900590565b611c26611c1f87830261188e565b6007900590565b90611c3c611c3588840261188e565b6008900590565b92611c52611c4b89860261188e565b6009900590565b9468056bc75e2d63100000611c72611c6b8b890261188e565b600a900590565b97611c88611c818c8b0261188e565b600b900590565b99611c9e611c978d8d0261188e565b600c900590565b9b0101010101010101010101010261188e565b026064900590565b68015af1d78b58c3ffff190190611cda906806f5f17757889379370261188e565b90611ba8565b6802b5e3af16b187ffff190190611d01906808f00f760a4b2db55d0261188e565b90611b96565b68056bc75e2d630fffff190190611d2890680ebc5fb417461211100261188e565b90611b84565b680ad78ebc5ac61fffff190190611d4f9068280e60114edb805d030261188e565b90611b72565b6815af1d78b58c3fffff190190611d7790690127fa27722cc06cc5e20261188e565b90611b60565b682b5e3af16b187fffff190190611d9f90693f1fce3da636ea5cf8500261188e565b90611b4e565b6856bc75e2d630ffffff190190611dc9906b02df0ab5a80a22c61ab5a7000261188e565b90611b3c565b6e01855144814a7ff805980ff0084000915068ad78ebc5ac61ffffff1901611b2a565b6803782dace9d90000008112611e26576803782dace9d8ffffff1901611cb160646b1425982cf597cd205cef738092611b0c565b611cb16064600192611b0c565b611e3e905f03611aa8565b6114da90611875565b5068070c1cc73b00c80000811315611abc565b5f811315611f3c5780670c7d713b49da00001280611f2b575b15611f2257670de0b6b3a764000090611eb39082026a0c097ce7bc90715b34b9f160241b818101916ec097ce7bc90715b34b9f0fffffffff19010261189d565b60036a0c097ce7bc90715b34b9f160241b828002819005808402829005928305909301600592840282900592830501600792840282900592830501600992840282900592830501600b92840282900592830501600d92840282900592830501600f9290930205050160011b0590565b6114da90611f71565b50670f43fc2c04ee00008112611e73565b60405162461bcd60e51b815260206004820152600d60248201526c6f7574206f6620626f756e647360981b6044820152606490fd5b670de0b6b3a7640000811261234d576114da905f775803bcc5cb9634ba4cfb2213f784019318ed4dcb6017880f60361b821215612324575b6f8bcc0026baae9e45e470190267a230cf60191b8212156122f7575b6120b2906064808492029302906e01855144814a7ff805980ff00840008212156122bd575b506b02df0ab5a80a22c61ab5a70081121561228a575b693f1fce3da636ea5cf850811215612259575b690127fa27722cc06cc5e2811215612228575b68280e60114edb805d038112156121f8575b680ebc5fb417461211108112156121d8575b6808f00f760a4b2db55d8112156121a8575b6806f5f1775788937937811215612178575b6806248f33704b286603811215612149575b6805c548670b9510e7ac81121561211a575b68056bc75e2d631000008181019168056bc75e2d630fffff19010261189d565b61210e611c816120c383800261188e565b612101816120f4816120e7816120da818b0261188e565b9960038b0501990261188e565b976005890501970261188e565b956007870501950261188e565b936009850501930261188e565b0160011b016064900590565b61214168056bc75e2d631000006756bc75e2d631000092026805c548670b9510e7ac900590565b920191612092565b61217068056bc75e2d6310000067ad78ebc5ac62000092026806248f33704b286603900590565b920191612080565b6121a068056bc75e2d6310000068015af1d78b58c4000092026806f5f1775788937937900590565b92019161206e565b6121d068056bc75e2d631000006802b5e3af16b188000092026808f00f760a4b2db55d900590565b92019161205c565b68056bc75e2d6310000092830192680ebc5fb4174612111091020561204a565b61222068056bc75e2d63100000680ad78ebc5ac6200000920268280e60114edb805d03900590565b920191612038565b61225168056bc75e2d631000006815af1d78b58c4000009202690127fa27722cc06cc5e2900590565b920191612026565b61228268056bc75e2d63100000682b5e3af16b188000009202693f1fce3da636ea5cf850900590565b920191612013565b6122b568056bc75e2d631000006856bc75e2d63100000092026b02df0ab5a80a22c61ab5a700900590565b920191612000565b68ad78ebc5ac62000000915069021e19e0c9bab24000006122ee91026e01855144814a7ff805980ff0084000900590565b9201915f611fea565b906803782dace9d900000061231b6120b2926b1425982cf597cd205cef7380900590565b92019050611fc5565b5072195e54c5dd42177f53a27172fa9ec63026282760241b90056806f05b59d3b2000000611fa9565b61235961235e91611875565b611f71565b5f039056fea2646970667358221220f27067449771f4cb05150e850e6ba3a00958a2b9557cf1c7f145c5f81e1f173964736f6c634300081c0033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 31 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.