Feature Tip: Add private address tag to any address under My Name Tag !
Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Contract Name:
OrigamiPendlePtToAssetOracle
Compiler Version
v0.8.19+commit.7dd6d404
Optimization Enabled:
Yes with 10000 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
pragma solidity 0.8.19; // SPDX-License-Identifier: AGPL-3.0-or-later // Origami (common/oracle/OrigamiPendlePtToAssetOracle.sol) import { PendlePYOracleLib } from "@pendle/core-v2/contracts/oracles/PendlePYOracleLib.sol"; import { PendlePYLpOracle } from "@pendle/core-v2/contracts/oracles/PendlePYLpOracle.sol"; import { IPMarket } from "@pendle/core-v2/contracts/interfaces/IPMarket.sol"; import { OrigamiOracleBase } from "contracts/common/oracle/OrigamiOracleBase.sol"; import { OrigamiMath } from "contracts/libraries/OrigamiMath.sol"; /** * @title OrigamiPendlePtToAssetOracle * @notice A Pendle PT to Asset oracle price, for a given market and twap duration * @dev Pendle oracle price definition example: 1 <PT sUSDe> is equal to 1 <USDe> deposited on Ethena at maturity. */ contract OrigamiPendlePtToAssetOracle is OrigamiOracleBase { using PendlePYOracleLib for IPMarket; error UninitializedPendleOracle(); /** * @notice The pendle market to observe */ IPMarket public immutable pendleMarket; /** * @notice The twap duration to observe over. * @dev If an update is required here, the oracle can be redeployed. */ uint32 public immutable twapDuration; constructor ( BaseOracleParams memory baseParams, address _pendleOracle, address _pendleMarket, uint32 _twapDuration ) OrigamiOracleBase(baseParams) { pendleMarket = IPMarket(_pendleMarket); twapDuration = _twapDuration; // Check that the pendle oracle is initialized properly. // It's the deployer's responsibility to do so prior. ( bool increaseCardinalityRequired, , bool oldestObservationSatisfied ) = PendlePYLpOracle(_pendleOracle).getOracleState( _pendleMarket, _twapDuration ); if (increaseCardinalityRequired || !oldestObservationSatisfied) revert UninitializedPendleOracle(); } /** * @notice Return the latest oracle price, to `decimals` precision */ function latestPrice( PriceType /*priceType*/, OrigamiMath.Rounding /*roundingMode*/ ) public override view returns (uint256 price) { // There isn't a separate historic reference price, so return the same price for both SPOT and HISTORIC // There isn't any extra rounding required here either. // The pendle returns a rate such that `1 PT * rate / 1e18 = amount of underlying` // It is ok to assume that the PT and underlying have the same decimals, and so the rate is 18dp. // Since this matches our origami oracle, no scaling is required. // If in future for a new oracle the PT does not have the same decimals as the underlying (would be strange), // a change can be made here to scale it. return pendleMarket.getPtToAssetRate(twapDuration); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// 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; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract BoringOwnableUpgradeableData { address public owner; address public pendingOwner; } abstract contract BoringOwnableUpgradeable is BoringOwnableUpgradeableData, Initializable { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function __BoringOwnable_init() internal onlyInitializing { owner = msg.sender; } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } uint256[48] private __gap; }
// 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; } // @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 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) / market.totalLp; } else { lpToAccount = netLpBySy; syUsed = syDesired; ptUsed = (market.totalPt * lpToAccount) / 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 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 "@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; 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; interface IPPYLpOracle { event SetBlockCycleNumerator(uint16 newBlockCycleNumerator); function getPtToAssetRate(address market, uint32 duration) external view returns (uint256); function getYtToAssetRate(address market, uint32 duration) external view returns (uint256); function getLpToAssetRate(address market, uint32 duration) external view returns (uint256); function getPtToSyRate(address market, uint32 duration) external view returns (uint256); function getYtToSyRate(address market, uint32 duration) external view returns (uint256); function getLpToSyRate(address market, uint32 duration) external view returns (uint256); function getOracleState( address market, uint32 duration ) external view returns (bool increaseCardinalityRequired, uint16 cardinalityRequired, bool oldestObservationSatisfied); }
// 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 "./PendlePYOracleLib.sol"; library PendleLpOracleLib { using PendlePYOracleLib for IPMarket; using PMath for uint256; using PMath for int256; using MarketMathCore for MarketState; /** * This function returns the approximated twap rate LP/asset on market, but take into account the current rate of SY This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate * @param market market to get rate from * @param duration twap duration */ function getLpToAssetRate(IPMarket market, uint32 duration) internal view returns (uint256) { (uint256 syIndex, uint256 pyIndex) = market.getSYandPYIndexCurrent(); uint256 lpToAssetRateRaw = _getLpToAssetRateRaw(market, duration, pyIndex); if (syIndex >= pyIndex) { return lpToAssetRateRaw; } else { return (lpToAssetRateRaw * syIndex) / pyIndex; } } /** * This function returns the approximated twap rate LP/asset on market, but take into account the current rate of SY This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate * @param market market to get rate from * @param duration twap duration */ function getLpToSyRate(IPMarket market, uint32 duration) internal view returns (uint256) { (uint256 syIndex, uint256 pyIndex) = market.getSYandPYIndexCurrent(); uint256 lpToAssetRateRaw = _getLpToAssetRateRaw(market, duration, pyIndex); if (syIndex >= pyIndex) { return lpToAssetRateRaw.divDown(syIndex); } else { return lpToAssetRateRaw.divDown(pyIndex); } } function _getLpToAssetRateRaw( IPMarket market, uint32 duration, uint256 pyIndex ) private view returns (uint256 lpToAssetRateRaw) { MarketState memory state = market.readState(address(0)); int256 totalHypotheticalAsset; if (state.expiry <= block.timestamp) { // 1 PT = 1 Asset post-expiry totalHypotheticalAsset = state.totalPt + PYIndexLib.syToAsset(PYIndex.wrap(pyIndex), state.totalSy); } else { MarketPreCompute memory comp = state.getMarketPreCompute(PYIndex.wrap(pyIndex), block.timestamp); (int256 rateOracle, int256 rateHypTrade) = _getPtRatesRaw(market, state, duration); int256 cParam = LogExpMath.exp(comp.rateScalar.mulDown((rateOracle - comp.rateAnchor))); int256 tradeSize = (cParam.mulDown(comp.totalAsset) - state.totalPt).divDown( PMath.IONE + cParam.divDown(rateHypTrade) ); totalHypotheticalAsset = comp.totalAsset - tradeSize.divDown(rateHypTrade) + (state.totalPt + tradeSize).divDown(rateOracle); } lpToAssetRateRaw = totalHypotheticalAsset.divDown(state.totalLp).Uint(); } function _getPtRatesRaw( IPMarket market, MarketState memory state, uint32 duration ) private view returns (int256 rateOracle, int256 rateHypTrade) { uint256 lnImpliedRate = market.getMarketLnImpliedRate(duration); uint256 timeToExpiry = state.expiry - block.timestamp; rateOracle = MarketMathCore._getExchangeRateFromImpliedRate(lnImpliedRate, timeToExpiry); int256 rateLastTrade = MarketMathCore._getExchangeRateFromImpliedRate(state.lastLnImpliedRate, timeToExpiry); rateHypTrade = (rateLastTrade + rateOracle) / 2; } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.17; import "./PendlePYOracleLib.sol"; import "./PendleLpOracleLib.sol"; import "../interfaces/IPPYLpOracle.sol"; import "../core/libraries/BoringOwnableUpgradeable.sol"; // This is a pre-deployed version of PendlePtOracleLib & PendleLpOracleLib with additional utility functions. // Use of this contract rather than direct library integration resulting in a smaller bytecode size and simpler structure // but slightly higher gas usage (~ 4000 gas, 2 external calls & 1 cold code load) contract PendlePYLpOracle is BoringOwnableUpgradeable, IPPYLpOracle { using PendlePYOracleLib for IPMarket; using PendleLpOracleLib for IPMarket; error InvalidBlockRate(uint256 blockCycleNumerator); error TwapDurationTooLarge(uint32 duration, uint32 cardinalityRequired); /// @notice Oracles will be created ensuring a lowerbound in PendleMarket oracle's cardinality /// @dev Cardinality lowerbound will be calculated as twap_duration * 1000 / blockCycleNumerator /// @dev blockCycleNumerator should be configured so that blockCycleNumerator / 1000 < actual block cycle /// @dev blockCycleNumerator should be greater or equal to 1000 since the oracle only records one /// rate per timestamp /// For example, on Ethereum blockCycleNumerator = 11000, where 11000/1000 = 11 < 12 /// Arbitrum blockCycleNumerator = 1000, since we can't do better than this uint16 public blockCycleNumerator; uint16 public constant BLOCK_CYCLE_DENOMINATOR = 1000; constructor() { _disableInitializers(); } function initialize(uint16 _blockCycleNumerator) external initializer { __BoringOwnable_init(); _setBlockCycleNumerator(_blockCycleNumerator); } // Refer to https://docs.pendle.finance/Home on how to use the oracle /*/////////////////////////////////////////////////////////////// PT, YT, LP to SY //////////////////////////////////////////////////////////////*/ function getPtToSyRate(address market, uint32 duration) external view returns (uint256) { return IPMarket(market).getPtToSyRate(duration); } function getYtToSyRate(address market, uint32 duration) external view returns (uint256) { return IPMarket(market).getYtToSyRate(duration); } function getLpToSyRate(address market, uint32 duration) external view returns (uint256) { return IPMarket(market).getLpToSyRate(duration); } /*/////////////////////////////////////////////////////////////// PT, YT, LP to Asset //////////////////////////////////////////////////////////////*/ /// @notice make sure you have taken into account the risk of not being able to withdraw from SY to Asset function getPtToAssetRate(address market, uint32 duration) external view returns (uint256) { return IPMarket(market).getPtToAssetRate(duration); } function getYtToAssetRate(address market, uint32 duration) external view returns (uint256) { return IPMarket(market).getYtToAssetRate(duration); } function getLpToAssetRate(address market, uint32 duration) external view returns (uint256) { return IPMarket(market).getLpToAssetRate(duration); } /*/////////////////////////////////////////////////////////////// Utility functions //////////////////////////////////////////////////////////////*/ /** * A check function for the cardinality status of the market * @param market PendleMarket address * @param duration twap duration * @return increaseCardinalityRequired a boolean indicates whether the cardinality should be increased to serve the duration * @return cardinalityRequired the amount of cardinality required for the twap duration */ function getOracleState( address market, uint32 duration ) external view returns (bool increaseCardinalityRequired, uint16 cardinalityRequired, bool oldestObservationSatisfied) { (, , , uint16 observationIndex, uint16 observationCardinality, uint16 cardinalityReserved) = IPMarket(market) ._storage(); // checkIncreaseCardinalityRequired cardinalityRequired = _calcCardinalityRequiredRequired(duration); increaseCardinalityRequired = cardinalityReserved < cardinalityRequired; // check oldestObservationSatisfied (uint32 oldestTimestamp, , bool initialized) = IPMarket(market).observations( (observationIndex + 1) % observationCardinality ); if (!initialized) { (oldestTimestamp, , ) = IPMarket(market).observations(0); } oldestObservationSatisfied = oldestTimestamp < block.timestamp - duration; } function _calcCardinalityRequiredRequired(uint32 duration) internal view returns (uint16) { uint32 cardinalityRequired = (duration * BLOCK_CYCLE_DENOMINATOR + blockCycleNumerator - 1) / blockCycleNumerator + 1; if (cardinalityRequired > type(uint16).max) { revert TwapDurationTooLarge(duration, cardinalityRequired); } return uint16(cardinalityRequired); } // --- Owner-Only Functions --- function setBlockCycleNumerator(uint16 newBlockCycleNumerator) external onlyOwner { _setBlockCycleNumerator(newBlockCycleNumerator); } function _setBlockCycleNumerator(uint16 newBlockCycleNumerator) internal { if (newBlockCycleNumerator < BLOCK_CYCLE_DENOMINATOR) { revert InvalidBlockRate(newBlockCycleNumerator); } blockCycleNumerator = newBlockCycleNumerator; emit SetBlockCycleNumerator(newBlockCycleNumerator); } }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "../interfaces/IPMarket.sol"; import "../core/libraries/math/PMath.sol"; // This library can & should be integrated directly for optimal gas usage. // If you prefer not to integrate it directly, the PendlePtOracle contract (a pre-deployed version of this contract) can be used. library PendlePYOracleLib { using PMath for uint256; using PMath for int256; /** * This function returns the twap rate PT/Asset on market, but take into account the current rate of SY This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate * @param market market to get rate from * @param duration twap duration */ function getPtToAssetRate(IPMarket market, uint32 duration) internal view returns (uint256) { (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market); if (syIndex >= pyIndex) { return getPtToAssetRateRaw(market, duration); } else { return (getPtToAssetRateRaw(market, duration) * syIndex) / pyIndex; } } /** * This function returns the twap rate YT/Asset on market, but take into account the current rate of SY This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate * @param market market to get rate from * @param duration twap duration */ function getYtToAssetRate(IPMarket market, uint32 duration) internal view returns (uint256) { (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market); if (syIndex >= pyIndex) { return getYtToAssetRateRaw(market, duration); } else { return (getYtToAssetRateRaw(market, duration) * syIndex) / pyIndex; } } /// @notice Similar to getPtToAsset but returns the rate in SY instead function getPtToSyRate(IPMarket market, uint32 duration) internal view returns (uint256) { (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market); if (syIndex >= pyIndex) { return getPtToAssetRateRaw(market, duration).divDown(syIndex); } else { return getPtToAssetRateRaw(market, duration).divDown(pyIndex); } } /// @notice Similar to getPtToAsset but returns the rate in SY instead function getYtToSyRate(IPMarket market, uint32 duration) internal view returns (uint256) { (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market); if (syIndex >= pyIndex) { return getYtToAssetRateRaw(market, duration).divDown(syIndex); } else { return getYtToAssetRateRaw(market, duration).divDown(pyIndex); } } /// @notice returns the raw rate without taking into account whether SY is solvent function getPtToAssetRateRaw(IPMarket market, uint32 duration) internal view returns (uint256) { uint256 expiry = market.expiry(); if (expiry <= block.timestamp) { return PMath.ONE; } else { uint256 lnImpliedRate = getMarketLnImpliedRate(market, duration); uint256 timeToExpiry = expiry - block.timestamp; uint256 assetToPtRate = MarketMathCore._getExchangeRateFromImpliedRate(lnImpliedRate, timeToExpiry).Uint(); return PMath.ONE.divDown(assetToPtRate); } } /// @notice returns the raw rate without taking into account whether SY is solvent function getYtToAssetRateRaw(IPMarket market, uint32 duration) internal view returns (uint256) { return PMath.ONE - getPtToAssetRateRaw(market, duration); } function getSYandPYIndexCurrent(IPMarket market) internal view returns (uint256 syIndex, uint256 pyIndex) { (IStandardizedYield SY, , IPYieldToken YT) = market.readTokens(); syIndex = SY.exchangeRate(); uint256 pyIndexStored = YT.pyIndexStored(); if (YT.doCacheIndexSameBlock() && YT.pyIndexLastUpdatedBlock() == block.number) { pyIndex = pyIndexStored; } else { pyIndex = PMath.max(syIndex, pyIndexStored); } } function getMarketLnImpliedRate(IPMarket market, uint32 duration) internal view returns (uint256) { uint32[] memory durations = new uint32[](2); durations[0] = duration; uint216[] memory lnImpliedRateCumulative = market.observe(durations); return (lnImpliedRateCumulative[1] - lnImpliedRateCumulative[0]) / duration; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.19; // Common.sol // // Common mathematical functions needed by both SD59x18 and UD60x18. Note that these global functions do not // always operate with SD59x18 and UD60x18 numbers. /*////////////////////////////////////////////////////////////////////////// CUSTOM ERRORS //////////////////////////////////////////////////////////////////////////*/ /// @notice Thrown when the resultant value in {mulDiv} overflows uint256. error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator); /// @notice Thrown when the resultant value in {mulDiv18} overflows uint256. error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y); /// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`. error PRBMath_MulDivSigned_InputTooSmall(); /// @notice Thrown when the resultant value in {mulDivSigned} overflows int256. error PRBMath_MulDivSigned_Overflow(int256 x, int256 y); /*////////////////////////////////////////////////////////////////////////// CONSTANTS //////////////////////////////////////////////////////////////////////////*/ /// @dev The maximum value a uint128 number can have. uint128 constant MAX_UINT128 = type(uint128).max; /// @dev The maximum value a uint40 number can have. uint40 constant MAX_UINT40 = type(uint40).max; /// @dev The unit number, which the decimal precision of the fixed-point types. uint256 constant UNIT = 1e18; /// @dev The unit number inverted mod 2^256. uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant /// bit in the binary representation of `UNIT`. uint256 constant UNIT_LPOTD = 262144; /*////////////////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////////////////*/ /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. /// @custom:smtchecker abstract-function-nondet function exp2(uint256 x) pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points: // // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65. // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1, // we know that `x & 0xFF` is also 1. if (x & 0xFF00000000000000 > 0) { if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } } if (x & 0xFF000000000000 > 0) { if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } } if (x & 0xFF0000000000 > 0) { if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } } if (x & 0xFF00000000 > 0) { if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } } if (x & 0xFF000000 > 0) { if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } } if (x & 0xFF0000 > 0) { if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } } if (x & 0xFF00 > 0) { if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } } if (x & 0xFF > 0) { if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } } // In the code snippet below, two operations are executed simultaneously: // // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1 // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192. // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format. // // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the, // integer part, $2^n$. result *= UNIT; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first 1 in the binary representation of x. /// /// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set /// /// Each step in this implementation is equivalent to this high-level code: /// /// ```solidity /// if (x >= 2 ** 128) { /// x >>= 128; /// result += 128; /// } /// ``` /// /// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here: /// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948 /// /// The Yul instructions used below are: /// /// - "gt" is "greater than" /// - "or" is the OR bitwise operator /// - "shl" is "shift left" /// - "shr" is "shift right" /// /// @param x The uint256 number for which to find the index of the most significant bit. /// @return result The index of the most significant bit as a uint256. /// @custom:smtchecker abstract-function-nondet function msb(uint256 x) pure returns (uint256 result) { // 2^128 assembly ("memory-safe") { let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^64 assembly ("memory-safe") { let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^32 assembly ("memory-safe") { let factor := shl(5, gt(x, 0xFFFFFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^16 assembly ("memory-safe") { let factor := shl(4, gt(x, 0xFFFF)) x := shr(factor, x) result := or(result, factor) } // 2^8 assembly ("memory-safe") { let factor := shl(3, gt(x, 0xFF)) x := shr(factor, x) result := or(result, factor) } // 2^4 assembly ("memory-safe") { let factor := shl(2, gt(x, 0xF)) x := shr(factor, x) result := or(result, factor) } // 2^2 assembly ("memory-safe") { let factor := shl(1, gt(x, 0x3)) x := shr(factor, x) result := or(result, factor) } // 2^1 // No need to shift x any more. assembly ("memory-safe") { let factor := gt(x, 0x1) result := or(result, factor) } } /// @notice Calculates x*y÷denominator with 512-bit precision. /// /// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - The denominator must not be zero. /// - The result must fit in uint256. /// /// @param x The multiplicand as a uint256. /// @param y The multiplier as a uint256. /// @param denominator The divisor as a uint256. /// @return result The result as a uint256. /// @custom:smtchecker abstract-function-nondet function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512-bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly ("memory-safe") { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { return prod0 / denominator; } } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath_MulDiv_Overflow(x, y, denominator); } //////////////////////////////////////////////////////////////////////////// // 512 by 256 division //////////////////////////////////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly ("memory-safe") { // Compute remainder using the mulmod Yul instruction. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512-bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } unchecked { // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow // because the denominator cannot be zero at this point in the function execution. The result is always >= 1. // For more detail, see https://cs.stackexchange.com/q/138556/92363. uint256 lpotdod = denominator & (~denominator + 1); uint256 flippedLpotdod; assembly ("memory-safe") { // Factor powers of two out of denominator. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one. // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits. // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693 flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * flippedLpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; } } /// @notice Calculates x*y÷1e18 with 512-bit precision. /// /// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18. /// /// Notes: /// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}. /// - The result is rounded toward zero. /// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations: /// /// $$ /// \begin{cases} /// x * y = MAX\_UINT256 * UNIT \\ /// (x * y) \% UNIT \geq \frac{UNIT}{2} /// \end{cases} /// $$ /// /// Requirements: /// - Refer to the requirements in {mulDiv}. /// - The result must fit in uint256. /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. /// @custom:smtchecker abstract-function-nondet function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly ("memory-safe") { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 == 0) { unchecked { return prod0 / UNIT; } } if (prod1 >= UNIT) { revert PRBMath_MulDiv18_Overflow(x, y); } uint256 remainder; assembly ("memory-safe") { remainder := mulmod(x, y, UNIT) result := mul( or( div(sub(prod0, remainder), UNIT_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1)) ), UNIT_INVERSE ) } } /// @notice Calculates x*y÷denominator with 512-bit precision. /// /// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately. /// /// Notes: /// - The result is rounded toward zero. /// /// Requirements: /// - Refer to the requirements in {mulDiv}. /// - None of the inputs can be `type(int256).min`. /// - The result must fit in int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. /// @custom:smtchecker abstract-function-nondet function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath_MulDivSigned_InputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 xAbs; uint256 yAbs; uint256 dAbs; unchecked { xAbs = x < 0 ? uint256(-x) : uint256(x); yAbs = y < 0 ? uint256(-y) : uint256(y); dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of x*y÷denominator. The result must fit in int256. uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs); if (resultAbs > uint256(type(int256).max)) { revert PRBMath_MulDivSigned_Overflow(x, y); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly ("memory-safe") { // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement. sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs. // If there are, the result should be negative. Otherwise, it should be positive. unchecked { result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs); } } /// @notice Calculates the square root of x using the Babylonian method. /// /// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Notes: /// - If x is not a perfect square, the result is rounded down. /// - Credits to OpenZeppelin for the explanations in comments below. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as a uint256. /// @custom:smtchecker abstract-function-nondet function sqrt(uint256 x) pure returns (uint256 result) { if (x == 0) { return 0; } // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x. // // We know that the "msb" (most significant bit) of x is a power of 2 such that we have: // // $$ // msb(x) <= x <= 2*msb(x)$ // $$ // // We write $msb(x)$ as $2^k$, and we get: // // $$ // k = log_2(x) // $$ // // Thus, we can write the initial inequality as: // // $$ // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\ // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\ // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1} // $$ // // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit. uint256 xAux = uint256(x); result = 1; if (xAux >= 2 ** 128) { xAux >>= 128; result <<= 64; } if (xAux >= 2 ** 64) { xAux >>= 64; result <<= 32; } if (xAux >= 2 ** 32) { xAux >>= 32; result <<= 16; } if (xAux >= 2 ** 16) { xAux >>= 16; result <<= 8; } if (xAux >= 2 ** 8) { xAux >>= 8; result <<= 4; } if (xAux >= 2 ** 4) { xAux >>= 4; result <<= 2; } if (xAux >= 2 ** 2) { result <<= 1; } // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at // most 128 bits, since it is the square root of a uint256. Newton's method converges quadratically (precision // doubles at every iteration). We thus need at most 7 iteration to turn our partial result with one bit of // precision into the expected uint128 result. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // If x is not a perfect square, round the result toward zero. uint256 roundedResult = x / result; if (result >= roundedResult) { result = roundedResult; } } }
pragma solidity 0.8.19; // SPDX-License-Identifier: AGPL-3.0-or-later // Origami (common/oracle/OrigamiOracleBase.sol) import { IOrigamiOracle } from "contracts/interfaces/common/oracle/IOrigamiOracle.sol"; import { CommonEventsAndErrors } from "contracts/libraries/CommonEventsAndErrors.sol"; import { OrigamiMath } from "contracts/libraries/OrigamiMath.sol"; /** * @title OrigamiOracleBase * @notice Common base logic for Origami Oracle's */ abstract contract OrigamiOracleBase is IOrigamiOracle { using OrigamiMath for uint256; /** * @notice The address used to reference the baseAsset for amount conversions */ address public immutable override baseAsset; /** * @notice The address used to reference the quoteAsset for amount conversions */ address public immutable override quoteAsset; /** * @notice The number of decimals of precision the oracle price is returned as */ uint8 public constant override decimals = 18; /** * @notice The precision that the cross rate oracle price is returned as: `10^decimals` */ uint256 public constant override precision = 1e18; /** * @notice When converting from baseAsset<->quoteAsset, the fixed point amounts * need to be scaled by this amount. */ uint256 public immutable override assetScalingFactor; /** * @notice A human readable description for this origami oracle */ string public override description; constructor(BaseOracleParams memory params) { description = params.description; baseAsset = params.baseAssetAddress; quoteAsset = params.quoteAssetAddress; if (params.quoteAssetDecimals > decimals + params.baseAssetDecimals) revert CommonEventsAndErrors.InvalidParam(); assetScalingFactor = 10 ** (decimals + params.baseAssetDecimals - params.quoteAssetDecimals); } /** * @notice Return the latest oracle price, to `decimals` precision * @dev This may still revert - eg if deemed stale, div by 0, negative price * @param priceType What kind of price - Spot or Historic * @param roundingMode Round the price at each intermediate step such that the final price rounds in the specified direction. */ function latestPrice( PriceType priceType, OrigamiMath.Rounding roundingMode ) public virtual override view returns (uint256 price); /** * @notice Same as `latestPrice()` but for two separate prices from this oracle */ function latestPrices( PriceType priceType1, OrigamiMath.Rounding roundingMode1, PriceType priceType2, OrigamiMath.Rounding roundingMode2 ) external virtual override view returns ( uint256 /*price1*/, uint256 /*price2*/, address /*oracleBaseAsset*/, address /*oracleQuoteAsset*/ ) { return ( latestPrice(priceType1, roundingMode1), latestPrice(priceType2, roundingMode2), baseAsset, quoteAsset ); } /** * @notice Convert either the baseAsset->quoteAsset or quoteAsset->baseAsset * @dev The `fromAssetAmount` needs to be in it's natural fixed point precision (eg USDC=6dp) * The `toAssetAmount` will also be returned in it's natural fixed point precision */ function convertAmount( address fromAsset, uint256 fromAssetAmount, PriceType priceType, OrigamiMath.Rounding roundingMode ) external override view returns (uint256 toAssetAmount) { if (fromAsset == baseAsset) { // The numerator needs to round in the same way to be conservative uint256 _price = latestPrice( priceType, roundingMode ); return fromAssetAmount.mulDiv( _price, assetScalingFactor, roundingMode ); } else if (fromAsset == quoteAsset) { // The denominator needs to round in the opposite way to be conservative uint256 _price = latestPrice( priceType, roundingMode == OrigamiMath.Rounding.ROUND_UP ? OrigamiMath.Rounding.ROUND_DOWN : OrigamiMath.Rounding.ROUND_UP ); if (_price == 0) revert InvalidPrice(address(this), int256(_price)); return fromAssetAmount.mulDiv( assetScalingFactor, _price, roundingMode ); } revert CommonEventsAndErrors.InvalidToken(fromAsset); } /** * @notice Match whether a pair of assets match the base and quote asset on this oracle, in either order */ function matchAssets(address asset1, address asset2) public view returns (bool) { return ( (asset1 == baseAsset && asset2 == quoteAsset) || (asset2 == baseAsset && asset1 == quoteAsset) ); } }
pragma solidity 0.8.19; // SPDX-License-Identifier: AGPL-3.0-or-later // Origami (interfaces/common/oracle/IOrigamiOracle.sol) import { OrigamiMath } from "contracts/libraries/OrigamiMath.sol"; /** * @notice An oracle which returns prices for pairs of assets, where an asset * could refer to a token (eg DAI) or a currency (eg USD) * Convention is the same as the FX market. Given the DAI/USD pair: * - DAI = Base Asset (LHS of pair) * - USD = Quote Asset (RHS of pair) * This price defines how many USD you get if selling 1 DAI * * Further, an oracle can define two PriceType's: * - SPOT_PRICE: The latest spot price, for example from a chainlink oracle * - HISTORIC_PRICE: An expected (eg 1:1 peg) or calculated historic price (eg TWAP) * * For assets which do are not tokens (eg USD), an internal address reference will be used * since this is for internal purposes only */ interface IOrigamiOracle { error InvalidPrice(address oracle, int256 price); error InvalidOracleData(address oracle); error StalePrice(address oracle, uint256 lastUpdatedAt, int256 price); error UnknownPriceType(uint8 priceType); error BelowMinValidRange(address oracle, uint256 price, uint128 floor); error AboveMaxValidRange(address oracle, uint256 price, uint128 ceiling); event ValidPriceRangeSet(uint128 validFloor, uint128 validCeiling); enum PriceType { /// @notice The current spot price of this Oracle SPOT_PRICE, /// @notice The historic price of this Oracle. /// It may be a fixed expectation (eg DAI/USD would be fixed to 1) /// or use a TWAP or some other moving average, etc. HISTORIC_PRICE } /** * @dev Wrapped in a struct to remove stack-too-deep constraints */ struct BaseOracleParams { string description; address baseAssetAddress; uint8 baseAssetDecimals; address quoteAssetAddress; uint8 quoteAssetDecimals; } /** * @notice The address used to reference the baseAsset for amount conversions */ function baseAsset() external view returns (address); /** * @notice The address used to reference the quoteAsset for amount conversions */ function quoteAsset() external view returns (address); /** * @notice The number of decimals of precision the price is returned as */ function decimals() external view returns (uint8); /** * @notice The precision that the cross rate oracle price is returned as: `10^decimals` */ function precision() external view returns (uint256); /** * @notice When converting from baseAsset<->quoteAsset, the fixed point amounts * need to be scaled by this amount. */ function assetScalingFactor() external view returns (uint256); /** * @notice A human readable description for this oracle */ function description() external view returns (string memory); /** * @notice Return the latest oracle price, to `decimals` precision * @dev This may still revert - eg if deemed stale, div by 0, negative price * @param priceType What kind of price - Spot or Historic * @param roundingMode Round the price at each intermediate step such that the final price rounds in the specified direction. */ function latestPrice( PriceType priceType, OrigamiMath.Rounding roundingMode ) external view returns (uint256 price); /** * @notice Same as `latestPrice()` but for two separate prices from this oracle */ function latestPrices( PriceType priceType1, OrigamiMath.Rounding roundingMode1, PriceType priceType2, OrigamiMath.Rounding roundingMode2 ) external view returns ( uint256 price1, uint256 price2, address oracleBaseAsset, address oracleQuoteAsset ); /** * @notice Convert either the baseAsset->quoteAsset or quoteAsset->baseAsset * @dev The `fromAssetAmount` needs to be in it's natural fixed point precision (eg USDC=6dp) * The `toAssetAmount` will also be returned in it's natural fixed point precision */ function convertAmount( address fromAsset, uint256 fromAssetAmount, PriceType priceType, OrigamiMath.Rounding roundingMode ) external view returns (uint256 toAssetAmount); /** * @notice Match whether a pair of assets match the base and quote asset on this oracle, in either order */ function matchAssets(address asset1, address asset2) external view returns (bool); }
pragma solidity 0.8.19; // SPDX-License-Identifier: AGPL-3.0-or-later // Origami (libraries/CommonEventsAndErrors.sol) /// @notice A collection of common events and errors thrown within the Origami contracts library CommonEventsAndErrors { error InsufficientBalance(address token, uint256 required, uint256 balance); error InvalidToken(address token); error InvalidParam(); error InvalidAddress(address addr); error InvalidAmount(address token, uint256 amount); error ExpectedNonZero(); error Slippage(uint256 minAmountExpected, uint256 actualAmount); error IsPaused(); error UnknownExecuteError(bytes returndata); error InvalidAccess(); error BreachedMaxTotalSupply(uint256 totalSupply, uint256 maxTotalSupply); event TokenRecovered(address indexed to, address indexed token, uint256 amount); }
pragma solidity 0.8.19; // SPDX-License-Identifier: AGPL-3.0-or-later // Origami (libraries/OrigamiMath.sol) import { mulDiv as prbMulDiv, PRBMath_MulDiv_Overflow } from "@prb/math/src/Common.sol"; import { CommonEventsAndErrors } from "contracts/libraries/CommonEventsAndErrors.sol"; /** * @notice Utilities to operate on fixed point math multipliation and division * taking rounding into consideration */ library OrigamiMath { enum Rounding { ROUND_DOWN, ROUND_UP } uint256 public constant BASIS_POINTS_DIVISOR = 10_000; function scaleUp(uint256 amount, uint256 scalar) internal pure returns (uint256) { // Special case for scalar == 1, as it's common for token amounts to not need // scaling if decimal places are the same return scalar == 1 ? amount : amount * scalar; } function scaleDown( uint256 amount, uint256 scalar, Rounding roundingMode ) internal pure returns (uint256 result) { // Special case for scalar == 1, as it's common for token amounts to not need // scaling if decimal places are the same unchecked { if (scalar == 1) { result = amount; } else if (roundingMode == Rounding.ROUND_DOWN) { result = amount / scalar; } else { // ROUND_UP uses the same logic as OZ Math.ceilDiv() result = amount == 0 ? 0 : (amount - 1) / scalar + 1; } } } /** * @notice Calculates x * y / denominator with full precision, * rounding up */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding roundingMode ) internal pure returns (uint256 result) { result = prbMulDiv(x, y, denominator); if (roundingMode == Rounding.ROUND_UP) { if (mulmod(x, y, denominator) != 0) { if (result < type(uint256).max) { unchecked { result = result + 1; } } else { revert PRBMath_MulDiv_Overflow(x, y, denominator); } } } } function subtractBps( uint256 inputAmount, uint256 basisPoints, Rounding roundingMode ) internal pure returns (uint256 result) { uint256 numeratorBps; unchecked { numeratorBps = BASIS_POINTS_DIVISOR - basisPoints; } result = basisPoints < BASIS_POINTS_DIVISOR ? mulDiv( inputAmount, numeratorBps, BASIS_POINTS_DIVISOR, roundingMode ) : 0; } function addBps( uint256 inputAmount, uint256 basisPoints, Rounding roundingMode ) internal pure returns (uint256 result) { uint256 numeratorBps; unchecked { numeratorBps = BASIS_POINTS_DIVISOR + basisPoints; } // Round up for max amounts out expected result = mulDiv( inputAmount, numeratorBps, BASIS_POINTS_DIVISOR, roundingMode ); } /** * @notice Split the `inputAmount` into two parts based on the `basisPoints` fraction. * eg: 3333 BPS (33.3%) can be used to split an input amount of 600 into: (result=400, removed=200). * @dev The rounding mode is applied to the `result` */ function splitSubtractBps( uint256 inputAmount, uint256 basisPoints, Rounding roundingMode ) internal pure returns (uint256 result, uint256 removed) { result = subtractBps(inputAmount, basisPoints, roundingMode); unchecked { removed = inputAmount - result; } } /** * @notice Reverse the fractional amount of an input. * eg: For 3333 BPS (33.3%) and the remainder=400, the result is 600 */ function inverseSubtractBps( uint256 remainderAmount, uint256 basisPoints, Rounding roundingMode ) internal pure returns (uint256 result) { if (basisPoints == 0) return remainderAmount; // gas shortcut for 0 if (basisPoints >= BASIS_POINTS_DIVISOR) revert CommonEventsAndErrors.InvalidParam(); uint256 denominatorBps; unchecked { denominatorBps = BASIS_POINTS_DIVISOR - basisPoints; } result = mulDiv( remainderAmount, BASIS_POINTS_DIVISOR, denominatorBps, roundingMode ); } /** * @notice Calculate the relative difference of a value to a reference * @dev `value` and `referenceValue` must have the same precision * The denominator is always the referenceValue */ function relativeDifferenceBps( uint256 value, uint256 referenceValue, Rounding roundingMode ) internal pure returns (uint256) { if (referenceValue == 0) revert CommonEventsAndErrors.InvalidParam(); uint256 absDelta; unchecked { absDelta = value < referenceValue ? referenceValue - value : value - referenceValue; } return mulDiv( absDelta, BASIS_POINTS_DIVISOR, referenceValue, roundingMode ); } }
{ "optimizer": { "enabled": true, "runs": 10000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"components":[{"internalType":"string","name":"description","type":"string"},{"internalType":"address","name":"baseAssetAddress","type":"address"},{"internalType":"uint8","name":"baseAssetDecimals","type":"uint8"},{"internalType":"address","name":"quoteAssetAddress","type":"address"},{"internalType":"uint8","name":"quoteAssetDecimals","type":"uint8"}],"internalType":"struct IOrigamiOracle.BaseOracleParams","name":"baseParams","type":"tuple"},{"internalType":"address","name":"_pendleOracle","type":"address"},{"internalType":"address","name":"_pendleMarket","type":"address"},{"internalType":"uint32","name":"_twapDuration","type":"uint32"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint128","name":"ceiling","type":"uint128"}],"name":"AboveMaxValidRange","type":"error"},{"inputs":[{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"price","type":"uint256"},{"internalType":"uint128","name":"floor","type":"uint128"}],"name":"BelowMinValidRange","type":"error"},{"inputs":[{"internalType":"address","name":"oracle","type":"address"}],"name":"InvalidOracleData","type":"error"},{"inputs":[],"name":"InvalidParam","type":"error"},{"inputs":[{"internalType":"address","name":"oracle","type":"address"},{"internalType":"int256","name":"price","type":"int256"}],"name":"InvalidPrice","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"InvalidToken","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"lastUpdatedAt","type":"uint256"},{"internalType":"int256","name":"price","type":"int256"}],"name":"StalePrice","type":"error"},{"inputs":[],"name":"UninitializedPendleOracle","type":"error"},{"inputs":[{"internalType":"uint8","name":"priceType","type":"uint8"}],"name":"UnknownPriceType","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint128","name":"validFloor","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"validCeiling","type":"uint128"}],"name":"ValidPriceRangeSet","type":"event"},{"inputs":[],"name":"assetScalingFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"baseAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"fromAsset","type":"address"},{"internalType":"uint256","name":"fromAssetAmount","type":"uint256"},{"internalType":"enum IOrigamiOracle.PriceType","name":"priceType","type":"uint8"},{"internalType":"enum OrigamiMath.Rounding","name":"roundingMode","type":"uint8"}],"name":"convertAmount","outputs":[{"internalType":"uint256","name":"toAssetAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum IOrigamiOracle.PriceType","name":"","type":"uint8"},{"internalType":"enum OrigamiMath.Rounding","name":"","type":"uint8"}],"name":"latestPrice","outputs":[{"internalType":"uint256","name":"price","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum IOrigamiOracle.PriceType","name":"priceType1","type":"uint8"},{"internalType":"enum OrigamiMath.Rounding","name":"roundingMode1","type":"uint8"},{"internalType":"enum IOrigamiOracle.PriceType","name":"priceType2","type":"uint8"},{"internalType":"enum OrigamiMath.Rounding","name":"roundingMode2","type":"uint8"}],"name":"latestPrices","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"asset1","type":"address"},{"internalType":"address","name":"asset2","type":"address"}],"name":"matchAssets","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendleMarket","outputs":[{"internalType":"contract IPMarket","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"precision","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"quoteAsset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"twapDuration","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
6101206040523480156200001257600080fd5b506040516200217d3803806200217d833981016040819052620000359162000255565b835184906000906200004890826200044b565b5060208101516001600160a01b0390811660805260608201511660a0526040810151620000779060126200052d565b60ff16816080015160ff161115620000a257604051633494a40d60e21b815260040160405180910390fd5b60808101516040820151620000b99060126200052d565b620000c591906200054f565b620000d290600a62000668565b60c052506001600160a01b0382811660e081905263ffffffff831661010081905260405162439f4b60e91b81526004810192909252602482015260009182919086169063873e960090604401606060405180830381865afa1580156200013c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000162919062000691565b9250509150818062000172575080155b156200019157604051636efece6560e01b815260040160405180910390fd5b505050505050620006e3565b634e487b7160e01b600052604160045260246000fd5b60405160a081016001600160401b0381118282101715620001d857620001d86200019d565b60405290565b604051601f8201601f191681016001600160401b03811182821017156200020957620002096200019d565b604052919050565b80516001600160a01b03811681146200022957600080fd5b919050565b805160ff811681146200022957600080fd5b805163ffffffff811681146200022957600080fd5b600080600080608085870312156200026c57600080fd5b84516001600160401b03808211156200028457600080fd5b9086019060a082890312156200029957600080fd5b620002a3620001b3565b825182811115620002b357600080fd5b8301601f81018a13620002c557600080fd5b805183811115620002da57620002da6200019d565b60209350620002f2601f8201601f19168501620001de565b8181528b858385010111156200030757600080fd5b60005b82811015620003275783810186015182820187015285016200030a565b5060008583830101528084525050506200034382840162000211565b8282015262000355604084016200022e565b6040820152620003686060840162000211565b60608201526200037b608084016200022e565b608082015295506200038f87820162000211565b94505050620003a16040860162000211565b9150620003b16060860162000240565b905092959194509250565b600181811c90821680620003d157607f821691505b602082108103620003f257634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156200044657600081815260208120601f850160051c81016020861015620004215750805b601f850160051c820191505b8181101562000442578281556001016200042d565b5050505b505050565b81516001600160401b038111156200046757620004676200019d565b6200047f81620004788454620003bc565b84620003f8565b602080601f831160018114620004b757600084156200049e5750858301515b600019600386901b1c1916600185901b17855562000442565b600085815260208120601f198616915b82811015620004e857888601518255948401946001909101908401620004c7565b5085821015620005075787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b600052601160045260246000fd5b60ff818116838216019081111562000549576200054962000517565b92915050565b60ff828116828216039081111562000549576200054962000517565b600181815b80851115620005ac57816000190482111562000590576200059062000517565b808516156200059e57918102915b93841c939080029062000570565b509250929050565b600082620005c55750600162000549565b81620005d45750600062000549565b8160018114620005ed5760028114620005f85762000618565b600191505062000549565b60ff8411156200060c576200060c62000517565b50506001821b62000549565b5060208310610133831016604e8410600b84101617156200063d575081810a62000549565b6200064983836200056b565b806000190482111562000660576200066062000517565b029392505050565b60006200067960ff841683620005b4565b9392505050565b805180151581146200022957600080fd5b600080600060608486031215620006a757600080fd5b620006b28462000680565b9250602084015161ffff81168114620006ca57600080fd5b9150620006da6040850162000680565b90509250925092565b60805160a05160c05160e05161010051611a026200077b6000396000818160de015261073401526000818161020801526107120152600081816101be01528181610424015261052101526000818161029d0152818161030301528181610453015281816105f3015261069f015260008181610267015281816102e0015281816103be0152818161059d01526106490152611a026000f3fe608060405234801561001057600080fd5b50600436106100d45760003560e01c80639502128011610081578063cdf456e11161005b578063cdf456e114610262578063d3b5dc3b14610289578063fdf262b71461029857600080fd5b806395021280146101e057806399d9a71f14610203578063c6845a091461024f57600080fd5b80637284e416116100b25780637284e416146101835780637349615f146101985780638fc5e88d146101b957600080fd5b806326d89545146100d9578063313ce5671461011a5780636999451114610134575b600080fd5b6101007f000000000000000000000000000000000000000000000000000000000000000081565b60405163ffffffff90911681526020015b60405180910390f35b610122601281565b60405160ff9091168152602001610111565b610147610142366004611442565b6102bf565b60408051948552602085019390935273ffffffffffffffffffffffffffffffffffffffff91821692840192909252166060820152608001610111565b61018b61032c565b604051610111919061149e565b6101ab6101a636600461152c565b6103ba565b604051908152602001610111565b6101ab7f000000000000000000000000000000000000000000000000000000000000000081565b6101f36101ee366004611564565b610599565b6040519015158152602001610111565b61022a7f000000000000000000000000000000000000000000000000000000000000000081565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610111565b6101ab61025d36600461159d565b6106f6565b61022a7f000000000000000000000000000000000000000000000000000000000000000081565b6101ab670de0b6b3a764000081565b61022a7f000000000000000000000000000000000000000000000000000000000000000081565b6000806000806102cf88886106f6565b6102d987876106f6565b90999098507f000000000000000000000000000000000000000000000000000000000000000097507f00000000000000000000000000000000000000000000000000000000000000009650945050505050565b60008054610339906115cb565b80601f0160208091040260200160405190810160405280929190818152602001828054610365906115cb565b80156103b25780601f10610387576101008083540402835291602001916103b2565b820191906000526020600020905b81548152906001019060200180831161039557829003601f168201915b505050505081565b60007f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff160361045157600061041b84846106f6565b905061044985827f000000000000000000000000000000000000000000000000000000000000000086610758565b915050610591565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16036105475760006104d18460018560018111156104be576104be61161e565b146104ca5760016106f6565b60006106f6565b90508060000361051b576040517fdcd07d4f000000000000000000000000000000000000000000000000000000008152306004820152602481018290526044015b60405180910390fd5b610449857f00000000000000000000000000000000000000000000000000000000000000008386610758565b6040517f961c9a4f00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff86166004820152602401610512565b949350505050565b60007f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614801561064157507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16145b806106ed57507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161480156106ed57507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b90505b92915050565b60006106ed73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000167f0000000000000000000000000000000000000000000000000000000000000000610809565b6000610765858585610855565b9050600182600181111561077b5761077b61161e565b0361059157828061078e5761078e61164d565b84860915610591577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156107c657600101610591565b6040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018690526024810185905260448101849052606401610512565b600080600061081785610966565b915091508082106108355761082c8585610be0565b925050506106f0565b80826108418787610be0565b61084b91906116ab565b61082c91906116c2565b600080807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff858709858702925082811083820303915050806000036108ad578382816108a3576108a361164d565b049250505061095f565b8381106108f7576040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606401610512565b600084868809851960019081018716968790049682860381900495909211909303600082900391909104909201919091029190911760038402600290811880860282030280860282030280860282030280860282030280860282030280860290910302029150505b9392505050565b6000806000808473ffffffffffffffffffffffffffffffffffffffff16632c8ce6bc6040518163ffffffff1660e01b8152600401606060405180830381865afa1580156109b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109db91906116d6565b92505091508173ffffffffffffffffffffffffffffffffffffffff16633ba0b9a96040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a2b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a4f9190611723565b935060008173ffffffffffffffffffffffffffffffffffffffff1663d2a3584e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a9e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ac29190611723565b90508173ffffffffffffffffffffffffffffffffffffffff1663516399df6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b0f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b33919061173c565b8015610bbe5750438273ffffffffffffffffffffffffffffffffffffffff166360e0a9e16040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610baa919061175e565b6fffffffffffffffffffffffffffffffff16145b15610bcb57809350610bd8565b610bd58582610cc2565b93505b505050915091565b6000808373ffffffffffffffffffffffffffffffffffffffff1663e184c9be6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c529190611723565b9050428111610c6c57670de0b6b3a76400009150506106f0565b6000610c788585610cd8565b90506000610c864284611790565b90506000610c9c610c978484610e57565b610e90565b9050610cb0670de0b6b3a764000082610ea3565b9450505050506106f0565b5092915050565b6000818311610cd157816106ed565b5090919050565b604080516002808252606082018352600092839291906020830190803683370190505090508281600081518110610d1157610d116117d2565b63ffffffff909216602092830291909101909101526040517f883bdbfd00000000000000000000000000000000000000000000000000000000815260009073ffffffffffffffffffffffffffffffffffffffff86169063883bdbfd90610d7b908590600401611801565b600060405180830381865afa158015610d98573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201604052610dde919081019061187b565b90508363ffffffff1681600081518110610dfa57610dfa6117d2565b602002602001015182600181518110610e1557610e156117d2565b6020026020010151610e27919061195e565b610e319190611992565b7affffffffffffffffffffffffffffffffffffffffffffffffffffff1695945050505050565b600080610e696201518061016d6116ab565b610e7384866116ab565b610e7d91906116c2565b9050610591610e8b82610ed2565b610f01565b600080821215610e9f57600080fd5b5090565b600080610eb8670de0b6b3a7640000856116ab565b9050828181610ec957610ec961164d565b04949350505050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff821115610e9f57600080fd5b60007ffffffffffffffffffffffffffffffffffffffffffffffffdc702bd3a30fc00008212158015610f3c575068070c1cc73b00c800008213155b610fa2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c6964206578706f6e656e74000000000000000000000000000000006044820152606401610512565b6000821215610fdb57610fb782600003610f01565b6ec097ce7bc90715b34b9f100000000081610fd457610fd461164d565b0592915050565b60006806f05b59d3b2000000831261103157507ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e00000090910190770195e54c5dd42177f53a27172fa9ec63026282700000000061107d565b6803782dace9d9000000831261107957507ffffffffffffffffffffffffffffffffffffffffffffffffc87d2531627000000909101906b1425982cf597cd205cef738061107d565b5060015b6064929092029168056bc75e2d6310000068ad78ebc5ac6200000084126110e3577fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e0000009093019268056bc75e2d631000006e01855144814a7ff805980ff008400082020590505b6856bc75e2d6310000008412611135577fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf0000009093019268056bc75e2d631000006b02df0ab5a80a22c61ab5a70082020590505b682b5e3af16b188000008412611185577fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e78000009093019268056bc75e2d63100000693f1fce3da636ea5cf85082020590505b6815af1d78b58c40000084126111d5577fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000009093019268056bc75e2d63100000690127fa27722cc06cc5e282020590505b680ad78ebc5ac62000008412611224577ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000009093019268056bc75e2d6310000068280e60114edb805d0382020590505b68056bc75e2d631000008412611273577ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000009093019268056bc75e2d63100000680ebc5fb4174612111082020590505b6802b5e3af16b188000084126112c2577ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800009093019268056bc75e2d631000006808f00f760a4b2db55d82020590505b68015af1d78b58c400008412611311577ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00009093019268056bc75e2d631000006806f5f177578893793782020590505b68056bc75e2d631000008481019085906002908280020505918201919050600368056bc75e2d631000008783020505918201919050600468056bc75e2d631000008783020505918201919050600568056bc75e2d631000008783020505918201919050600668056bc75e2d631000008783020505918201919050600768056bc75e2d631000008783020505918201919050600868056bc75e2d631000008783020505918201919050600968056bc75e2d631000008783020505918201919050600a68056bc75e2d631000008783020505918201919050600b68056bc75e2d631000008783020505918201919050600c68056bc75e2d631000008783020505918201919050606468056bc75e2d63100000848402058502059695505050505050565b6002811061143f57600080fd5b50565b6000806000806080858703121561145857600080fd5b843561146381611432565b9350602085013561147381611432565b9250604085013561148381611432565b9150606085013561149381611432565b939692955090935050565b600060208083528351808285015260005b818110156114cb578581018301518582016040015282016114af565b5060006040828601015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8301168501019250505092915050565b73ffffffffffffffffffffffffffffffffffffffff8116811461143f57600080fd5b6000806000806080858703121561154257600080fd5b843561154d8161150a565b935060208501359250604085013561148381611432565b6000806040838503121561157757600080fd5b82356115828161150a565b915060208301356115928161150a565b809150509250929050565b600080604083850312156115b057600080fd5b82356115bb81611432565b9150602083013561159281611432565b600181811c908216806115df57607f821691505b602082108103611618577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b80820281158282048414176106f0576106f061167c565b6000826116d1576116d161164d565b500490565b6000806000606084860312156116eb57600080fd5b83516116f68161150a565b60208501519093506117078161150a565b60408501519092506117188161150a565b809150509250925092565b60006020828403121561173557600080fd5b5051919050565b60006020828403121561174e57600080fd5b8151801515811461095f57600080fd5b60006020828403121561177057600080fd5b81516fffffffffffffffffffffffffffffffff8116811461095f57600080fd5b818103818111156106f0576106f061167c565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b6020808252825182820181905260009190848201906040850190845b8181101561183f57835163ffffffff168352928401929184019160010161181d565b50909695505050505050565b80517affffffffffffffffffffffffffffffffffffffffffffffffffffff8116811461187657600080fd5b919050565b6000602080838503121561188e57600080fd5b825167ffffffffffffffff808211156118a657600080fd5b818501915085601f8301126118ba57600080fd5b8151818111156118cc576118cc6117a3565b8060051b6040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0603f8301168101818110858211171561190f5761190f6117a3565b60405291825284820192508381018501918883111561192d57600080fd5b938501935b82851015611952576119438561184b565b84529385019392850192611932565b98975050505050505050565b7affffffffffffffffffffffffffffffffffffffffffffffffffffff828116828216039080821115610cbb57610cbb61167c565b60007affffffffffffffffffffffffffffffffffffffffffffffffffffff808416806119c0576119c061164d565b9216919091049291505056fea2646970667358221220b41418860cad90e67931260adee5942dc445cd823a0f72e8ba9e820049c09a9d64736f6c6343000813003300000000000000000000000000000000000000000000000000000000000000800000000000000000000000009a9fa8338dd5e5b2188006f1cd2ef26d921650c2000000000000000000000000cdd26eb5eb2ce0f203a84553853667ae69ca29ce0000000000000000000000000000000000000000000000000000000000000e1000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8100000000000000000000000000000000000000000000000000000000000000120000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b30000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001550542d73555344652d4d6172323032352f555344650000000000000000000000
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106100d45760003560e01c80639502128011610081578063cdf456e11161005b578063cdf456e114610262578063d3b5dc3b14610289578063fdf262b71461029857600080fd5b806395021280146101e057806399d9a71f14610203578063c6845a091461024f57600080fd5b80637284e416116100b25780637284e416146101835780637349615f146101985780638fc5e88d146101b957600080fd5b806326d89545146100d9578063313ce5671461011a5780636999451114610134575b600080fd5b6101007f0000000000000000000000000000000000000000000000000000000000000e1081565b60405163ffffffff90911681526020015b60405180910390f35b610122601281565b60405160ff9091168152602001610111565b610147610142366004611442565b6102bf565b60408051948552602085019390935273ffffffffffffffffffffffffffffffffffffffff91821692840192909252166060820152608001610111565b61018b61032c565b604051610111919061149e565b6101ab6101a636600461152c565b6103ba565b604051908152602001610111565b6101ab7f0000000000000000000000000000000000000000000000000de0b6b3a764000081565b6101f36101ee366004611564565b610599565b6040519015158152602001610111565b61022a7f000000000000000000000000cdd26eb5eb2ce0f203a84553853667ae69ca29ce81565b60405173ffffffffffffffffffffffffffffffffffffffff9091168152602001610111565b6101ab61025d36600461159d565b6106f6565b61022a7f000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8181565b6101ab670de0b6b3a764000081565b61022a7f0000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b381565b6000806000806102cf88886106f6565b6102d987876106f6565b90999098507f000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8197507f0000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b39650945050505050565b60008054610339906115cb565b80601f0160208091040260200160405190810160405280929190818152602001828054610365906115cb565b80156103b25780601f10610387576101008083540402835291602001916103b2565b820191906000526020600020905b81548152906001019060200180831161039557829003601f168201915b505050505081565b60007f000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8173ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff160361045157600061041b84846106f6565b905061044985827f0000000000000000000000000000000000000000000000000de0b6b3a764000086610758565b915050610591565b7f0000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16036105475760006104d18460018560018111156104be576104be61161e565b146104ca5760016106f6565b60006106f6565b90508060000361051b576040517fdcd07d4f000000000000000000000000000000000000000000000000000000008152306004820152602481018290526044015b60405180910390fd5b610449857f0000000000000000000000000000000000000000000000000de0b6b3a76400008386610758565b6040517f961c9a4f00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff86166004820152602401610512565b949350505050565b60007f000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614801561064157507f0000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b373ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16145b806106ed57507f000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8173ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161480156106ed57507f0000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b373ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b90505b92915050565b60006106ed73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000cdd26eb5eb2ce0f203a84553853667ae69ca29ce167f0000000000000000000000000000000000000000000000000000000000000e10610809565b6000610765858585610855565b9050600182600181111561077b5761077b61161e565b0361059157828061078e5761078e61164d565b84860915610591577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156107c657600101610591565b6040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018690526024810185905260448101849052606401610512565b600080600061081785610966565b915091508082106108355761082c8585610be0565b925050506106f0565b80826108418787610be0565b61084b91906116ab565b61082c91906116c2565b600080807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff858709858702925082811083820303915050806000036108ad578382816108a3576108a361164d565b049250505061095f565b8381106108f7576040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606401610512565b600084868809851960019081018716968790049682860381900495909211909303600082900391909104909201919091029190911760038402600290811880860282030280860282030280860282030280860282030280860282030280860290910302029150505b9392505050565b6000806000808473ffffffffffffffffffffffffffffffffffffffff16632c8ce6bc6040518163ffffffff1660e01b8152600401606060405180830381865afa1580156109b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109db91906116d6565b92505091508173ffffffffffffffffffffffffffffffffffffffff16633ba0b9a96040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a2b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a4f9190611723565b935060008173ffffffffffffffffffffffffffffffffffffffff1663d2a3584e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a9e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ac29190611723565b90508173ffffffffffffffffffffffffffffffffffffffff1663516399df6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b0f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b33919061173c565b8015610bbe5750438273ffffffffffffffffffffffffffffffffffffffff166360e0a9e16040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b86573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610baa919061175e565b6fffffffffffffffffffffffffffffffff16145b15610bcb57809350610bd8565b610bd58582610cc2565b93505b505050915091565b6000808373ffffffffffffffffffffffffffffffffffffffff1663e184c9be6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c529190611723565b9050428111610c6c57670de0b6b3a76400009150506106f0565b6000610c788585610cd8565b90506000610c864284611790565b90506000610c9c610c978484610e57565b610e90565b9050610cb0670de0b6b3a764000082610ea3565b9450505050506106f0565b5092915050565b6000818311610cd157816106ed565b5090919050565b604080516002808252606082018352600092839291906020830190803683370190505090508281600081518110610d1157610d116117d2565b63ffffffff909216602092830291909101909101526040517f883bdbfd00000000000000000000000000000000000000000000000000000000815260009073ffffffffffffffffffffffffffffffffffffffff86169063883bdbfd90610d7b908590600401611801565b600060405180830381865afa158015610d98573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201604052610dde919081019061187b565b90508363ffffffff1681600081518110610dfa57610dfa6117d2565b602002602001015182600181518110610e1557610e156117d2565b6020026020010151610e27919061195e565b610e319190611992565b7affffffffffffffffffffffffffffffffffffffffffffffffffffff1695945050505050565b600080610e696201518061016d6116ab565b610e7384866116ab565b610e7d91906116c2565b9050610591610e8b82610ed2565b610f01565b600080821215610e9f57600080fd5b5090565b600080610eb8670de0b6b3a7640000856116ab565b9050828181610ec957610ec961164d565b04949350505050565b60007f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff821115610e9f57600080fd5b60007ffffffffffffffffffffffffffffffffffffffffffffffffdc702bd3a30fc00008212158015610f3c575068070c1cc73b00c800008213155b610fa2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c6964206578706f6e656e74000000000000000000000000000000006044820152606401610512565b6000821215610fdb57610fb782600003610f01565b6ec097ce7bc90715b34b9f100000000081610fd457610fd461164d565b0592915050565b60006806f05b59d3b2000000831261103157507ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e00000090910190770195e54c5dd42177f53a27172fa9ec63026282700000000061107d565b6803782dace9d9000000831261107957507ffffffffffffffffffffffffffffffffffffffffffffffffc87d2531627000000909101906b1425982cf597cd205cef738061107d565b5060015b6064929092029168056bc75e2d6310000068ad78ebc5ac6200000084126110e3577fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e0000009093019268056bc75e2d631000006e01855144814a7ff805980ff008400082020590505b6856bc75e2d6310000008412611135577fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf0000009093019268056bc75e2d631000006b02df0ab5a80a22c61ab5a70082020590505b682b5e3af16b188000008412611185577fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e78000009093019268056bc75e2d63100000693f1fce3da636ea5cf85082020590505b6815af1d78b58c40000084126111d5577fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000009093019268056bc75e2d63100000690127fa27722cc06cc5e282020590505b680ad78ebc5ac62000008412611224577ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000009093019268056bc75e2d6310000068280e60114edb805d0382020590505b68056bc75e2d631000008412611273577ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000009093019268056bc75e2d63100000680ebc5fb4174612111082020590505b6802b5e3af16b188000084126112c2577ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800009093019268056bc75e2d631000006808f00f760a4b2db55d82020590505b68015af1d78b58c400008412611311577ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00009093019268056bc75e2d631000006806f5f177578893793782020590505b68056bc75e2d631000008481019085906002908280020505918201919050600368056bc75e2d631000008783020505918201919050600468056bc75e2d631000008783020505918201919050600568056bc75e2d631000008783020505918201919050600668056bc75e2d631000008783020505918201919050600768056bc75e2d631000008783020505918201919050600868056bc75e2d631000008783020505918201919050600968056bc75e2d631000008783020505918201919050600a68056bc75e2d631000008783020505918201919050600b68056bc75e2d631000008783020505918201919050600c68056bc75e2d631000008783020505918201919050606468056bc75e2d63100000848402058502059695505050505050565b6002811061143f57600080fd5b50565b6000806000806080858703121561145857600080fd5b843561146381611432565b9350602085013561147381611432565b9250604085013561148381611432565b9150606085013561149381611432565b939692955090935050565b600060208083528351808285015260005b818110156114cb578581018301518582016040015282016114af565b5060006040828601015260407fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8301168501019250505092915050565b73ffffffffffffffffffffffffffffffffffffffff8116811461143f57600080fd5b6000806000806080858703121561154257600080fd5b843561154d8161150a565b935060208501359250604085013561148381611432565b6000806040838503121561157757600080fd5b82356115828161150a565b915060208301356115928161150a565b809150509250929050565b600080604083850312156115b057600080fd5b82356115bb81611432565b9150602083013561159281611432565b600181811c908216806115df57607f821691505b602082108103611618577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b80820281158282048414176106f0576106f061167c565b6000826116d1576116d161164d565b500490565b6000806000606084860312156116eb57600080fd5b83516116f68161150a565b60208501519093506117078161150a565b60408501519092506117188161150a565b809150509250925092565b60006020828403121561173557600080fd5b5051919050565b60006020828403121561174e57600080fd5b8151801515811461095f57600080fd5b60006020828403121561177057600080fd5b81516fffffffffffffffffffffffffffffffff8116811461095f57600080fd5b818103818111156106f0576106f061167c565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b6020808252825182820181905260009190848201906040850190845b8181101561183f57835163ffffffff168352928401929184019160010161181d565b50909695505050505050565b80517affffffffffffffffffffffffffffffffffffffffffffffffffffff8116811461187657600080fd5b919050565b6000602080838503121561188e57600080fd5b825167ffffffffffffffff808211156118a657600080fd5b818501915085601f8301126118ba57600080fd5b8151818111156118cc576118cc6117a3565b8060051b6040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0603f8301168101818110858211171561190f5761190f6117a3565b60405291825284820192508381018501918883111561192d57600080fd5b938501935b82851015611952576119438561184b565b84529385019392850192611932565b98975050505050505050565b7affffffffffffffffffffffffffffffffffffffffffffffffffffff828116828216039080821115610cbb57610cbb61167c565b60007affffffffffffffffffffffffffffffffffffffffffffffffffffff808416806119c0576119c061164d565b9216919091049291505056fea2646970667358221220b41418860cad90e67931260adee5942dc445cd823a0f72e8ba9e820049c09a9d64736f6c63430008130033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000000000000000000000000000000000000000000800000000000000000000000009a9fa8338dd5e5b2188006f1cd2ef26d921650c2000000000000000000000000cdd26eb5eb2ce0f203a84553853667ae69ca29ce0000000000000000000000000000000000000000000000000000000000000e1000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b8100000000000000000000000000000000000000000000000000000000000000120000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b30000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000001550542d73555344652d4d6172323032352f555344650000000000000000000000
-----Decoded View---------------
Arg [0] : baseParams (tuple): System.Collections.Generic.List`1[Nethereum.ABI.FunctionEncoding.ParameterOutput]
Arg [1] : _pendleOracle (address): 0x9a9Fa8338dd5E5B2188006f1Cd2Ef26d921650C2
Arg [2] : _pendleMarket (address): 0xcDd26Eb5EB2Ce0f203a84553853667aE69Ca29Ce
Arg [3] : _twapDuration (uint32): 3600
-----Encoded View---------------
11 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000080
Arg [1] : 0000000000000000000000009a9fa8338dd5e5b2188006f1cd2ef26d921650c2
Arg [2] : 000000000000000000000000cdd26eb5eb2ce0f203a84553853667ae69ca29ce
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000e10
Arg [4] : 00000000000000000000000000000000000000000000000000000000000000a0
Arg [5] : 000000000000000000000000e00bd3df25fb187d6abbb620b3dfd19839947b81
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [7] : 0000000000000000000000004c9edd5852cd905f086c759e8383e09bff1e68b3
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000015
Arg [10] : 50542d73555344652d4d6172323032352f555344650000000000000000000000
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
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.