MNT Price: $0.73 (+2.60%)

Contract

0xC6AE150de14e17e6F444c8464B248d6D17D2cDad
 

Overview

MNT Balance

Mantle Mainnet Network LogoMantle Mainnet Network LogoMantle Mainnet Network Logo0 MNT

MNT Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PendleLimitRouter

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 1000000 runs

Other Settings:
shanghai EvmVersion
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import "./LimitRouterBase.sol";
import "../core/libraries/Errors.sol";

contract PendleLimitRouter is LimitRouterBase {
    using Address for address;

    constructor(address _WNATIVE) LimitRouterBase(_WNATIVE) {
        _disableInitializers();
    }

    /// @notice Cancels multiple orders by setting remaining amount to zero
    function cancelBatch(Order[] calldata orders) external {
        for (uint256 i = 0; i < orders.length; ++i) {
            cancelSingle(orders[i]);
        }
    }

    /// @notice Cancels order by setting remaining amount to zero
    function cancelSingle(Order calldata order) public {
        require(order.maker == msg.sender, "LOP: Access denied");

        bytes32 orderHash = hashOrder(order);
        require(_status[orderHash].remaining != _ORDER_FILLED, "LOP: already filled");
        _status[orderHash].remaining = _ORDER_FILLED;

        emit OrderCanceled(msg.sender, orderHash);
    }

    /// @dev auto skip cancelled orders to avoid race conditions
    function forceCancel(bytes32[] calldata orderHashes) public onlyHelperAndOwner {
        for (uint256 i = 0; i < orderHashes.length; ++i) {
            if (_status[orderHashes[i]].remaining == _ORDER_FILLED) continue;

            _status[orderHashes[i]].remaining = _ORDER_FILLED;
            emit OrderForceCanceled(orderHashes[i]);
        }
    }

    function orderStatusesRaw(
        bytes32[] memory orderHashes
    ) public view returns (uint256[] memory remainingsRaw, uint256[] memory filledAmounts) {
        uint256 len = orderHashes.length;
        remainingsRaw = new uint256[](len);
        filledAmounts = new uint256[](len);

        for (uint256 i = 0; i < len; i++) {
            OrderStatus memory status = _status[orderHashes[i]];
            (remainingsRaw[i], filledAmounts[i]) = (status.remaining, status.filledAmount);
        }
    }

    function orderStatuses(
        bytes32[] memory orderHashes
    ) external view returns (uint256[] memory remainings, uint256[] memory filledAmounts) {
        (remainings, filledAmounts) = orderStatusesRaw(orderHashes);
        for (uint256 i = 0; i < remainings.length; i++) {
            require(remainings[i] != _ORDER_DOES_NOT_EXIST, "LOP: Unknown order");
            unchecked {
                remainings[i] -= 1;
            }
        }
    }

    function DOMAIN_SEPARATOR() external view returns (bytes32) {
        return _domainSeparatorV4();
    }

    function simulate(address target, bytes calldata data) external payable {
        (bool success, bytes memory result) = target.delegatecall(data);
        revert Errors.SimulationResults(success, result);
    }
}

File 2 of 41 : IERC5267Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.0;

interface IERC5267Upgradeable {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

// 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);
        }
    }
}

File 5 of 41 : draft-EIP712Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

// EIP-712 is Final as of 2022-08-11. This file is deprecated.

import "./EIP712Upgradeable.sol";

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../StringsUpgradeable.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSAUpgradeable {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.8;

import "./ECDSAUpgradeable.sol";
import "../../interfaces/IERC5267Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * _Available since v3.4._
 *
 * @custom:storage-size 52
 */
abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable {
    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    /// @custom:oz-renamed-from _HASHED_NAME
    bytes32 private _hashedName;
    /// @custom:oz-renamed-from _HASHED_VERSION
    bytes32 private _hashedVersion;

    string private _name;
    string private _version;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
        __EIP712_init_unchained(name, version);
    }

    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
        _name = name;
        _version = version;

        // Reset prior values in storage if upgrading
        _hashedName = 0;
        _hashedVersion = 0;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        return _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {EIP-5267}.
     *
     * _Available since v4.9._
     */
    function eip712Domain()
        public
        view
        virtual
        override
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
        // and the EIP712 domain is not reliable, as it will be missing name and version.
        require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized");

        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Name() internal virtual view returns (string memory) {
        return _name;
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Version() internal virtual view returns (string memory) {
        return _version;
    }

    /**
     * @dev The hash of the name parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
     */
    function _EIP712NameHash() internal view returns (bytes32) {
        string memory name = _EIP712Name();
        if (bytes(name).length > 0) {
            return keccak256(bytes(name));
        } else {
            // If the name is empty, the contract may have been upgraded without initializing the new storage.
            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
            bytes32 hashedName = _hashedName;
            if (hashedName != 0) {
                return hashedName;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev The hash of the version parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
     */
    function _EIP712VersionHash() internal view returns (bytes32) {
        string memory version = _EIP712Version();
        if (bytes(version).length > 0) {
            return keccak256(bytes(version));
        } else {
            // If the version is empty, the contract may have been upgraded without initializing the new storage.
            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
            bytes32 hashedVersion = _hashedVersion;
            if (hashedVersion != 0) {
                return hashedVersion;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[48] private __gap;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 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 {
                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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // 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;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // 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 + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = MathUpgradeable.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, MathUpgradeable.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 *
 * _Available since v4.1._
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

// 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/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

// 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: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

// 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 Address {
    /**
     * @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 (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";
import "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
 * Argent and Gnosis Safe.
 *
 * _Available since v4.1._
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
        return
            (error == ECDSA.RecoverError.NoError && recovered == signer) ||
            isValidERC1271SignatureNow(signer, hash, signature);
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 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 {
                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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // 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;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // 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 + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// 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 BoringOwnableUpgradeableV2 is BoringOwnableUpgradeableData, Initializable {
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    function __BoringOwnableV2_init(address _owner) internal onlyInitializing {
        owner = _owner;
    }

    /// @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;
}

File 23 of 41 : Errors.sol
// 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 VCInvalidCap(uint256 cap);
    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;
        }
    }
}

File 25 of 41 : PMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity ^0.8.0;

/* solhint-disable private-vars-leading-underscore, reason-string */

library PMath {
    uint256 internal constant ONE = 1e18; // 18 decimal places
    int256 internal constant IONE = 1e18; // 18 decimal places

    function subMax0(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            return (a >= b ? a - b : 0);
        }
    }

    function subNoNeg(int256 a, int256 b) internal pure returns (int256) {
        require(a >= b, "negative");
        return a - b; // no unchecked since if b is very negative, a - b might overflow
    }

    function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 product = a * b;
        unchecked {
            return product / ONE;
        }
    }

    function mulDown(int256 a, int256 b) internal pure returns (int256) {
        int256 product = a * b;
        unchecked {
            return product / IONE;
        }
    }

    function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 aInflated = a * ONE;
        unchecked {
            return aInflated / b;
        }
    }

    function divDown(int256 a, int256 b) internal pure returns (int256) {
        int256 aInflated = a * IONE;
        unchecked {
            return aInflated / b;
        }
    }

    function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a + b - 1) / b;
    }

    function rawDivUp(int256 a, int256 b) internal pure returns (int256) {
        return (a + b - 1) / b;
    }

    function tweakUp(uint256 a, uint256 factor) internal pure returns (uint256) {
        return mulDown(a, ONE + factor);
    }

    function tweakDown(uint256 a, uint256 factor) internal pure returns (uint256) {
        return mulDown(a, ONE - factor);
    }

    /// @return res = min(a + b, bound)
    /// @dev This function should handle arithmetic operation and bound check without overflow/underflow
    function addWithUpperBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) {
        unchecked {
            if (type(uint256).max - b < a) res = bound;
            else res = min(bound, a + b);
        }
    }

    /// @return res = max(a - b, bound)
    /// @dev This function should handle arithmetic operation and bound check without overflow/underflow
    function subWithLowerBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) {
        unchecked {
            if (b > a) res = bound;
            else res = max(a - b, bound);
        }
    }

    function clamp(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256 res) {
        res = x;
        if (x < lower) res = lower;
        else if (x > upper) res = upper;
    }

    // @author Uniswap
    function sqrt(uint256 y) internal pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
    }

    function square(uint256 x) internal pure returns (uint256) {
        return x * x;
    }

    function squareDown(uint256 x) internal pure returns (uint256) {
        return mulDown(x, x);
    }

    function abs(int256 x) internal pure returns (uint256) {
        return uint256(x > 0 ? x : -x);
    }

    function neg(int256 x) internal pure returns (int256) {
        return x * (-1);
    }

    function neg(uint256 x) internal pure returns (int256) {
        return Int(x) * (-1);
    }

    function max(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x > y ? x : y);
    }

    function max(int256 x, int256 y) internal pure returns (int256) {
        return (x > y ? x : y);
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x < y ? x : y);
    }

    function min(int256 x, int256 y) internal pure returns (int256) {
        return (x < y ? x : y);
    }

    /*///////////////////////////////////////////////////////////////
                               SIGNED CASTS
    //////////////////////////////////////////////////////////////*/

    function Int(uint256 x) internal pure returns (int256) {
        require(x <= uint256(type(int256).max));
        return int256(x);
    }

    function Int128(int256 x) internal pure returns (int128) {
        require(type(int128).min <= x && x <= type(int128).max);
        return int128(x);
    }

    function Int128(uint256 x) internal pure returns (int128) {
        return Int128(Int(x));
    }

    /*///////////////////////////////////////////////////////////////
                               UNSIGNED CASTS
    //////////////////////////////////////////////////////////////*/

    function Uint(int256 x) internal pure returns (uint256) {
        require(x >= 0);
        return uint256(x);
    }

    function Uint32(uint256 x) internal pure returns (uint32) {
        require(x <= type(uint32).max);
        return uint32(x);
    }

    function Uint64(uint256 x) internal pure returns (uint64) {
        require(x <= type(uint64).max);
        return uint64(x);
    }

    function Uint112(uint256 x) internal pure returns (uint112) {
        require(x <= type(uint112).max);
        return uint112(x);
    }

    function Uint96(uint256 x) internal pure returns (uint96) {
        require(x <= type(uint96).max);
        return uint96(x);
    }

    function Uint128(uint256 x) internal pure returns (uint128) {
        require(x <= type(uint128).max);
        return uint128(x);
    }

    function Uint192(uint256 x) internal pure returns (uint192) {
        require(x <= type(uint192).max);
        return uint192(x);
    }

    function Uint80(uint256 x) internal pure returns (uint80) {
        require(x <= type(uint80).max);
        return uint80(x);
    }

    function isAApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
        return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps);
    }

    function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
        return a >= b && a <= mulDown(b, ONE + eps);
    }

    function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
        return a <= b && a >= mulDown(b, ONE - eps);
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

library MiniHelpers {
    function isCurrentlyExpired(uint256 expiry) internal view returns (bool) {
        return (expiry <= block.timestamp);
    }

    function isExpired(uint256 expiry, uint256 blockTime) internal pure returns (bool) {
        return (expiry <= blockTime);
    }

    function isTimeInThePast(uint256 timestamp) internal view returns (bool) {
        return (timestamp <= block.timestamp); // same definition as isCurrentlyExpired
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IWETH.sol";

abstract contract TokenHelper {
    using SafeERC20 for IERC20;

    address internal constant NATIVE = address(0);
    uint256 internal constant LOWER_BOUND_APPROVAL = type(uint96).max / 2; // some tokens use 96 bits for approval

    function _transferIn(address token, address from, uint256 amount) internal {
        if (token == NATIVE) require(msg.value == amount, "eth mismatch");
        else if (amount != 0) IERC20(token).safeTransferFrom(from, address(this), amount);
    }

    function _transferFrom(IERC20 token, address from, address to, uint256 amount) internal {
        if (amount != 0) token.safeTransferFrom(from, to, amount);
    }

    function _transferOut(address token, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (token == NATIVE) {
            (bool success, ) = to.call{value: amount}("");
            require(success, "eth send failed");
        } else {
            IERC20(token).safeTransfer(to, amount);
        }
    }

    function _transferOut(address[] memory tokens, address to, uint256[] memory amounts) internal {
        uint256 numTokens = tokens.length;
        require(numTokens == amounts.length, "length mismatch");
        for (uint256 i = 0; i < numTokens; ) {
            _transferOut(tokens[i], to, amounts[i]);
            unchecked {
                i++;
            }
        }
    }

    function _selfBalance(address token) internal view returns (uint256) {
        return (token == NATIVE) ? address(this).balance : IERC20(token).balanceOf(address(this));
    }

    function _selfBalance(IERC20 token) internal view returns (uint256) {
        return token.balanceOf(address(this));
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev PLS PAY ATTENTION to tokens that requires the approval to be set to 0 before changing it
    function _safeApprove(address token, address to, uint256 value) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), "Safe Approve");
    }

    function _safeApproveInf(address token, address to) internal {
        if (token == NATIVE) return;
        if (IERC20(token).allowance(address(this), to) < LOWER_BOUND_APPROVAL) {
            _safeApprove(token, to, 0);
            _safeApprove(token, to, type(uint256).max);
        }
    }

    function _wrap_unwrap_ETH(address tokenIn, address tokenOut, uint256 netTokenIn) internal {
        if (tokenIn == NATIVE) IWETH(tokenOut).deposit{value: netTokenIn}();
        else IWETH(tokenIn).withdraw(netTokenIn);
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "../libraries/math/PMath.sol";
import "../libraries/math/LogExpMath.sol";

import "../StandardizedYield/PYIndex.sol";
import "../libraries/MiniHelpers.sol";
import "../libraries/Errors.sol";

struct MarketState {
    int256 totalPt;
    int256 totalSy;
    int256 totalLp;
    address treasury;
    /// immutable variables ///
    int256 scalarRoot;
    uint256 expiry;
    /// fee data ///
    uint256 lnFeeRateRoot;
    uint256 reserveFeePercent; // base 100
    /// last trade data ///
    uint256 lastLnImpliedRate;
}

// params that are expensive to compute, therefore we pre-compute them
struct MarketPreCompute {
    int256 rateScalar;
    int256 totalAsset;
    int256 rateAnchor;
    int256 feeRate;
}

// solhint-disable ordering
library MarketMathCore {
    using PMath for uint256;
    using PMath for int256;
    using LogExpMath for int256;
    using PYIndexLib for PYIndex;

    int256 internal constant MINIMUM_LIQUIDITY = 10 ** 3;
    int256 internal constant PERCENTAGE_DECIMALS = 100;
    uint256 internal constant DAY = 86400;
    uint256 internal constant IMPLIED_RATE_TIME = 365 * DAY;

    int256 internal constant MAX_MARKET_PROPORTION = (1e18 * 96) / 100;

    using PMath for uint256;
    using PMath for int256;

    /*///////////////////////////////////////////////////////////////
                UINT FUNCTIONS TO PROXY TO CORE FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function addLiquidity(
        MarketState memory market,
        uint256 syDesired,
        uint256 ptDesired,
        uint256 blockTime
    ) internal pure returns (uint256 lpToReserve, uint256 lpToAccount, uint256 syUsed, uint256 ptUsed) {
        (int256 _lpToReserve, int256 _lpToAccount, int256 _syUsed, int256 _ptUsed) = addLiquidityCore(
            market,
            syDesired.Int(),
            ptDesired.Int(),
            blockTime
        );

        lpToReserve = _lpToReserve.Uint();
        lpToAccount = _lpToAccount.Uint();
        syUsed = _syUsed.Uint();
        ptUsed = _ptUsed.Uint();
    }

    function removeLiquidity(
        MarketState memory market,
        uint256 lpToRemove
    ) internal pure returns (uint256 netSyToAccount, uint256 netPtToAccount) {
        (int256 _syToAccount, int256 _ptToAccount) = removeLiquidityCore(market, lpToRemove.Int());

        netSyToAccount = _syToAccount.Uint();
        netPtToAccount = _ptToAccount.Uint();
    }

    function swapExactPtForSy(
        MarketState memory market,
        PYIndex index,
        uint256 exactPtToMarket,
        uint256 blockTime
    ) internal pure returns (uint256 netSyToAccount, uint256 netSyFee, uint256 netSyToReserve) {
        (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore(
            market,
            index,
            exactPtToMarket.neg(),
            blockTime
        );

        netSyToAccount = _netSyToAccount.Uint();
        netSyFee = _netSyFee.Uint();
        netSyToReserve = _netSyToReserve.Uint();
    }

    function swapSyForExactPt(
        MarketState memory market,
        PYIndex index,
        uint256 exactPtToAccount,
        uint256 blockTime
    ) internal pure returns (uint256 netSyToMarket, uint256 netSyFee, uint256 netSyToReserve) {
        (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore(
            market,
            index,
            exactPtToAccount.Int(),
            blockTime
        );

        netSyToMarket = _netSyToAccount.neg().Uint();
        netSyFee = _netSyFee.Uint();
        netSyToReserve = _netSyToReserve.Uint();
    }

    /*///////////////////////////////////////////////////////////////
                    CORE FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function addLiquidityCore(
        MarketState memory market,
        int256 syDesired,
        int256 ptDesired,
        uint256 blockTime
    ) internal pure returns (int256 lpToReserve, int256 lpToAccount, int256 syUsed, int256 ptUsed) {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (syDesired == 0 || ptDesired == 0) revert Errors.MarketZeroAmountsInput();
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        if (market.totalLp == 0) {
            lpToAccount = PMath.sqrt((syDesired * ptDesired).Uint()).Int() - MINIMUM_LIQUIDITY;
            lpToReserve = MINIMUM_LIQUIDITY;
            syUsed = syDesired;
            ptUsed = ptDesired;
        } else {
            int256 netLpByPt = (ptDesired * market.totalLp) / market.totalPt;
            int256 netLpBySy = (syDesired * market.totalLp) / market.totalSy;
            if (netLpByPt < netLpBySy) {
                lpToAccount = netLpByPt;
                ptUsed = ptDesired;
                syUsed = (market.totalSy * lpToAccount).rawDivUp(market.totalLp);
            } else {
                lpToAccount = netLpBySy;
                syUsed = syDesired;
                ptUsed = (market.totalPt * lpToAccount).rawDivUp(market.totalLp);
            }
        }

        if (lpToAccount <= 0 || syUsed <= 0 || ptUsed <= 0) revert Errors.MarketZeroAmountsOutput();

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        market.totalSy += syUsed;
        market.totalPt += ptUsed;
        market.totalLp += lpToAccount + lpToReserve;
    }

    function removeLiquidityCore(
        MarketState memory market,
        int256 lpToRemove
    ) internal pure returns (int256 netSyToAccount, int256 netPtToAccount) {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (lpToRemove == 0) revert Errors.MarketZeroAmountsInput();

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        netSyToAccount = (lpToRemove * market.totalSy) / market.totalLp;
        netPtToAccount = (lpToRemove * market.totalPt) / market.totalLp;

        if (netSyToAccount == 0 && netPtToAccount == 0) revert Errors.MarketZeroAmountsOutput();

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        market.totalLp = market.totalLp.subNoNeg(lpToRemove);
        market.totalPt = market.totalPt.subNoNeg(netPtToAccount);
        market.totalSy = market.totalSy.subNoNeg(netSyToAccount);
    }

    function executeTradeCore(
        MarketState memory market,
        PYIndex index,
        int256 netPtToAccount,
        uint256 blockTime
    ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();
        if (market.totalPt <= netPtToAccount)
            revert Errors.MarketInsufficientPtForTrade(market.totalPt, netPtToAccount);

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        MarketPreCompute memory comp = getMarketPreCompute(market, index, blockTime);

        (netSyToAccount, netSyFee, netSyToReserve) = calcTrade(market, comp, index, netPtToAccount);

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        _setNewMarketStateTrade(market, comp, index, netPtToAccount, netSyToAccount, netSyToReserve, blockTime);
    }

    function getMarketPreCompute(
        MarketState memory market,
        PYIndex index,
        uint256 blockTime
    ) internal pure returns (MarketPreCompute memory res) {
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();

        uint256 timeToExpiry = market.expiry - blockTime;

        res.rateScalar = _getRateScalar(market, timeToExpiry);
        res.totalAsset = index.syToAsset(market.totalSy);

        if (market.totalPt == 0 || res.totalAsset == 0)
            revert Errors.MarketZeroTotalPtOrTotalAsset(market.totalPt, res.totalAsset);

        res.rateAnchor = _getRateAnchor(
            market.totalPt,
            market.lastLnImpliedRate,
            res.totalAsset,
            res.rateScalar,
            timeToExpiry
        );
        res.feeRate = _getExchangeRateFromImpliedRate(market.lnFeeRateRoot, timeToExpiry);
    }

    function calcTrade(
        MarketState memory market,
        MarketPreCompute memory comp,
        PYIndex index,
        int256 netPtToAccount
    ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) {
        int256 preFeeExchangeRate = _getExchangeRate(
            market.totalPt,
            comp.totalAsset,
            comp.rateScalar,
            comp.rateAnchor,
            netPtToAccount
        );

        int256 preFeeAssetToAccount = netPtToAccount.divDown(preFeeExchangeRate).neg();
        int256 fee = comp.feeRate;

        if (netPtToAccount > 0) {
            int256 postFeeExchangeRate = preFeeExchangeRate.divDown(fee);
            if (postFeeExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(postFeeExchangeRate);

            fee = preFeeAssetToAccount.mulDown(PMath.IONE - fee);
        } else {
            fee = ((preFeeAssetToAccount * (PMath.IONE - fee)) / fee).neg();
        }

        int256 netAssetToReserve = (fee * market.reserveFeePercent.Int()) / PERCENTAGE_DECIMALS;
        int256 netAssetToAccount = preFeeAssetToAccount - fee;

        netSyToAccount = netAssetToAccount < 0
            ? index.assetToSyUp(netAssetToAccount)
            : index.assetToSy(netAssetToAccount);
        netSyFee = index.assetToSy(fee);
        netSyToReserve = index.assetToSy(netAssetToReserve);
    }

    function _setNewMarketStateTrade(
        MarketState memory market,
        MarketPreCompute memory comp,
        PYIndex index,
        int256 netPtToAccount,
        int256 netSyToAccount,
        int256 netSyToReserve,
        uint256 blockTime
    ) internal pure {
        uint256 timeToExpiry = market.expiry - blockTime;

        market.totalPt = market.totalPt.subNoNeg(netPtToAccount);
        market.totalSy = market.totalSy.subNoNeg(netSyToAccount + netSyToReserve);

        market.lastLnImpliedRate = _getLnImpliedRate(
            market.totalPt,
            index.syToAsset(market.totalSy),
            comp.rateScalar,
            comp.rateAnchor,
            timeToExpiry
        );

        if (market.lastLnImpliedRate == 0) revert Errors.MarketZeroLnImpliedRate();
    }

    function _getRateAnchor(
        int256 totalPt,
        uint256 lastLnImpliedRate,
        int256 totalAsset,
        int256 rateScalar,
        uint256 timeToExpiry
    ) internal pure returns (int256 rateAnchor) {
        int256 newExchangeRate = _getExchangeRateFromImpliedRate(lastLnImpliedRate, timeToExpiry);

        if (newExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(newExchangeRate);

        {
            int256 proportion = totalPt.divDown(totalPt + totalAsset);

            int256 lnProportion = _logProportion(proportion);

            rateAnchor = newExchangeRate - lnProportion.divDown(rateScalar);
        }
    }

    /// @notice Calculates the current market implied rate.
    /// @return lnImpliedRate the implied rate
    function _getLnImpliedRate(
        int256 totalPt,
        int256 totalAsset,
        int256 rateScalar,
        int256 rateAnchor,
        uint256 timeToExpiry
    ) internal pure returns (uint256 lnImpliedRate) {
        // This will check for exchange rates < PMath.IONE
        int256 exchangeRate = _getExchangeRate(totalPt, totalAsset, rateScalar, rateAnchor, 0);

        // exchangeRate >= 1 so its ln >= 0
        uint256 lnRate = exchangeRate.ln().Uint();

        lnImpliedRate = (lnRate * IMPLIED_RATE_TIME) / timeToExpiry;
    }

    /// @notice Converts an implied rate to an exchange rate given a time to expiry. The
    /// formula is E = e^rt
    function _getExchangeRateFromImpliedRate(
        uint256 lnImpliedRate,
        uint256 timeToExpiry
    ) internal pure returns (int256 exchangeRate) {
        uint256 rt = (lnImpliedRate * timeToExpiry) / IMPLIED_RATE_TIME;

        exchangeRate = LogExpMath.exp(rt.Int());
    }

    function _getExchangeRate(
        int256 totalPt,
        int256 totalAsset,
        int256 rateScalar,
        int256 rateAnchor,
        int256 netPtToAccount
    ) internal pure returns (int256 exchangeRate) {
        int256 numerator = totalPt.subNoNeg(netPtToAccount);

        int256 proportion = (numerator.divDown(totalPt + totalAsset));

        if (proportion > MAX_MARKET_PROPORTION)
            revert Errors.MarketProportionTooHigh(proportion, MAX_MARKET_PROPORTION);

        int256 lnProportion = _logProportion(proportion);

        exchangeRate = lnProportion.divDown(rateScalar) + rateAnchor;

        if (exchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(exchangeRate);
    }

    function _logProportion(int256 proportion) internal pure returns (int256 res) {
        if (proportion == PMath.IONE) revert Errors.MarketProportionMustNotEqualOne();

        int256 logitP = proportion.divDown(PMath.IONE - proportion);

        res = logitP.ln();
    }

    function _getRateScalar(MarketState memory market, uint256 timeToExpiry) internal pure returns (int256 rateScalar) {
        rateScalar = (market.scalarRoot * IMPLIED_RATE_TIME.Int()) / timeToExpiry.Int();
        if (rateScalar <= 0) revert Errors.MarketRateScalarBelowZero(rateScalar);
    }

    function setInitialLnImpliedRate(
        MarketState memory market,
        PYIndex index,
        int256 initialAnchor,
        uint256 blockTime
    ) internal pure {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        int256 totalAsset = index.syToAsset(market.totalSy);
        uint256 timeToExpiry = market.expiry - blockTime;
        int256 rateScalar = _getRateScalar(market, timeToExpiry);

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        market.lastLnImpliedRate = _getLnImpliedRate(
            market.totalPt,
            totalAsset,
            rateScalar,
            initialAnchor,
            timeToExpiry
        );
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../interfaces/IPYieldToken.sol";
import "../../interfaces/IPPrincipalToken.sol";

import "./SYUtils.sol";
import "../libraries/math/PMath.sol";

type PYIndex is uint256;

library PYIndexLib {
    using PMath for uint256;
    using PMath for int256;

    function newIndex(IPYieldToken YT) internal returns (PYIndex) {
        return PYIndex.wrap(YT.pyIndexCurrent());
    }

    function syToAsset(PYIndex index, uint256 syAmount) internal pure returns (uint256) {
        return SYUtils.syToAsset(PYIndex.unwrap(index), syAmount);
    }

    function assetToSy(PYIndex index, uint256 assetAmount) internal pure returns (uint256) {
        return SYUtils.assetToSy(PYIndex.unwrap(index), assetAmount);
    }

    function assetToSyUp(PYIndex index, uint256 assetAmount) internal pure returns (uint256) {
        return SYUtils.assetToSyUp(PYIndex.unwrap(index), assetAmount);
    }

    function syToAssetUp(PYIndex index, uint256 syAmount) internal pure returns (uint256) {
        uint256 _index = PYIndex.unwrap(index);
        return SYUtils.syToAssetUp(_index, syAmount);
    }

    function syToAsset(PYIndex index, int256 syAmount) internal pure returns (int256) {
        int256 sign = syAmount < 0 ? int256(-1) : int256(1);
        return sign * (SYUtils.syToAsset(PYIndex.unwrap(index), syAmount.abs())).Int();
    }

    function assetToSy(PYIndex index, int256 assetAmount) internal pure returns (int256) {
        int256 sign = assetAmount < 0 ? int256(-1) : int256(1);
        return sign * (SYUtils.assetToSy(PYIndex.unwrap(index), assetAmount.abs())).Int();
    }

    function assetToSyUp(PYIndex index, int256 assetAmount) internal pure returns (int256) {
        int256 sign = assetAmount < 0 ? int256(-1) : int256(1);
        return sign * (SYUtils.assetToSyUp(PYIndex.unwrap(index), assetAmount.abs())).Int();
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

library SYUtils {
    uint256 internal constant ONE = 1e18;

    function syToAsset(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) {
        return (syAmount * exchangeRate) / ONE;
    }

    function syToAssetUp(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) {
        return (syAmount * exchangeRate + ONE - 1) / ONE;
    }

    function assetToSy(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) {
        return (assetAmount * ONE) / exchangeRate;
    }

    function assetToSyUp(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) {
        return (assetAmount * ONE + exchangeRate - 1) / exchangeRate;
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPInterestManagerYT {
    event CollectInterestFee(uint256 amountInterestFee);

    function userInterest(address user) external view returns (uint128 lastPYIndex, uint128 accruedInterest);
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "../core/StandardizedYield/PYIndex.sol";

interface IPLimitOrderType {
    enum OrderType {
        SY_FOR_PT,
        PT_FOR_SY,
        SY_FOR_YT,
        YT_FOR_SY
    }

    // Fixed-size order part with core information
    struct StaticOrder {
        uint256 salt;
        uint256 expiry;
        uint256 nonce;
        OrderType orderType;
        address token;
        address YT;
        address maker;
        address receiver;
        uint256 makingAmount;
        uint256 lnImpliedRate;
        uint256 failSafeRate;
    }

    struct FillResults {
        uint256 totalMaking;
        uint256 totalTaking;
        uint256 totalFee;
        uint256 totalNotionalVolume;
        uint256[] netMakings;
        uint256[] netTakings;
        uint256[] netFees;
        uint256[] notionalVolumes;
    }
}

struct Order {
    uint256 salt;
    uint256 expiry;
    uint256 nonce;
    IPLimitOrderType.OrderType orderType;
    address token;
    address YT;
    address maker;
    address receiver;
    uint256 makingAmount;
    uint256 lnImpliedRate;
    uint256 failSafeRate;
    bytes permit;
}

struct FillOrderParams {
    Order order;
    bytes signature;
    uint256 makingAmount;
}

interface IPLimitRouterCallback is IPLimitOrderType {
    function limitRouterCallback(
        uint256 actualMaking,
        uint256 actualTaking,
        uint256 totalFee,
        bytes memory data
    ) external returns (bytes memory);
}

interface IPLimitRouter is IPLimitOrderType {
    struct OrderStatus {
        uint128 filledAmount;
        uint128 remaining;
    }

    event OrderCanceled(address indexed maker, bytes32 indexed orderHash);

    event OrderForceCanceled(bytes32 indexed orderHash);

    event OrderFilledV2(
        bytes32 indexed orderHash,
        OrderType indexed orderType,
        address indexed YT,
        address token,
        uint256 netInputFromMaker,
        uint256 netOutputToMaker,
        uint256 feeAmount,
        uint256 notionalVolume,
        address maker,
        address taker
    );

    // event added on 2/1/2025
    event LnFeeRateRootsSet(address[] YTs, uint256[] lnFeeRateRoots);

    // @dev actualMaking, actualTaking are in the SY form
    function fill(
        FillOrderParams[] memory params,
        address receiver,
        uint256 maxTaking,
        bytes calldata optData,
        bytes calldata callback
    ) external returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn);

    function feeRecipient() external view returns (address);

    function hashOrder(Order memory order) external view returns (bytes32);

    function cancelSingle(Order calldata order) external;

    function cancelBatch(Order[] calldata orders) external;

    function orderStatusesRaw(
        bytes32[] memory orderHashes
    ) external view returns (uint256[] memory remainingsRaw, uint256[] memory filledAmounts);

    function orderStatuses(
        bytes32[] memory orderHashes
    ) external view returns (uint256[] memory remainings, uint256[] memory filledAmounts);

    function DOMAIN_SEPARATOR() external view returns (bytes32);

    function simulate(address target, bytes calldata data) external payable;

    function WNATIVE() external view returns (address);

    function _checkSig(
        Order memory order,
        bytes memory signature
    )
        external
        view
        returns (
            bytes32,
            /*orderHash*/
            uint256,
            /*remainingMakerAmount*/
            uint256
        ); /*filledMakerAmount*/

    /* --- Deprecated events --- */

    // deprecate on 7/1/2024, prior to official launch
    event OrderFilled(
        bytes32 indexed orderHash,
        OrderType indexed orderType,
        address indexed YT,
        address token,
        uint256 netInputFromMaker,
        uint256 netOutputToMaker,
        uint256 feeAmount,
        uint256 notionalVolume
    );
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPMarketFactory {
    struct FeeConfig {
        uint80 lnFeeRateRoot;
        uint8 reserveFeePercent;
        bool active;
    }

    event NewMarketConfig(address indexed treasury, uint80 defaultLnFeeRateRoot, uint8 reserveFeePercent);
    event SetOverriddenFee(address indexed router, uint80 lnFeeRateRoot, uint8 reserveFeePercent);
    event UnsetOverriddenFee(address indexed router);

    event CreateNewMarket(address indexed market, address indexed PT, int256 scalarRoot, int256 initialAnchor);

    function isValidMarket(address market) external view returns (bool);

    // If this is changed, change the readState function in market as well
    function getMarketConfig(
        address router
    ) external view returns (address treasury, uint80 lnFeeRateRoot, uint8 reserveFeePercent);
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IPPrincipalToken is IERC20Metadata {
    function burnByYT(address user, uint256 amount) external;

    function mintByYT(address user, uint256 amount) external;

    function initialize(address _YT) external;

    function SY() external view returns (address);

    function YT() external view returns (address);

    function factory() external view returns (address);

    function expiry() external view returns (uint256);

    function isExpired() external view returns (bool);
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@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
/*
 * 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/IERC20.sol";

interface IWETH is IERC20 {
    event Deposit(address indexed dst, uint256 wad);
    event Withdrawal(address indexed src, uint256 wad);

    function deposit() external payable;

    function withdraw(uint256 wad) external;
}

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @title A helper contract for managing nonce of tx sender

contract NonceManager {
    event NonceIncreased(address indexed maker, uint256 oldNonce, uint256 newNonce);

    mapping(address => uint256) public nonce;

    uint256[100] private __gap;

    /// @notice Advances nonce by one
    function increaseNonce() external {
        advanceNonce(1);
    }

    /// @notice Advances nonce by specified amount
    function advanceNonce(uint8 amount) public {
        uint256 newNonce = nonce[msg.sender] + amount;
        nonce[msg.sender] = newNonce;
        emit NonceIncreased(msg.sender, newNonce - amount, newNonce);
    }

    /// @notice Checks if `makerAddress` has specified `makerNonce`
    /// @return Result True if `makerAddress` has specified nonce. Otherwise, false
    function nonceEquals(address makerAddress, uint256 makerNonce) external view returns (bool) {
        return nonce[makerAddress] == makerNonce;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../interfaces/IPLimitRouter.sol";
import "../core/Market/MarketMathCore.sol";
import "../interfaces/IPMarketFactory.sol";

library LimitMathCore {
    using PYIndexLib for PYIndex;
    using PYIndexLib for IPYieldToken;
    using PMath for uint256;
    using PMath for int256;

    function calcBatch(
        FillOrderParams[] memory params,
        address YT,
        uint256 lnFeeRateRoot
    ) internal returns (IPLimitOrderType.FillResults memory out) {
        return
            calcBatch(
                params,
                IPYieldToken(YT).expiry() - block.timestamp,
                IPYieldToken(YT).pyIndexCurrent(),
                lnFeeRateRoot
            );
    }

    // --- PURE FUNCTIONS ---
    function calcBatch(
        FillOrderParams[] memory params,
        uint256 timeToExpiry,
        uint256 pyIndex,
        uint256 lnFeeRateRoot
    ) internal pure returns (IPLimitOrderType.FillResults memory out) {
        uint256 len = params.length;
        out.netMakings = new uint256[](len);
        out.netTakings = new uint256[](len);
        out.netFees = new uint256[](len);
        out.notionalVolumes = new uint256[](len);

        function(uint256, uint256, PYIndex, uint256)
            internal
            pure
            returns (uint256, uint256, uint256) calc = getCalcFunctions(params[0].order.orderType);

        uint256 feeRate = impliedRateToExchangeRate(lnFeeRateRoot, timeToExpiry);

        for (uint256 i = 0; i < len; i++) {
            FillOrderParams memory param = params[i];
            if (param.makingAmount == 0) continue; // nothing changes

            uint256 exchangeRate = impliedRateToExchangeRate(param.order.lnImpliedRate, timeToExpiry);

            out.netMakings[i] = param.makingAmount;
            (out.netTakings[i], out.netFees[i], out.notionalVolumes[i]) = calc(
                out.netMakings[i],
                exchangeRate,
                PYIndex.wrap(pyIndex),
                feeRate
            );

            require(out.netTakings[i] > 0, "LOP: can't swap 0 amount");

            out.totalMaking += out.netMakings[i];
            out.totalTaking += out.netTakings[i];
            out.totalFee += out.netFees[i];
            out.totalNotionalVolume += out.notionalVolumes[i];
        }
    }

    function calcSyForPt(
        uint256 makeSy,
        uint256 r,
        PYIndex index,
        uint256 f
    ) internal pure returns (uint256 takePt, uint256 fee, uint256 notionalVolume) {
        // takePt = makeSy * index * r
        // fee = makeSy * (f - 1) / f
        // notionalVolume = makeSy

        takePt = index.syToAsset(makeSy).mulDown(r);
        fee = (makeSy * (f - PMath.ONE)) / f;
        notionalVolume = makeSy;
    }

    function calcPtForSy(
        uint256 makePt,
        uint256 r,
        PYIndex index,
        uint256 f
    ) internal pure returns (uint256 takeSy, uint256 fee, uint256 notionalVolume) {
        // takeAsset = make / r
        // takeSy = takeAsset / index
        // fee = takeSy * (f-1)
        // notionalVolume = takeSy

        takeSy = index.assetToSy(makePt.divDown(r));
        fee = takeSy.mulDown(f - PMath.ONE);
        notionalVolume = takeSy;
    }

    function calcSyForYt(
        uint256 makeSy,
        uint256 r,
        PYIndex index,
        uint256 f
    ) internal pure returns (uint256 takeYt, uint256 fee, uint256 notionalVolume) {
        // pt = makeSy * index * r
        // yt = pt / (r-1)
        // fee = makeSy * (f-1) / (r-1)
        // notionalVolume = makeSy / (r-1)
        uint256 pt_yt_ratio = r - PMath.ONE;

        takeYt = (index.syToAsset(makeSy) * r) / pt_yt_ratio;
        fee = (makeSy * (f - PMath.ONE)) / pt_yt_ratio;
        notionalVolume = makeSy.divDown(pt_yt_ratio);
    }

    function calcYtForSy(
        uint256 makeYt,
        uint256 r,
        PYIndex index,
        uint256 f
    ) internal pure returns (uint256 takeSy, uint256 fee, uint256 notionalVolume) {
        // pt = yt * (r-1)
        // takeSy = pt / r / index
        // feeSy = takeSy * (f-1) / f / (r-1)
        // notionalVolume = takeSy / (r-1)
        uint256 pt_yt_ratio = r - PMath.ONE;

        takeSy = index.assetToSy((makeYt * pt_yt_ratio) / r);
        fee = ((takeSy * (f - PMath.ONE)) / f).divDown(pt_yt_ratio);
        notionalVolume = takeSy.divDown(pt_yt_ratio);
    }

    function impliedRateToExchangeRate(uint256 lnRate, uint256 timeToExpiry) internal pure returns (uint256) {
        return MarketMathCore._getExchangeRateFromImpliedRate(lnRate, timeToExpiry).Uint();
    }

    function getCalcFunctions(
        IPLimitOrderType.OrderType t
    )
        internal
        pure
        returns (function(uint256, uint256, PYIndex, uint256) internal pure returns (uint256, uint256, uint256) calc)
    {
        if (t == IPLimitOrderType.OrderType.SY_FOR_PT) {
            return (calcSyForPt);
        } else if (t == IPLimitOrderType.OrderType.PT_FOR_SY) {
            return (calcPtForSy);
        } else if (t == IPLimitOrderType.OrderType.SY_FOR_YT) {
            return (calcSyForYt);
        } else {
            return (calcYtForSy);
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.17;

import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
import "../interfaces/IPLimitRouter.sol";
import "../core/libraries/BoringOwnableUpgradeableV2.sol";
import "../core/libraries/TokenHelper.sol";
import "../interfaces/IStandardizedYield.sol";
import "./helpers/NonceManager.sol";
import "../interfaces/IWETH.sol";
import {LimitMathCore as LimitMath} from "./LimitMathCore.sol";

abstract contract LimitRouterBase is
    EIP712Upgradeable,
    IPLimitRouter,
    BoringOwnableUpgradeableV2,
    NonceManager,
    TokenHelper
{
    using SafeERC20 for IERC20;
    using PMath for uint256;

    bytes32 internal constant LIMIT_ORDER_TYPEHASH =
        keccak256(
            "Order(uint256 salt,uint256 expiry,uint256 nonce,uint8 orderType,address token,address YT,address maker,address receiver,uint256 makingAmount,uint256 lnImpliedRate,uint256 failSafeRate,bytes permit)"
        );

    uint128 internal constant _ORDER_DOES_NOT_EXIST = 0;
    uint128 internal constant _ORDER_FILLED = 1;
    uint256 internal constant NEW_PRIME = 12421;
    uint256 internal constant MAX_LN_FEE_RATE_ROOT = 48790164169432003; // ln(1.05)

    bytes private constant EMPTY_BYTES = abi.encode();

    address public feeRecipient;

    // YT => lnFeeRateRoot // not to be accessed directly
    mapping(address => uint256) internal __lnFeeRateRoot;

    address public immutable WNATIVE;

    mapping(bytes32 => OrderStatus) internal _status;

    address public ownerHelper;

    uint256[99] private __gap;

    modifier onlyHelperAndOwner() {
        require(msg.sender == ownerHelper || msg.sender == owner, "not allowed");
        _;
    }

    constructor(address _WNATIVE) {
        WNATIVE = _WNATIVE;
    }

    // solhint-disable-next-line no-empty-blocks
    receive() external payable {}

    function initialize(address _feeRecipient, address _owner) external initializer {
        __BoringOwnableV2_init(msg.sender);
        __EIP712_init("Pendle Limit Order Protocol", "1");
        setFeeRecipient(_feeRecipient);
        transferOwnership(_owner, true, false);
    }

    function fill(
        FillOrderParams[] memory params,
        address receiver,
        uint256 maxTaking,
        bytes calldata /*optData*/,
        bytes memory callback
    ) external returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn) {
        params = _validateSkipSigAndFilterOrders(params);
        if (params.length == 0) return fillNoOrders(callback);

        OrderType orderType = params[0].order.orderType;
        if (orderType == OrderType.SY_FOR_PT || orderType == OrderType.SY_FOR_YT) {
            return fillTokenForPY(Args(orderType, params, receiver, maxTaking, callback));
        } else {
            return fillPYForToken(Args(orderType, params, receiver, maxTaking, callback));
        }
    }

    // ----------------- Core logic -----------------

    struct Args {
        OrderType orderType;
        FillOrderParams[] params;
        address receiver;
        uint256 maxTaking;
        bytes callback;
    }

    function fillNoOrders(
        bytes memory callback
    ) internal returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn) {
        callbackReturn = callbackIfNeeded(0, 0, 0, callback);
        return (0, 0, 0, callbackReturn);
    }

    function fillTokenForPY(
        Args memory a
    ) internal returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn) {
        (address SY, address PT, address YT, bytes32[] memory orderHashes) = _checkSig_updMakingAndStatus(a.params);

        // Token => This
        uint256[] memory fromMakers = _transferFromMakers_mintSy_updMakings(SY, a.params);

        FillResults memory out = LimitMath.calcBatch(a.params, YT, getLnFeeRateRoot(YT));
        (actualMaking, actualTaking, totalFee) = (out.totalMaking - out.totalFee, out.totalTaking, out.totalFee);

        require(actualTaking <= a.maxTaking, "LOP: maxTaking exceeded");

        // This => Taker
        _transferOut(SY, a.receiver, actualMaking);

        // callback to Taker
        callbackReturn = callbackIfNeeded(actualMaking, actualTaking, totalFee, a.callback);

        // Taker => Makers
        address pyToMaker = (a.orderType == OrderType.SY_FOR_PT) ? PT : YT;
        _transferToMakers(IERC20(pyToMaker), msg.sender, a.params, out.netTakings);

        // This => Fee
        _transferOut(SY, feeRecipient, totalFee);

        // toMakers == netTakings
        _emitEvents(a.params, orderHashes, fromMakers, out.netTakings, out.netFees, out.notionalVolumes);
    }

    function fillPYForToken(
        Args memory a
    ) internal returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn) {
        (address SY, address PT, address YT, bytes32[] memory orderHashes) = _checkSig_updMakingAndStatus(a.params);

        FillResults memory out = LimitMath.calcBatch(a.params, YT, getLnFeeRateRoot(YT));
        (actualMaking, actualTaking, totalFee) = (out.totalMaking, out.totalTaking + out.totalFee, out.totalFee);

        require(actualTaking <= a.maxTaking, "LOP: maxTaking exceeded");

        // Makers => Taker
        address pyFromMaker = (a.orderType == OrderType.PT_FOR_SY) ? PT : YT;
        _transferFromMakers(IERC20(pyFromMaker), a.params, a.receiver, out.netMakings);

        // callback to Taker
        callbackReturn = callbackIfNeeded(actualMaking, actualTaking, totalFee, a.callback);

        // Taker => This
        _transferFrom(IERC20(SY), msg.sender, address(this), actualTaking);

        // This => Makers
        uint256[] memory toMakers = _redeemSy_transferToMakers(SY, a.params, out.netTakings);

        // This => Fee
        _transferOut(SY, feeRecipient, totalFee);

        // fromMakers == netMakings
        _emitEvents(a.params, orderHashes, out.netMakings, toMakers, out.netFees, out.notionalVolumes);
    }

    // ----------------- verify & convert functions -----------------
    function _validateSkipSigAndFilterOrders(
        FillOrderParams[] memory params
    ) internal view returns (FillOrderParams[] memory res) {
        uint256 len = params.length;
        require(len != 0, "LOP: empty batch");

        (address YT, OrderType orderType) = (params[0].order.YT, params[0].order.orderType);
        require(block.timestamp < IPYieldToken(YT).expiry(), "LOP: PY expired");

        uint256 skipped = 0;
        for (uint256 i = 0; i < len; i++) {
            Order memory order = params[i].order;
            require(order.orderType == orderType && order.YT == YT, "LOP: mismatch types");

            if (!(block.timestamp < order.expiry && order.nonce >= nonce[order.maker])) {
                skipped++;
                params[i].signature = EMPTY_BYTES;
            }
        }

        res = new FillOrderParams[](len - skipped);
        uint256 iter = 0;
        for (uint256 i = 0; i < len; i++) {
            if (params[i].signature.length != 0) {
                res[iter] = params[i];
                iter++;
            }
        }
    }

    function _checkSig_updMakingAndStatus(
        FillOrderParams[] memory params
    ) internal returns (address SY, address PT, address YT, bytes32[] memory orderHashes) {
        uint256 len = params.length;
        orderHashes = new bytes32[](len);

        for (uint256 i = 0; i < len; i++) {
            FillOrderParams memory param = params[i];

            (bytes32 orderHash, uint256 remainingMakerAmount, uint256 filledMakerAmount) = _checkSig(
                param.order,
                param.signature
            );
            uint256 netMaking = PMath.min(param.makingAmount, remainingMakerAmount);

            unchecked {
                remainingMakerAmount = remainingMakerAmount - netMaking;
                _status[orderHash] = OrderStatus({
                    remaining: (remainingMakerAmount + 1).Uint128(),
                    filledAmount: (filledMakerAmount + netMaking).Uint128()
                });
            }

            param.makingAmount = netMaking;

            orderHashes[i] = orderHash;
        }

        YT = params[0].order.YT;
        SY = IPYieldToken(YT).SY();
        PT = IPYieldToken(YT).PT();
    }

    function _emitEvents(
        FillOrderParams[] memory params,
        bytes32[] memory hashes,
        uint256[] memory fromMakers,
        uint256[] memory toMakers,
        uint256[] memory netFees,
        uint256[] memory notionalVolumes
    ) internal {
        uint256 len = hashes.length;

        for (uint256 i = 0; i < len; i++) {
            Order memory order = params[i].order;
            emit OrderFilledV2(
                hashes[i],
                order.orderType,
                order.YT,
                order.token,
                fromMakers[i],
                toMakers[i],
                netFees[i],
                notionalVolumes[i],
                params[i].order.maker,
                msg.sender
            );
        }
    }

    function callbackIfNeeded(
        uint256 actualMaking,
        uint256 actualTaking,
        uint256 totalFee,
        bytes memory callback
    ) internal returns (bytes memory callbackReturn) {
        if (callback.length > 0) {
            callbackReturn = IPLimitRouterCallback(msg.sender).limitRouterCallback(
                actualMaking,
                actualTaking,
                totalFee,
                callback
            );
        }
    }

    function _checkSig(
        Order memory order,
        bytes memory signature
    )
        public
        view
        returns (
            bytes32,
            /*orderHash*/
            uint256,
            /*remainingMakerAmount*/
            uint256 /*filledMakerAmount*/
        )
    {
        bytes32 orderHash = hashOrder(order);
        OrderStatus memory status = _status[orderHash];
        (uint256 remainingMakerAmount, uint256 filledMakerAmount) = (status.remaining, status.filledAmount);

        if (remainingMakerAmount == _ORDER_DOES_NOT_EXIST) {
            require(SignatureChecker.isValidSignatureNow(order.maker, orderHash, signature), "LOP: bad signature");

            remainingMakerAmount = order.makingAmount;
        } else {
            unchecked {
                remainingMakerAmount -= 1;
            }
        }

        return (orderHash, remainingMakerAmount, filledMakerAmount);
    }

    // ----------------- simple helper functions functions -----------------

    function _transferFromMakers_mintSy_updMakings(
        address SY,
        FillOrderParams[] memory params
    ) internal returns (uint256[] memory fromMakers) {
        uint256 len = params.length;
        fromMakers = new uint256[](len);

        for ((uint256 l, uint256 r) = (0, 0); l < len; l = r) {
            address sharedToken = params[l].order.token;
            uint256 totalMaking = 0;
            for (; r < len && params[r].order.token == sharedToken; r++) {
                _transferIn(sharedToken, params[r].order.maker, params[r].makingAmount);
                totalMaking += params[r].makingAmount;
                fromMakers[r] = params[r].makingAmount;
            }

            if (sharedToken == SY || totalMaking == 0) continue;

            uint256 totalSy = __mintSy_Single(SY, sharedToken, totalMaking);
            for (uint256 i = l; i < r; i++) {
                uint256 netToken = params[i].makingAmount;
                uint256 netSy = (netToken * totalSy) / totalMaking;

                if (_isNewOrder(params[i].order)) {
                    require(netToken.mulDown(params[i].order.failSafeRate) <= netSy, "LOP: fail safe");
                }

                params[i].makingAmount = netSy;
            }
        }
    }

    function __mintSy_Single(address SY, address token, uint256 netTokenIn) private returns (uint256 netSyOut) {
        if (token == WNATIVE && !IStandardizedYield(SY).isValidTokenIn(WNATIVE)) {
            _wrap_unwrap_ETH(WNATIVE, NATIVE, netTokenIn);
            token = NATIVE;
        }
        _safeApproveInf(token, SY);
        return
            IStandardizedYield(SY).deposit{value: token == NATIVE ? netTokenIn : 0}(
                address(this),
                token,
                netTokenIn,
                0
            );
    }

    function _redeemSy_transferToMakers(
        address SY,
        FillOrderParams[] memory params,
        uint256[] memory netSyOuts
    ) internal returns (uint256[] memory toMakers) {
        uint256 len = params.length;
        toMakers = new uint256[](len);

        for ((uint256 l, uint256 r) = (0, 0); l < len; l = r) {
            address sharedToken = params[l].order.token;
            uint256 totalSy = 0;

            for (; r < len && __stillShared(sharedToken, params[r].order.token); r++) {
                totalSy += netSyOuts[r];
            }

            if (totalSy == 0) continue;

            if (sharedToken == SY) {
                for (uint256 i = l; i < r; i++) {
                    _transferOut(SY, params[i].order.receiver, netSyOuts[i]);
                    toMakers[i] = netSyOuts[i];
                }
                continue;
            }

            if (r - l == 1) {
                toMakers[l] = __redeemSy_Single(params[l].order.receiver, SY, sharedToken, netSyOuts[l]);
            } else {
                uint256 totalToken = __redeemSy_Single(address(this), SY, sharedToken, totalSy);
                for (uint256 i = l; i < r; i++) {
                    address token = params[i].order.token;
                    toMakers[i] = (netSyOuts[i] * totalToken) / totalSy;
                    if (sharedToken != token) {
                        // WNATIVE case
                        _wrap_unwrap_ETH(sharedToken, token, toMakers[i]);
                    }
                    _transferOut(token, params[i].order.receiver, toMakers[i]);
                }
            }

            for (uint256 i = l; i < r; i++) {
                if (_isNewOrder(params[i].order)) {
                    uint256 netSy = netSyOuts[i];
                    uint256 netToken = toMakers[i];

                    require(netSy.mulDown(params[i].order.failSafeRate) <= netToken, "LOP: fail safe");
                }
            }
        }
    }

    function __stillShared(address currentShared, address nextToken) private view returns (bool) {
        return
            (currentShared == nextToken) ||
            (currentShared == NATIVE && nextToken == WNATIVE) ||
            (currentShared == WNATIVE && nextToken == NATIVE);
    }

    function __redeemSy_Single(
        address receiver,
        address SY,
        address tokenOut,
        uint256 netSyIn
    ) private returns (uint256 netTokenOut) {
        if (tokenOut == NATIVE || tokenOut == WNATIVE) {
            address otherToken = tokenOut == NATIVE ? WNATIVE : NATIVE;
            address tokenRedeemSy = IStandardizedYield(SY).isValidTokenOut(tokenOut) ? tokenOut : otherToken;

            netTokenOut = IStandardizedYield(SY).redeem(address(this), netSyIn, tokenRedeemSy, 0, false);

            if (tokenOut != tokenRedeemSy) {
                _wrap_unwrap_ETH(tokenRedeemSy, tokenOut, netTokenOut);
            }

            if (receiver != address(this)) {
                _transferOut(tokenOut, receiver, netTokenOut);
            }
        } else {
            return IStandardizedYield(SY).redeem(receiver, netSyIn, tokenOut, 0, false);
        }
    }

    // ! Allow self-fill of orders
    function _transferFromMakers(
        IERC20 token,
        FillOrderParams[] memory params,
        address to,
        uint256[] memory netIn
    ) internal {
        uint256 len = params.length;
        for (uint256 i = 0; i < len; i++) {
            if (params[i].order.maker == to) continue;
            token.safeTransferFrom(params[i].order.maker, to, netIn[i]);
        }
    }

    function _transferToMakers(
        IERC20 token,
        address payer,
        FillOrderParams[] memory params,
        uint256[] memory netOut
    ) internal {
        uint256 len = params.length;
        for (uint256 i = 0; i < len; i++) {
            if (payer == params[i].order.receiver) continue;
            token.safeTransferFrom(payer, params[i].order.receiver, netOut[i]);
        }
    }

    function _isNewOrder(Order memory order) internal pure returns (bool) {
        return order.salt % NEW_PRIME == 0;
    }

    function hashOrder(Order memory order) public view returns (bytes32) {
        StaticOrder memory staticOrder;
        assembly {
            staticOrder := order
        }
        return _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_TYPEHASH, staticOrder, keccak256(order.permit))));
    }

    function getLnFeeRateRoot(address YT) public view returns (uint256 res) {
        res = __lnFeeRateRoot[YT];
        require(res > 0, "LOP: fee not set");
    }

    // ----------------- Owner -----------------

    function setFeeRecipient(address _feeRecipient) public onlyOwner {
        feeRecipient = _feeRecipient;
    }

    function setOwnerHelper(address _helper) public onlyOwner {
        ownerHelper = _helper;
    }

    /// @dev if zero fees are intended, it must be explicitly allowed again
    function setLnFeeRateRoots(
        address[] memory YTs,
        uint256[] memory lnFeeRateRoots,
        bool allowZeroFees
    ) public onlyHelperAndOwner {
        uint256 len = YTs.length;
        require(len == lnFeeRateRoots.length, "LOP: length mismatch");

        for (uint256 i = 0; i < len; i++) {
            require(lnFeeRateRoots[i] > 0 || allowZeroFees, "LOP: zero fee must be allowed explicitly");
            require(lnFeeRateRoots[i] <= MAX_LN_FEE_RATE_ROOT, "LOP: fee too high");

            __lnFeeRateRoot[YTs[i]] = lnFeeRateRoots[i];
        }

        emit LnFeeRateRootsSet(YTs, lnFeeRateRoots);
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 1000000
  },
  "viaIR": true,
  "evmVersion": "shanghai",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_WNATIVE","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"res","type":"bytes"}],"name":"SimulationResults","type":"error"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address[]","name":"YTs","type":"address[]"},{"indexed":false,"internalType":"uint256[]","name":"lnFeeRateRoots","type":"uint256[]"}],"name":"LnFeeRateRootsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":false,"internalType":"uint256","name":"oldNonce","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newNonce","type":"uint256"}],"name":"NonceIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"maker","type":"address"},{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"OrderCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":true,"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"indexed":true,"internalType":"address","name":"YT","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"netInputFromMaker","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"netOutputToMaker","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"notionalVolume","type":"uint256"}],"name":"OrderFilled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"},{"indexed":true,"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"indexed":true,"internalType":"address","name":"YT","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"netInputFromMaker","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"netOutputToMaker","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feeAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"notionalVolume","type":"uint256"},{"indexed":false,"internalType":"address","name":"maker","type":"address"},{"indexed":false,"internalType":"address","name":"taker","type":"address"}],"name":"OrderFilledV2","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"orderHash","type":"bytes32"}],"name":"OrderForceCanceled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WNATIVE","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"YT","type":"address"},{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"makingAmount","type":"uint256"},{"internalType":"uint256","name":"lnImpliedRate","type":"uint256"},{"internalType":"uint256","name":"failSafeRate","type":"uint256"},{"internalType":"bytes","name":"permit","type":"bytes"}],"internalType":"struct Order","name":"order","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"_checkSig","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"amount","type":"uint8"}],"name":"advanceNonce","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"YT","type":"address"},{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"makingAmount","type":"uint256"},{"internalType":"uint256","name":"lnImpliedRate","type":"uint256"},{"internalType":"uint256","name":"failSafeRate","type":"uint256"},{"internalType":"bytes","name":"permit","type":"bytes"}],"internalType":"struct Order[]","name":"orders","type":"tuple[]"}],"name":"cancelBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"YT","type":"address"},{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"makingAmount","type":"uint256"},{"internalType":"uint256","name":"lnImpliedRate","type":"uint256"},{"internalType":"uint256","name":"failSafeRate","type":"uint256"},{"internalType":"bytes","name":"permit","type":"bytes"}],"internalType":"struct Order","name":"order","type":"tuple"}],"name":"cancelSingle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"YT","type":"address"},{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"makingAmount","type":"uint256"},{"internalType":"uint256","name":"lnImpliedRate","type":"uint256"},{"internalType":"uint256","name":"failSafeRate","type":"uint256"},{"internalType":"bytes","name":"permit","type":"bytes"}],"internalType":"struct Order","name":"order","type":"tuple"},{"internalType":"bytes","name":"signature","type":"bytes"},{"internalType":"uint256","name":"makingAmount","type":"uint256"}],"internalType":"struct FillOrderParams[]","name":"params","type":"tuple[]"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"maxTaking","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"bytes","name":"callback","type":"bytes"}],"name":"fill","outputs":[{"internalType":"uint256","name":"actualMaking","type":"uint256"},{"internalType":"uint256","name":"actualTaking","type":"uint256"},{"internalType":"uint256","name":"totalFee","type":"uint256"},{"internalType":"bytes","name":"callbackReturn","type":"bytes"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"orderHashes","type":"bytes32[]"}],"name":"forceCancel","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"YT","type":"address"}],"name":"getLnFeeRateRoot","outputs":[{"internalType":"uint256","name":"res","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"salt","type":"uint256"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"enum IPLimitOrderType.OrderType","name":"orderType","type":"uint8"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"YT","type":"address"},{"internalType":"address","name":"maker","type":"address"},{"internalType":"address","name":"receiver","type":"address"},{"internalType":"uint256","name":"makingAmount","type":"uint256"},{"internalType":"uint256","name":"lnImpliedRate","type":"uint256"},{"internalType":"uint256","name":"failSafeRate","type":"uint256"},{"internalType":"bytes","name":"permit","type":"bytes"}],"internalType":"struct Order","name":"order","type":"tuple"}],"name":"hashOrder","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"increaseNonce","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeRecipient","type":"address"},{"internalType":"address","name":"_owner","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"makerAddress","type":"address"},{"internalType":"uint256","name":"makerNonce","type":"uint256"}],"name":"nonceEquals","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"orderHashes","type":"bytes32[]"}],"name":"orderStatuses","outputs":[{"internalType":"uint256[]","name":"remainings","type":"uint256[]"},{"internalType":"uint256[]","name":"filledAmounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32[]","name":"orderHashes","type":"bytes32[]"}],"name":"orderStatusesRaw","outputs":[{"internalType":"uint256[]","name":"remainingsRaw","type":"uint256[]"},{"internalType":"uint256[]","name":"filledAmounts","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ownerHelper","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_feeRecipient","type":"address"}],"name":"setFeeRecipient","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"YTs","type":"address[]"},{"internalType":"uint256[]","name":"lnFeeRateRoots","type":"uint256[]"},{"internalType":"bool","name":"allowZeroFees","type":"bool"}],"name":"setLnFeeRateRoots","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_helper","type":"address"}],"name":"setOwnerHelper","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"simulate","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"},{"internalType":"bool","name":"direct","type":"bool"},{"internalType":"bool","name":"renounce","type":"bool"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60a0346200014a57601f62005d5538819003918201601f19168301916001600160401b038311848410176200014e578084926020946040528339810103126200014a57516001600160a01b03811681036200014a5760805260015460ff8160a81c16620000f55760ff808260a01c1603620000b1575b604051615bf290816200016382396080518181816114c7015281816148b4015281816149030152818161497101528181614bc80152614e160152f35b60ff60a01b191660ff60a01b1760015560405160ff81527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602090a15f62000075565b60405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b6064820152608490fd5b5f80fd5b634e487b7160e01b5f52604160045260245ffdfe6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c8063078dfbe7146101c95780630b4e3350146101c45780630c0b8c9c146101bf5780632545e4bd146101ba57806332707597146101b557806335ee3ffc146101b05780633644e515146101ab57806346904840146101a6578063485cc955146101a15780634e71e0c81461019c5780635413fba7146101975780635d436b7e146101925780636122b1731461018d57806370ae92d21461018857806372c244a81461018357806384b0196e1461017e5780638da5cb5b1461017957806397cf58b014610174578063b381cf401461016f578063bd61951d1461016a578063c53a029214610165578063cf6fc6e314610160578063d74a3eca1461015b578063e30c397814610156578063e74b981b14610151578063f1d4deb31461014c5763f34c010c0361000e57611967565b611907565b61187a565b611829565b611712565b61163c565b6115a8565b6114eb565b61147d565b6113aa565b6112fa565b611229565b6110f5565b61108e565b610f04565b610ddb565b610d7f565b610c3d565b610a9f565b610a4e565b610a16565b6109eb565b610992565b610945565b610860565b6106c7565b610221565b73ffffffffffffffffffffffffffffffffffffffff8116036101ec57565b5f80fd5b602435906101fd826101ce565b565b35906101fd826101ce565b801515036101ec57565b604435906101fd8261020a565b346101ec5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043561025c816101ce565b602435906102698261020a565b604435916102768361020a565b73ffffffffffffffffffffffffffffffffffffffff9061029a825f541633146119f4565b156103e7578116918215908115916103df575b501561038157610354916102f16102d85f5473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b7f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000005f5416175f55565b6100187fffffffffffffffffffffffff000000000000000000000000000000000000000060015416600155565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4f776e61626c653a207a65726f206164647265737300000000000000000000006044820152fd5b90505f6102ad565b9150167fffffffffffffffffffffffff000000000000000000000000000000000000000060015416176001555f80f35b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6060810190811067ffffffffffffffff82111761046057604052565b610417565b6040810190811067ffffffffffffffff82111761046057604052565b610160810190811067ffffffffffffffff82111761046057604052565b610180810190811067ffffffffffffffff82111761046057604052565b67ffffffffffffffff811161046057604052565b60a0810190811067ffffffffffffffff82111761046057604052565b6020810190811067ffffffffffffffff82111761046057604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761046057604052565b604051906101fd8261049e565b604051906101fd826104cf565b604051906101fd82610465565b359060048210156101ec57565b67ffffffffffffffff811161046057601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b81601f820112156101ec578035906105cd8261057c565b926105db6040519485610507565b828452602083830101116101ec57815f926020809301838601378301015290565b9190610180838203126101ec57610611610548565b928035845260208101356020850152604081013560408501526106366060820161056f565b6060850152610647608082016101ff565b608085015261065860a082016101ff565b60a085015261066960c082016101ff565b60c085015261067a60e082016101ff565b60e0850152610100808201359085015261012080820135908501526101408082013590850152610160918282013567ffffffffffffffff81116101ec576106c192016105b6565b90830152565b346101ec5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5767ffffffffffffffff6004358181116101ec576107179036906004016105fc565b906024359081116101ec5760609161073661073c9236906004016105b6565b90611b8d565b9060405192835260208301526040820152f35b67ffffffffffffffff81116104605760051b60200190565b6020807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126101ec576004359167ffffffffffffffff83116101ec57806023840112156101ec5782600401356107be8161074f565b936107cc6040519586610507565b8185526024602086019260051b8201019283116101ec57602401905b8282106107f6575050505090565b813581529083019083016107e8565b9081518082526020808093019301915f5b828110610824575050505090565b835185529381019392810192600101610816565b909161084f61085d93604084526040840190610805565b916020818403910152610805565b90565b346101ec5761087661087136610767565b61205a565b5f5b82518110156109305761088b8184611d8c565b51156108d257807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6108bf60019386611d8c565b51016108cb8286611d8c565b5201610878565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f4c4f503a20556e6b6e6f776e206f7264657200000000000000000000000000006044820152fd5b509061094160405192839283610838565b0390f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602061098a600435610985816101ce565b611da0565b604051908152f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043567ffffffffffffffff81116101ec5761098a6109e660209236906004016105fc565b611f78565b346101ec576109fc61087136610767565b9061094160405192839283610838565b5f9103126101ec57565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602061098a613480565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff60cb5416604051908152f35b346101ec5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57600435610ada816101ce565b610b5c602435610ae9816101ce565b60015492610b0e60ff8560a81c161580958196610c2b575b8115610c08575b506120e3565b83610b53740100000000000000000000000000000000000000007fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff6001541617600155565b610bbe5761216e565b610b6257005b610b8f7fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff60015416600155565b604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602090a1005b610c0375010000000000000000000000000000000000000000007fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff6001541617600155565b61216e565b303b15915081610c1a575b505f610b08565b60a01c60ff1660011490505f610c13565b9050600160ff8260a01c161090610b01565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5773ffffffffffffffffffffffffffffffffffffffff8060015416803303610d215780610cf7925f54167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000005f5416175f55565b600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055005b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f4f776e61626c653a2063616c6c657220213d2070656e64696e67206f776e65726044820152fd5b346101ec577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc6020813601126101ec576004359067ffffffffffffffff82116101ec576101809082360301126101ec57610018906004016123b6565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff60ce5416604051908152f35b9181601f840112156101ec5782359167ffffffffffffffff83116101ec57602083818601950101116101ec57565b5f5b838110610e6b5750505f910152565b8181015183820152602001610e5c565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f602093610eb781518092818752878088019101610e5a565b0116010190565b90608061085d925f81525f60208201525f60408201528160608201520190610e7b565b909260809261085d95948352602083015260408201528160608201520190610e7b565b346101ec5760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043567ffffffffffffffff8082116101ec57366023830112156101ec578160040135602492610f628261074f565b93604092610f736040519687610507565b8086526020936024602088019260051b850101933685116101ec5760248101925b858410610ff8578888610fa56101f0565b6064358281116101ec57610fbd903690600401610e2c565b50506084359182116101ec5761094192610fde610fe89336906004016105b6565b916044359161251d565b9060409492945194859485610ee1565b83358881116101ec57820160607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc82360301126101ec5783519161103b83610444565b868201358a81116101ec57611055908836918501016105fc565b83526044820135928a84116101ec5760648a949361107986958b36918401016105b6565b85840152013586820152815201930192610f94565b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5773ffffffffffffffffffffffffffffffffffffffff6004356110de816101ce565b165f526066602052602060405f2054604051908152f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043560ff81168091036101ec57335f52606660205260405f20549080820180921161119f57335f5260666020528160405f205581039080821161119f5760408051928352602083019190915233917fdc0537f71d06d3708f52baf4ddf6918b25f1a145ba08873de27485682b35cac191819081015b0390a2005b6125fc565b919361120a61085d9694956111fc73ffffffffffffffffffffffffffffffffffffffff947f0f00000000000000000000000000000000000000000000000000000000000000875260e0602088015260e0870190610e7b565b908582036040870152610e7b565b9460608401521660808201525f60a082015260c0818403910152610805565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760025415806112f0575b156112925761126e6132cf565b6112766133af565b90610941611282611ff5565b60405193849330914691866111a4565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4549503731323a20556e696e697469616c697a656400000000000000000000006044820152fd5b5060035415611261565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff5f5416604051908152f35b9080601f830112156101ec5760209082356113648161074f565b936113726040519586610507565b81855260208086019260051b8201019283116101ec57602001905b82821061139b575050505090565b8135815290830190830161138d565b346101ec5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5767ffffffffffffffff6004358181116101ec57366023820112156101ec5780600401356114058161074f565b916114136040519384610507565b8183526020916024602085019160051b830101913683116101ec57602401905b82821061146457602435858782116101ec5761145661001892369060040161134a565b61145e610214565b916126a8565b8380918335611472816101ce565b815201910190611433565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b60407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57600435611521816101ce565b60243567ffffffffffffffff81116101ec575f9161154483923690600401610e2c565b90816040519283928337810184815203915af461155f61297b565b906115a46040519283927f1934afc800000000000000000000000000000000000000000000000000000000845215156004840152604060248401526044830190610e7b565b0390fd5b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57335f52606660205260405f20546001810180821161119f5761119a7fdc0537f71d06d3708f52baf4ddf6918b25f1a145ba08873de27485682b35cac191335f5260666020528060405f205560405191829133958360209093929193604081019481520152565b346101ec5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5773ffffffffffffffffffffffffffffffffffffffff60043561168c816101ce565b165f526066602052602060243560405f205414604051908152f35b9060207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126101ec5760043567ffffffffffffffff928382116101ec57806023830112156101ec5781600401359384116101ec5760248460051b830101116101ec576024019190565b346101ec57611720366116a7565b9061174e73ffffffffffffffffffffffffffffffffffffffff8060ce5416331490811561181c575b50612643565b5f5b82811061175957005b8061176760019285856129aa565b355f5260cd6020528161179060405f205460801c6fffffffffffffffffffffffffffffffff1690565b14611817576117e06117b56117a68387876129aa565b355f5260cd60205260405f2090565b7001000000000000000000000000000000006fffffffffffffffffffffffffffffffff825416179055565b6117eb8185856129aa565b357f7e764b5c87bad409a763c11635251284e519d7bbd042eef277b3529e212c25465f80a25b01611750565b611811565b90505f541633145f611748565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec576004356118b5816101ce565b73ffffffffffffffffffffffffffffffffffffffff906118d9825f541633146119f4565b167fffffffffffffffffffffffff000000000000000000000000000000000000000060cb54161760cb555f80f35b346101ec57611915366116a7565b5f5b81811061192057005b8060051b830135907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81843603018212156101ec5761196160019285016123b6565b01611917565b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec576004356119a2816101ce565b73ffffffffffffffffffffffffffffffffffffffff906119c6825f541633146119f4565b167fffffffffffffffffffffffff000000000000000000000000000000000000000060ce54161760ce555f80f35b156119fb57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b73ffffffffffffffffffffffffffffffffffffffff90815f541691611a7f8333146119f4565b81168015801590611b21575b1561038157611af7927f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000005f5416175f55565b7fffffffffffffffffffffffff000000000000000000000000000000000000000060015416600155565b505f611a8b565b15611b2f57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f4c4f503a20626164207369676e617475726500000000000000000000000000006044820152fd5b91611b9783611f78565b92835f5260209060cd825260405f20938260405195611bb587610465565b54956fffffffffffffffffffffffffffffffff87169687825260801c918291015280155f14611d23575073ffffffffffffffffffffffffffffffffffffffff928360c084015116611c06838961344b565b9390956005851015611d1e578994159687611d12575b50508515611c3b575b50505050611c3561010092611b28565b01519190565b5f92939550908291604051611cb881611c8c888201947f1626ba7e000000000000000000000000000000000000000000000000000000009b8c87526024840152604060448401526064830190610e7b565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08101835282610507565b51915afa92611cc561297b565b9084611d05575b84611ce3575b505050611c3561010086915f611c25565b9091809450828051810103126101ec5761010093611c3592015114925f611cd2565b9350818151101593611ccc565b16821495505f80611c1c565b611e29565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01949392505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b805115611d875760200190565b611d4d565b8051821015611d875760209160051b010190565b73ffffffffffffffffffffffffffffffffffffffff165f5260cc60205260405f2054908115611dcb57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f4c4f503a20666565206e6f7420736574000000000000000000000000000000006044820152fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b60041115611d1e57565b906004821015611d1e5752565b61018090939291936101a08101947f22742a2f8610a2d0e945db84f408aacc9d3081f99974bc30b023966fa2fd59318252805160208301526020810151604083015260408101516060830152611ecb60608201516080840190611e60565b608081015173ffffffffffffffffffffffffffffffffffffffff1660a083015260a081015173ffffffffffffffffffffffffffffffffffffffff1660c083015260c081015173ffffffffffffffffffffffffffffffffffffffff1660e083015260e0810151611f55610100918285019073ffffffffffffffffffffffffffffffffffffffff169052565b810151610120908184015281015190610140918284015201516101608201520152565b61085d905f610140604051611f8c81610481565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e082015282610100820152826101208201520152611c8c611fed61016083015160208151910120604051928391602083019586611e6d565b519020612a0a565b604051612001816104eb565b5f8152905f368137565b906120158261074f565b6120226040519182610507565b8281527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0612050829461074f565b0190602036910137565b8051916120668361200b565b926120708161200b565b925f5b82811061207f57505050565b8061208c60019284611d8c565b515f52602060cd81526040805f209051906120a682610465565b54906fffffffffffffffffffffffffffffffff82169182825260801c92839101526120d18389611d8c565b526120dc8289611d8c565b5201612073565b156120ea57565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152fd5b600161218060ff825460a81c16612a4b565b5f80547fffffffffffffffffffffffff00000000000000000000000000000000000000001633179055604051906121b682610465565b601b825260207f50656e646c65204c696d6974204f726465722050726f746f636f6c00000000006020840152604051926121ef84610465565b8284527f3100000000000000000000000000000000000000000000000000000000000000602085015261223160ff845460a81c1661222c81612a4b565b612a4b565b80519267ffffffffffffffff8411610460576122578461225260045461327e565b6134f6565b602092601f85116001146122e2575050926122b3836101fd9796946122bb946122d2975f926122d7575b50507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b6004556135d0565b6122c45f600255565b6122cd5f600355565b6129ba565b611a59565b015190505f80612281565b917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0859492951661233460045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b90565b935f905b82821061239f575050926101fd9897959285926122bb966122d2999610612368575b505050811b016004556135d0565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c191690555f808061235a565b808886978294978701518155019601940190612338565b60c08101356123c4816101ce565b73ffffffffffffffffffffffffffffffffffffffff339116036124a6576109e66123ef9136906105fc565b6001612403825f5260cd60205260405f2090565b5460801c14612448576124216117b5825f5260cd60205260405f2090565b337f35ab4a1a0e9bec7fd7ae164679b9cc00e6568e4db238d8055a75b1862f62ec2e5f80a3565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f4c4f503a20616c72656164792066696c6c6564000000000000000000000000006044820152fd5b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f4c4f503a204163636573732064656e69656400000000000000000000000000006044820152fd5b516004811015611d1e5790565b6004821015611d1e5752565b61252990939193612d2e565b918251156125e757612547606061253f85611d7a565b515101612504565b9261255184611e56565b831580156125d4575b156125b2576125aa9461259b91612579612572610555565b9687612511565b602086015273ffffffffffffffffffffffffffffffffffffffff166040850152565b6060830152608082015261314d565b929391929091565b6125aa946125c591612579612572610555565b6060830152608082015261300a565b506125de84611e56565b6002841461255a565b5090506125f4915061370b565b5f9182918291565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b9190820180921161119f57565b9190820391821161119f57565b1561264a57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600b60248201527f6e6f7420616c6c6f7765640000000000000000000000000000000000000000006044820152fd5b90916126d673ffffffffffffffffffffffffffffffffffffffff8060ce5416331490811561181c5750612643565b815190835182036127c8575f5b82811061272457505050907fc3db6554492d97a6a5438d341beeab3232f4f79acc844de8e881ccf16330d31f9161271f60405192839283612916565b0390a1565b8061273160019287611d8c565b51158015906127c1575b61274490612826565b61276166ad566553da1bc36127598389611d8c565b5111156128b1565b61276b8187611d8c565b516127ba61279661277c8489611d8c565b5173ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff165f5260cc60205260405f2090565b55016126e3565b508261273b565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f4c4f503a206c656e677468206d69736d617463680000000000000000000000006044820152fd5b1561282d57565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602860248201527f4c4f503a207a65726f20666565206d75737420626520616c6c6f77656420657860448201527f706c696369746c790000000000000000000000000000000000000000000000006064820152fd5b156128b857565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f4c4f503a2066656520746f6f20686967680000000000000000000000000000006044820152fd5b909291604082019160408152845180935260608101926020809601905f5b8181106129515750505061085d9394506020818403910152610805565b825173ffffffffffffffffffffffffffffffffffffffff1686529487019491870191600101612934565b3d156129a5573d9061298c8261057c565b9161299a6040519384610507565b82523d5f602084013e565b606090565b9190811015611d875760051b0190565b73ffffffffffffffffffffffffffffffffffffffff906129de825f541633146119f4565b167fffffffffffffffffffffffff000000000000000000000000000000000000000060cb54161760cb55565b604290612a15613480565b90604051917f19010000000000000000000000000000000000000000000000000000000000008352600283015260228201522090565b15612a5257565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201527f6e697469616c697a696e670000000000000000000000000000000000000000006064820152fd5b15612add57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f4c4f503a20656d707479206261746368000000000000000000000000000000006044820152fd5b908160209103126101ec575190565b6040513d5f823e3d90fd5b15612b5c57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600f60248201527f4c4f503a205059206578706972656400000000000000000000000000000000006044820152fd5b15612bc157565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f4c4f503a206d69736d61746368207479706573000000000000000000000000006044820152fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811461119f5760010190565b6040515f815261085d816104eb565b90612c658261074f565b604090612c756040519182610507565b8381527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0612ca3829561074f565b01915f5b838110612cb45750505050565b6020908251612cc281610444565b8351612ccd8161049e565b5f815283905f828201525f868201526060905f828201525f60808201525f60a08201525f60c08201525f60e08201525f6101008201525f6101208201525f610140820152816101608201528352818301525f85830152828601015201612ca7565b908151612d3c811515612ad6565b60a0612d6960a0612d4c86611d7a565b5151015173ffffffffffffffffffffffffffffffffffffffff1690565b606091612d7a606061253f88611d7a565b9073ffffffffffffffffffffffffffffffffffffffff80931693604091604051957fe184c9be0000000000000000000000000000000000000000000000000000000087526020968781600481855afa8015612fa057612de2915f91612f73575b504210612b55565b5f955f5b898110612e6a5750505050505050612e01612e069184612636565b612c5b565b935f915f5b848110612e19575050505050565b81612e248285611d8c565b51015151612e35575b600101612e0b565b92612e62600191612e468686611d8c565b51612e51828b611d8c565b52612e5c818a611d8c565b50612c1f565b939050612e2d565b612e74818d611d8c565b51518786820151612e8481611e56565b612e8d82611e56565b612e9681611e56565b1480612f44575b612ea690612bba565b8981015142109081612eed575b5015612ec2575b600101612de6565b96612ece600191612c1f565b978c8a612ee383612edd612c4c565b93611d8c565b5101529050612eba565b9050612f3b612f1760c08984015193015173ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff165f52606660205260405f2090565b5411155f612eb3565b50612ea68484612f6a8885015173ffffffffffffffffffffffffffffffffffffffff1690565b16149050612e9d565b612f939150893d8b11612f99575b612f8b8183610507565b810190612b3b565b5f612dda565b503d612f81565b612b4a565b15612fac57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f4c4f503a206d617854616b696e672065786365656465640000000000000000006044820152fd5b90602082019161301a83516138d9565b61303587949297969396518861302f81611da0565b91613b2e565b80519260208201519561304e6040840197885190612629565b9651978799869b61306560608401518b1115612fa5565b6001835161307281611e56565b61307b81611e56565b036131455750955b888a73ffffffffffffffffffffffffffffffffffffffff93855160408201516130bf9073ffffffffffffffffffffffffffffffffffffffff1690565b9a60808a019b878d519216926130d493613c22565b60800151916130e2936137dd565b973033928516926130f293613c9e565b805160a08401516131039184613d8f565b918860cb546131259073ffffffffffffffffffffffffffffffffffffffff1690565b61312e9261404f565b51935160c08301519260e00151936101fd95614153565b905095613083565b906020820190815161315e906138d9565b959285949291945161317090826142ae565b9686518661317d81611da0565b9061318792613b2e565b9081519860408301998a5161319b91612636565b9860208401519a5198898c9b809d60608c01518111156131ba90612fa5565b60408c01516131e190839073ffffffffffffffffffffffffffffffffffffffff168b61404f565b8260808d0151916131f1936137dd565b99516131fc81611e56565b61320581611e56565b155f1497613262926101fd996132765750965b61324384519860a08901998a519173ffffffffffffffffffffffffffffffffffffffff33911661445e565b60cb5473ffffffffffffffffffffffffffffffffffffffff169061404f565b5193519160e060c085015194015194614153565b905096613218565b90600182811c921680156132c5575b602083101461329857565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b91607f169161328d565b604051905f82600454916132e28361327e565b8083529260209060019081811690811561336c575060011461330d575b50506101fd92500383610507565b91509260045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b935f925b82841061335457506101fd9450505081016020015f806132ff565b85548885018301529485019487945092810192613339565b9050602093506101fd9592507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0091501682840152151560051b8201015f806132ff565b604051905f82600554916133c28361327e565b8083529260209060019081811690811561336c57506001146133ec5750506101fd92500383610507565b91509260055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0935f925b82841061343357506101fd9450505081016020015f806132ff565b85548885018301529485019487945092810192613418565b9060418151145f146134775761347391602082015190606060408401519301515f1a906144da565b9091565b50505f90600290565b613488614562565b6134906145ad565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815260c0810181811067ffffffffffffffff8211176104605760405251902090565b601f8111613502575050565b60045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b906020601f840160051c83019310613559575b601f0160051c01905b81811061354e575050565b5f8155600101613543565b909150819061353a565b601f811161356f575050565b60055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0906020601f840160051c830193106135c6575b601f0160051c01905b8181106135bb575050565b5f81556001016135b0565b90915081906135a7565b90815167ffffffffffffffff8111610460576135f6816135f160055461327e565b613563565b602080601f83116001146136495750819061364493945f926122d75750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b600555565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe083169461369960055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db090565b925f905b8782106136f35750508360019596106136bc575b505050811b01600555565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c191690555f80806136b1565b8060018596829496860151815501950193019061369d565b9060609180516137185750565b6137539192505f90604051809381927feb3a7d4700000000000000000000000000000000000000000000000000000000835260048301610ebe565b038183335af1908115612fa0575f9161376a575090565b90503d805f833e61377b8183610507565b8101906020818303126101ec5780519067ffffffffffffffff82116101ec570181601f820112156101ec5780516137b18161057c565b926137bf6040519485610507565b818452602082840101116101ec5761085d9160208085019101610e5a565b835160609594906137ef575b50505050565b5f9394955061382c9060405195869485947feb3a7d4700000000000000000000000000000000000000000000000000000000865260048601610ee1565b038183335af1908115612fa0575f9161384b575b50905f8080806137e9565b90503d805f833e61385c8183610507565b8101906020818303126101ec5780519067ffffffffffffffff82116101ec570181601f820112156101ec5780516138928161057c565b926138a06040519485610507565b818452602082840101116101ec576138be9160208085019101610e5a565b5f613840565b908160209103126101ec575161085d816101ce565b908151916138e68361200b565b925f5b8181106139e257505060a0612d4c61390092611d7a565b73ffffffffffffffffffffffffffffffffffffffff8116926040517fafd27bf50000000000000000000000000000000000000000000000000000000081526020908181600481895afa908115612fa05760049183915f916139c5575b5096604051928380927fd94073d40000000000000000000000000000000000000000000000000000000082525afa918215612fa0575f9261399c57505092565b6139bb9250803d106139be575b6139b38183610507565b8101906138c4565b92565b503d6139a9565b6139dc9150823d84116139be576139b38183610507565b5f61395c565b80604060016139f2819487611d8c565b51613ace8151613a72613a35613a0e6020938487015190611b8d565b92919890960195613a2e613a238289516145d3565b9889809303016145e5565b92016145e5565b92613a59613a41610562565b6fffffffffffffffffffffffffffffffff9095168552565b8301906fffffffffffffffffffffffffffffffff169052565b613a84855f5260cd60205260405f2090565b815160209092015160801b7fffffffffffffffffffffffffffffffff00000000000000000000000000000000166fffffffffffffffffffffffffffffffff92909216919091179055565b52613ad98288611d8c565b52016138e9565b60405190610100820182811067ffffffffffffffff82111761046057604052606060e0835f81525f60208201525f60408201525f838201528260808201528260a08201528260c08201520152565b919073ffffffffffffffffffffffffffffffffffffffff90613b4e613ae0565b5016604051907fe184c9be0000000000000000000000000000000000000000000000000000000082526020938483600481855afa8015612fa057613b9e86915f958691613c05575b504290612636565b926004604051809681937f1d52edc40000000000000000000000000000000000000000000000000000000083525af1928315612fa05761085d955f94613be6575b5050614667565b613bfd929450803d10612f9957612f8b8183610507565b915f80613bdf565b613c1c9150833d8511612f9957612f8b8183610507565b5f613b96565b90918251935f5b858110613c3857505050505050565b60019060c073ffffffffffffffffffffffffffffffffffffffff8082613c5e858b611d8c565b515101511681871614613c9757613c9191613c79848a611d8c565b515101511685613c898487611d8c565b51918861481a565b01613c29565b5050613c91565b92919082613cac5750505050565b613cb59361481a565b5f8080806137e9565b90670de0b6b3a76400009182810292818404149015171561119f57565b8181029291811591840414171561119f57565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b8115613d25570490565b613cee565b15613d3157565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600e60248201527f4c4f503a206661696c20736166650000000000000000000000000000000000006044820152fd5b909291835190613d9e8261200b565b945f80945b848210613db257505050505050565b608097949697959192939591613dcc83612d4c8688611d8c565b905f5b89821080614032575b15613e0157613df5613dfb91613dee848c611d8c565b5190612629565b91612c1f565b90613dcf565b999897959492939190969980156140295773ffffffffffffffffffffffffffffffffffffffff808316918187168314613fd3576001613e40878c612636565b03613ef557505050613e6f9150613e5c60e0612d4c8588611d8c565b9084613e688589611d8c565b519261493f565b613e79828a611d8c565b525b848110613e8e57505b8390949394613da3565b80613eaa613e9e60019386611d8c565b51516130859051061590565b613eb5575b01613e7b565b613ef0613ec28287611d8c565b51613ee9613ed0848d611d8c565b5191610140613edf868a611d8c565b5151015190614d61565b1115613d2a565b613eaf565b613f018185893061493f565b8d89888c8e5b8210613f1c5750505050505050505050613e7b565b81868682938d613f2c8589611d8c565b5151015173ffffffffffffffffffffffffffffffffffffffff1693613f5091611d8c565b5190613f5b91613cdb565b90613f6591613d1b565b613f6f8387611d8c565b52898186848b83168d141597613fac96613f9b9560e095612d4c9560019c613fb6575b50505050611d8c565b613fa58487611d8c565b519161404f565b018a908c8e613f07565b613fca93613fc391611d8c565b5191614cb5565b818f878c613f92565b50505050505b848110613fe65750613e84565b8061400d613ffb60e0612d4c60019588611d8c565b6140058388611d8c565b51908561404f565b6140178186611d8c565b51614022828b611d8c565b5201613fd9565b50505050613e84565b5061404a61404486612d4c858b611d8c565b8461487f565b613dd8565b821561414e5773ffffffffffffffffffffffffffffffffffffffff16806140e757505f80809381935af161408161297b565b501561408957565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600f60248201527f6574682073656e64206661696c656400000000000000000000000000000000006044820152fd5b6040517fa9059cbb00000000000000000000000000000000000000000000000000000000602082015273ffffffffffffffffffffffffffffffffffffffff9290921660248301526044808301939093529181526101fd91614149606483610507565b614ff1565b505050565b91939490948551955f5b87811061416e575050505050505050565b80878782808080808c8c8c8c6141848585611d8c565b51519761419091611d8c565b519860608801519a6141a18c611e56565b60a089015173ffffffffffffffffffffffffffffffffffffffff1660809099015173ffffffffffffffffffffffffffffffffffffffff16976141e291611d8c565b51956141ed91611d8c565b519a6141f891611d8c565b519661420391611d8c565b519161420e91611d8c565b515160c0015173ffffffffffffffffffffffffffffffffffffffff169061423488611e56565b6040805173ffffffffffffffffffffffffffffffffffffffff958616815260208101949094528301989098526060820194909452608081019690965291821660a08601523360c086015216927f338aa396bce529256f46f1d51f463cc5be80195004e47cf0a1527507d38404479060e090a460010161415d565b91909182516142bc8161200b565b935f90815b8381106142cf575050505050565b60809694969593959291926142e881612d4c8487611d8c565b945f935b8881108061442f575b15614363578061434061431060c0612d4c61435e958b611d8c565b9661432c60409889614322868d611d8c565b510151908c614d78565b87614337848b611d8c565b51015190612629565b9561434b8289611d8c565b510151614358828b611d8c565b52612c1f565b6142ec565b9590979493915097959773ffffffffffffffffffffffffffffffffffffffff808816908216148015614427575b61441f578161439f9188614e14565b915b8581106143b4575050505b8291926142c1565b6001906040806143c48388611d8c565b510151906143db856143d68885613cdb565b613d1b565b91826143ea613e9e868b611d8c565b614404575b50506143fb8388611d8c565b510152016143a1565b613ee961441892610140613edf888d611d8c565b5f826143ef565b5050506143ac565b508115614390565b5061443e83612d4c8389611d8c565b73ffffffffffffffffffffffffffffffffffffffff8089169116146142f5565b90928251935f5b85811061447457505050505050565b60019060e073ffffffffffffffffffffffffffffffffffffffff808261449a858b611d8c565b5151015116818616146144d3576144cd916144b5848a611d8c565b51510151166144c48387611d8c565b5190858861481a565b01614465565b50506144cd565b7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411614557576020935f9360ff60809460405194855216868401526040830152606082015282805260015afa15612fa0575f5173ffffffffffffffffffffffffffffffffffffffff81161561454f57905f90565b505f90600190565b505050505f90600390565b61456a6132cf565b805190811561457a576020012090565b505060025480156145885790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b6145b56133af565b80519081156145c5576020012090565b505060035480156145885790565b90808210156145e0575090565b905090565b6fffffffffffffffffffffffffffffffff908181116101ec571690565b1561460957565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f4c4f503a2063616e27742073776170203020616d6f756e7400000000000000006044820152fd5b9392909193614674613ae0565b948151936146818561200b565b608088015261468f8561200b565b60a088015261469d8561200b565b60c08801526146ab8561200b565b60e08801526146d86146d3826146cd6146c8606061253f89611d7a565b614f97565b96615410565b614fe7565b925f94602089019060408a01928a60608101985b8a8110614700575050505050505050505050565b8888826001946147108288611d8c565b51908860408301928d84511561480d57614802976147d69760e09688956147436147699561012061479098510151614fdd565b91516147538860808b0151611d8c565b526147628760808a0151611d8c565b5190615ad5565b9061478a8560a08897959701519360c08901519061478a838c8c0151611d8c565b52611d8c565b526147aa6147a28460a0840151611d8c565b511515614602565b6147c36147bb846080840151611d8c565b518251612629565b81526147de6147d68460a0840151611d8c565b518b51612629565b8a526147f96147f18460c0840151611d8c565b518c51612629565b8b520151611d8c565b8a525b018b906146ec565b5050505050505050614805565b90926101fd93604051937f23b872dd00000000000000000000000000000000000000000000000000000000602086015273ffffffffffffffffffffffffffffffffffffffff8092166024860152166044840152606483015260648252614149826104cf565b73ffffffffffffffffffffffffffffffffffffffff8080931691168181149283156148ef575b83156148b2575b50505090565b7f000000000000000000000000000000000000000000000000000000000000000016149150816148e6575b505f80806148ac565b9050155f6148dd565b92508015806148ff575b926148a5565b50827f00000000000000000000000000000000000000000000000000000000000000001682146148f9565b908160209103126101ec575161085d8161020a565b73ffffffffffffffffffffffffffffffffffffffff8381169594928615808015614bc4575b15614b1a5715614b1257817f0000000000000000000000000000000000000000000000000000000000000000915b6040517f784367d600000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff881660048201526020969290911692918682602481875afa928315612fa057614a729388935f91614ae5575b5015614add5750879384915b5f6040518096819582947f769f8e5d00000000000000000000000000000000000000000000000000000000845230600485016080915f93959460a083019673ffffffffffffffffffffffffffffffffffffffff809316845260208401521660408201528260608201520152565b03925af1948515612fa0575f95614abe575b50508385819884841603614aad575b5050503090821603614aa457505050565b6101fd9261404f565b614ab692614cb5565b5f8385614a93565b614ad5929550803d10612f9957612f8b8183610507565b925f80614a84565b938491614a05565b614b059150843d8611614b0b575b614afd8183610507565b81019061492a565b5f6149f9565b503d614af3565b815f91614992565b5091614b9595965060209493915f91604051978896879586937f769f8e5d000000000000000000000000000000000000000000000000000000008552600485016080915f93959460a083019673ffffffffffffffffffffffffffffffffffffffff809316845260208401521660408201528260608201520152565b0393165af1908115612fa0575f91614bab575090565b61085d915060203d602011612f9957612f8b8183610507565b50827f0000000000000000000000000000000000000000000000000000000000000000168814614964565b73ffffffffffffffffffffffffffffffffffffffff1680614c6357505f3b156101ec575f600491604051928380927fd0e30db0000000000000000000000000000000000000000000000000000000008252845af18015612fa057614c505750565b80614c5d6101fd926104bb565b80610a0c565b803b156101ec576040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815260048101929092525f908290818381602481015b03925af18015612fa057614c505750565b73ffffffffffffffffffffffffffffffffffffffff9190821680614d19575016803b156101ec575f906004604051809481937fd0e30db00000000000000000000000000000000000000000000000000000000083525af18015612fa057614c505750565b915050803b156101ec576040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815260048101929092525f90829081838160248101614ca4565b670de0b6b3a764000091614d7491613cdb565b0490565b90919073ffffffffffffffffffffffffffffffffffffffff1680614dff575090503403614da157565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f657468206d69736d6174636800000000000000000000000000000000000000006044820152fd5b81614e0957505050565b6101fd92309161481a565b7f0000000000000000000000000000000000000000000000000000000000000000929173ffffffffffffffffffffffffffffffffffffffff8082168186161480614f01575b9084614b9596602096959493614eed575b5050614e768383615110565b818116614ee65783905b6040518097819682957f20e8c56500000000000000000000000000000000000000000000000000000000845230600485015f929493606092608083019673ffffffffffffffffffffffffffffffffffffffff809216845216602083015260408201520152565b5f90614e80565b614ef8929350614bef565b5f90835f614e6a565b506040517ffa5a4f0600000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff86166004820152939291906020856024818487165afa948515612fa057614b959660209686925f91614f7a575b5015929394955096509450614e59565b614f919150883d8a11614b0b57614afd8183610507565b5f614f6a565b6004811015611d1e5780614fab5750600190565b614fb481611e56565b60018103614fc25750600290565b80614fce600292611e56565b03614fd857600390565b600490565b90614fe791615410565b5f81126101ec5790565b60405161505b9173ffffffffffffffffffffffffffffffffffffffff1661501782610465565b5f806020958685527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656487860152868151910182855af161505561297b565b916159dc565b8051908282159283156150f8575b505050156150745750565b608490604051907f08c379a00000000000000000000000000000000000000000000000000000000082526004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152fd5b615108935082018101910161492a565b5f8281615069565b919073ffffffffffffffffffffffffffffffffffffffff928381169384156152d1576040519485917fdd62ed3e0000000000000000000000000000000000000000000000000000000083523060048401528416602483015281604460209788935afa8015612fa0576b7fffffffffffffffffffffff915f916152b4575b501061519a575b50509050565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000085820190815273ffffffffffffffffffffffffffffffffffffffff841660248301525f60448301819052918291906151f98160648101611c8c565b519082855af161520761297b565b81615284575b50156152265761521e929350615450565b805f80615194565b606484604051907f08c379a00000000000000000000000000000000000000000000000000000000082526004820152600c60248201527f5361666520417070726f766500000000000000000000000000000000000000006044820152fd5b8051801592508690831561529c575b5050505f61520d565b6152ac935082018101910161492a565b5f8581615293565b6152cb9150863d8811612f9957612f8b8183610507565b5f61518d565b5050509050565b929391937ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000948583019280841161119f57670de0b6b3a764000061531f6153259388613cdb565b04613cdb565b8215613d255782900494810190811161119f5781615346614d749286613cdb565b0493613cbe565b61535c90949394929192613cbe565b918015613d255761536e920490615579565b917ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000810190811161119f576153ac670de0b6b3a76400009184613cdb565b04908290565b92939161531f916153cf91670de0b6b3a764000093849187613cdb565b04927ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000810181811161119f576154059084613cdb565b8115613d2557049190565b6301e133809161541f91613cdb565b047f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81116101ec5761085d90615602565b6040517f095ea7b3000000000000000000000000000000000000000000000000000000006020820190815273ffffffffffffffffffffffffffffffffffffffff90931660248201527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60448201525f9283929183906154d28160648101611c8c565b51925af16154de61297b565b8161554a575b50156154ec57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f5361666520417070726f766500000000000000000000000000000000000000006044820152fd5b805180159250821561555f575b50505f6154e4565b615572925060208091830101910161492a565b5f80615557565b90613d1b90613cbe565b1561558a57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c6964206578706f6e656e74000000000000000000000000000000006044820152fd5b8015613d25576ec097ce7bc90715b34b9f10000000000590565b7ffffffffffffffffffffffffffffffffffffffffffffffffdc702bd3a30fc0000811215806159c9575b61563590615583565b5f81126159b5576064906806f05b59d3b20000008112615952577ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e0000000168056bc75e2d6310000082770195e54c5dd42177f53a27172fa9ec630262827000000000925b02819068ad78ebc5ac62000000811215615919575b6856bc75e2d6310000008112156158df575b682b5e3af16b188000008112156158a7575b6815af1d78b58c40000081121561586f575b680ad78ebc5ac6200000811215615838575b82811215615801575b6802b5e3af16b18800008112156157ca575b68015af1d78b58c40000811215615793575b60028382800205058360038184840205056004828583020505600583868302050560068487830205056007858883020505906008868984020505926009878a8602050594600a888b8802050596600b898c8a02050599600c8a8d8d0205059b0101010101010101010101010205020590565b6806f5f17757889379377ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000084920192020590615721565b6808f00f760a4b2db55d7ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800008492019202059061570f565b680ebc5fb417461211107ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf00000849201920205906156fd565b68280e60114edb805d037ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e00000849201920205906156f4565b690127fa27722cc06cc5e27fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00000849201920205906156e2565b693f1fce3da636ea5cf8507fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800000849201920205906156d0565b6b02df0ab5a80a22c61ab5a7007fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000000849201920205906156be565b6e01855144814a7ff805980ff008400091507fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000000016156ac565b6803782dace9d900000081126159a2577ffffffffffffffffffffffffffffffffffffffffffffffffc87d25316270000000168056bc75e2d63100000826b1425982cf597cd205cef738092615697565b68056bc75e2d6310000082600192615697565b6159c0905f03615602565b61085d906155e8565b5068070c1cc73b00c8000081131561562c565b91929015615a5757508151156159f0575090565b3b156159f95790565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152fd5b825190915015615a6a5750805190602001fd5b6115a4906040519182917f08c379a0000000000000000000000000000000000000000000000000000000008352602060048401526024830190610e7b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52605160045260245ffd5b939291909380600414615b1d5780600314615b135780600214615b0957600103615aa857615b02936153b2565b9192909190565b50615b029361534d565b50615b02936152d8565b507ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c00009492919394938482019582871161119f5786615b5a91613cdb565b918015613d2557615b6c920490615579565b92810181811161119f57615b809084613cdb565b8115613d25570492670de0b6b3a76400009384810294818604149015171561119f578015613d2557615bb5816143d685613cbe565b929304919056fea2646970667358221220b522fa078c5f8ec0eaf741819c6dd9192cc3b341b3301883713488522331de3764736f6c6343000818003300000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8

Deployed Bytecode

0x6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c8063078dfbe7146101c95780630b4e3350146101c45780630c0b8c9c146101bf5780632545e4bd146101ba57806332707597146101b557806335ee3ffc146101b05780633644e515146101ab57806346904840146101a6578063485cc955146101a15780634e71e0c81461019c5780635413fba7146101975780635d436b7e146101925780636122b1731461018d57806370ae92d21461018857806372c244a81461018357806384b0196e1461017e5780638da5cb5b1461017957806397cf58b014610174578063b381cf401461016f578063bd61951d1461016a578063c53a029214610165578063cf6fc6e314610160578063d74a3eca1461015b578063e30c397814610156578063e74b981b14610151578063f1d4deb31461014c5763f34c010c0361000e57611967565b611907565b61187a565b611829565b611712565b61163c565b6115a8565b6114eb565b61147d565b6113aa565b6112fa565b611229565b6110f5565b61108e565b610f04565b610ddb565b610d7f565b610c3d565b610a9f565b610a4e565b610a16565b6109eb565b610992565b610945565b610860565b6106c7565b610221565b73ffffffffffffffffffffffffffffffffffffffff8116036101ec57565b5f80fd5b602435906101fd826101ce565b565b35906101fd826101ce565b801515036101ec57565b604435906101fd8261020a565b346101ec5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043561025c816101ce565b602435906102698261020a565b604435916102768361020a565b73ffffffffffffffffffffffffffffffffffffffff9061029a825f541633146119f4565b156103e7578116918215908115916103df575b501561038157610354916102f16102d85f5473ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff1690565b7f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000005f5416175f55565b6100187fffffffffffffffffffffffff000000000000000000000000000000000000000060015416600155565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4f776e61626c653a207a65726f206164647265737300000000000000000000006044820152fd5b90505f6102ad565b9150167fffffffffffffffffffffffff000000000000000000000000000000000000000060015416176001555f80f35b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6060810190811067ffffffffffffffff82111761046057604052565b610417565b6040810190811067ffffffffffffffff82111761046057604052565b610160810190811067ffffffffffffffff82111761046057604052565b610180810190811067ffffffffffffffff82111761046057604052565b67ffffffffffffffff811161046057604052565b60a0810190811067ffffffffffffffff82111761046057604052565b6020810190811067ffffffffffffffff82111761046057604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761046057604052565b604051906101fd8261049e565b604051906101fd826104cf565b604051906101fd82610465565b359060048210156101ec57565b67ffffffffffffffff811161046057601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b81601f820112156101ec578035906105cd8261057c565b926105db6040519485610507565b828452602083830101116101ec57815f926020809301838601378301015290565b9190610180838203126101ec57610611610548565b928035845260208101356020850152604081013560408501526106366060820161056f565b6060850152610647608082016101ff565b608085015261065860a082016101ff565b60a085015261066960c082016101ff565b60c085015261067a60e082016101ff565b60e0850152610100808201359085015261012080820135908501526101408082013590850152610160918282013567ffffffffffffffff81116101ec576106c192016105b6565b90830152565b346101ec5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5767ffffffffffffffff6004358181116101ec576107179036906004016105fc565b906024359081116101ec5760609161073661073c9236906004016105b6565b90611b8d565b9060405192835260208301526040820152f35b67ffffffffffffffff81116104605760051b60200190565b6020807ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126101ec576004359167ffffffffffffffff83116101ec57806023840112156101ec5782600401356107be8161074f565b936107cc6040519586610507565b8185526024602086019260051b8201019283116101ec57602401905b8282106107f6575050505090565b813581529083019083016107e8565b9081518082526020808093019301915f5b828110610824575050505090565b835185529381019392810192600101610816565b909161084f61085d93604084526040840190610805565b916020818403910152610805565b90565b346101ec5761087661087136610767565b61205a565b5f5b82518110156109305761088b8184611d8c565b51156108d257807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6108bf60019386611d8c565b51016108cb8286611d8c565b5201610878565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f4c4f503a20556e6b6e6f776e206f7264657200000000000000000000000000006044820152fd5b509061094160405192839283610838565b0390f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602061098a600435610985816101ce565b611da0565b604051908152f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043567ffffffffffffffff81116101ec5761098a6109e660209236906004016105fc565b611f78565b346101ec576109fc61087136610767565b9061094160405192839283610838565b5f9103126101ec57565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602061098a613480565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff60cb5416604051908152f35b346101ec5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57600435610ada816101ce565b610b5c602435610ae9816101ce565b60015492610b0e60ff8560a81c161580958196610c2b575b8115610c08575b506120e3565b83610b53740100000000000000000000000000000000000000007fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff6001541617600155565b610bbe5761216e565b610b6257005b610b8f7fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff60015416600155565b604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602090a1005b610c0375010000000000000000000000000000000000000000007fffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffffff6001541617600155565b61216e565b303b15915081610c1a575b505f610b08565b60a01c60ff1660011490505f610c13565b9050600160ff8260a01c161090610b01565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5773ffffffffffffffffffffffffffffffffffffffff8060015416803303610d215780610cf7925f54167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000005f5416175f55565b600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055005b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f4f776e61626c653a2063616c6c657220213d2070656e64696e67206f776e65726044820152fd5b346101ec577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc6020813601126101ec576004359067ffffffffffffffff82116101ec576101809082360301126101ec57610018906004016123b6565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff60ce5416604051908152f35b9181601f840112156101ec5782359167ffffffffffffffff83116101ec57602083818601950101116101ec57565b5f5b838110610e6b5750505f910152565b8181015183820152602001610e5c565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f602093610eb781518092818752878088019101610e5a565b0116010190565b90608061085d925f81525f60208201525f60408201528160608201520190610e7b565b909260809261085d95948352602083015260408201528160608201520190610e7b565b346101ec5760a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043567ffffffffffffffff8082116101ec57366023830112156101ec578160040135602492610f628261074f565b93604092610f736040519687610507565b8086526020936024602088019260051b850101933685116101ec5760248101925b858410610ff8578888610fa56101f0565b6064358281116101ec57610fbd903690600401610e2c565b50506084359182116101ec5761094192610fde610fe89336906004016105b6565b916044359161251d565b9060409492945194859485610ee1565b83358881116101ec57820160607fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc82360301126101ec5783519161103b83610444565b868201358a81116101ec57611055908836918501016105fc565b83526044820135928a84116101ec5760648a949361107986958b36918401016105b6565b85840152013586820152815201930192610f94565b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5773ffffffffffffffffffffffffffffffffffffffff6004356110de816101ce565b165f526066602052602060405f2054604051908152f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760043560ff81168091036101ec57335f52606660205260405f20549080820180921161119f57335f5260666020528160405f205581039080821161119f5760408051928352602083019190915233917fdc0537f71d06d3708f52baf4ddf6918b25f1a145ba08873de27485682b35cac191819081015b0390a2005b6125fc565b919361120a61085d9694956111fc73ffffffffffffffffffffffffffffffffffffffff947f0f00000000000000000000000000000000000000000000000000000000000000875260e0602088015260e0870190610e7b565b908582036040870152610e7b565b9460608401521660808201525f60a082015260c0818403910152610805565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5760025415806112f0575b156112925761126e6132cf565b6112766133af565b90610941611282611ff5565b60405193849330914691866111a4565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4549503731323a20556e696e697469616c697a656400000000000000000000006044820152fd5b5060035415611261565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff5f5416604051908152f35b9080601f830112156101ec5760209082356113648161074f565b936113726040519586610507565b81855260208086019260051b8201019283116101ec57602001905b82821061139b575050505090565b8135815290830190830161138d565b346101ec5760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5767ffffffffffffffff6004358181116101ec57366023820112156101ec5780600401356114058161074f565b916114136040519384610507565b8183526020916024602085019160051b830101913683116101ec57602401905b82821061146457602435858782116101ec5761145661001892369060040161134a565b61145e610214565b916126a8565b8380918335611472816101ce565b815201910190611433565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602060405173ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8168152f35b60407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57600435611521816101ce565b60243567ffffffffffffffff81116101ec575f9161154483923690600401610e2c565b90816040519283928337810184815203915af461155f61297b565b906115a46040519283927f1934afc800000000000000000000000000000000000000000000000000000000845215156004840152604060248401526044830190610e7b565b0390fd5b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57335f52606660205260405f20546001810180821161119f5761119a7fdc0537f71d06d3708f52baf4ddf6918b25f1a145ba08873de27485682b35cac191335f5260666020528060405f205560405191829133958360209093929193604081019481520152565b346101ec5760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec5773ffffffffffffffffffffffffffffffffffffffff60043561168c816101ce565b165f526066602052602060243560405f205414604051908152f35b9060207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8301126101ec5760043567ffffffffffffffff928382116101ec57806023830112156101ec5781600401359384116101ec5760248460051b830101116101ec576024019190565b346101ec57611720366116a7565b9061174e73ffffffffffffffffffffffffffffffffffffffff8060ce5416331490811561181c575b50612643565b5f5b82811061175957005b8061176760019285856129aa565b355f5260cd6020528161179060405f205460801c6fffffffffffffffffffffffffffffffff1690565b14611817576117e06117b56117a68387876129aa565b355f5260cd60205260405f2090565b7001000000000000000000000000000000006fffffffffffffffffffffffffffffffff825416179055565b6117eb8185856129aa565b357f7e764b5c87bad409a763c11635251284e519d7bbd042eef277b3529e212c25465f80a25b01611750565b611811565b90505f541633145f611748565b346101ec575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec57602073ffffffffffffffffffffffffffffffffffffffff60015416604051908152f35b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec576004356118b5816101ce565b73ffffffffffffffffffffffffffffffffffffffff906118d9825f541633146119f4565b167fffffffffffffffffffffffff000000000000000000000000000000000000000060cb54161760cb555f80f35b346101ec57611915366116a7565b5f5b81811061192057005b8060051b830135907ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe81843603018212156101ec5761196160019285016123b6565b01611917565b346101ec5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101ec576004356119a2816101ce565b73ffffffffffffffffffffffffffffffffffffffff906119c6825f541633146119f4565b167fffffffffffffffffffffffff000000000000000000000000000000000000000060ce54161760ce555f80f35b156119fb57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b73ffffffffffffffffffffffffffffffffffffffff90815f541691611a7f8333146119f4565b81168015801590611b21575b1561038157611af7927f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a373ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000005f5416175f55565b7fffffffffffffffffffffffff000000000000000000000000000000000000000060015416600155565b505f611a8b565b15611b2f57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f4c4f503a20626164207369676e617475726500000000000000000000000000006044820152fd5b91611b9783611f78565b92835f5260209060cd825260405f20938260405195611bb587610465565b54956fffffffffffffffffffffffffffffffff87169687825260801c918291015280155f14611d23575073ffffffffffffffffffffffffffffffffffffffff928360c084015116611c06838961344b565b9390956005851015611d1e578994159687611d12575b50508515611c3b575b50505050611c3561010092611b28565b01519190565b5f92939550908291604051611cb881611c8c888201947f1626ba7e000000000000000000000000000000000000000000000000000000009b8c87526024840152604060448401526064830190610e7b565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08101835282610507565b51915afa92611cc561297b565b9084611d05575b84611ce3575b505050611c3561010086915f611c25565b9091809450828051810103126101ec5761010093611c3592015114925f611cd2565b9350818151101593611ccc565b16821495505f80611c1c565b611e29565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01949392505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b805115611d875760200190565b611d4d565b8051821015611d875760209160051b010190565b73ffffffffffffffffffffffffffffffffffffffff165f5260cc60205260405f2054908115611dcb57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f4c4f503a20666565206e6f7420736574000000000000000000000000000000006044820152fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b60041115611d1e57565b906004821015611d1e5752565b61018090939291936101a08101947f22742a2f8610a2d0e945db84f408aacc9d3081f99974bc30b023966fa2fd59318252805160208301526020810151604083015260408101516060830152611ecb60608201516080840190611e60565b608081015173ffffffffffffffffffffffffffffffffffffffff1660a083015260a081015173ffffffffffffffffffffffffffffffffffffffff1660c083015260c081015173ffffffffffffffffffffffffffffffffffffffff1660e083015260e0810151611f55610100918285019073ffffffffffffffffffffffffffffffffffffffff169052565b810151610120908184015281015190610140918284015201516101608201520152565b61085d905f610140604051611f8c81610481565b8281528260208201528260408201528260608201528260808201528260a08201528260c08201528260e082015282610100820152826101208201520152611c8c611fed61016083015160208151910120604051928391602083019586611e6d565b519020612a0a565b604051612001816104eb565b5f8152905f368137565b906120158261074f565b6120226040519182610507565b8281527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0612050829461074f565b0190602036910137565b8051916120668361200b565b926120708161200b565b925f5b82811061207f57505050565b8061208c60019284611d8c565b515f52602060cd81526040805f209051906120a682610465565b54906fffffffffffffffffffffffffffffffff82169182825260801c92839101526120d18389611d8c565b526120dc8289611d8c565b5201612073565b156120ea57565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201527f647920696e697469616c697a65640000000000000000000000000000000000006064820152fd5b600161218060ff825460a81c16612a4b565b5f80547fffffffffffffffffffffffff00000000000000000000000000000000000000001633179055604051906121b682610465565b601b825260207f50656e646c65204c696d6974204f726465722050726f746f636f6c00000000006020840152604051926121ef84610465565b8284527f3100000000000000000000000000000000000000000000000000000000000000602085015261223160ff845460a81c1661222c81612a4b565b612a4b565b80519267ffffffffffffffff8411610460576122578461225260045461327e565b6134f6565b602092601f85116001146122e2575050926122b3836101fd9796946122bb946122d2975f926122d7575b50507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b6004556135d0565b6122c45f600255565b6122cd5f600355565b6129ba565b611a59565b015190505f80612281565b917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0859492951661233460045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b90565b935f905b82821061239f575050926101fd9897959285926122bb966122d2999610612368575b505050811b016004556135d0565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c191690555f808061235a565b808886978294978701518155019601940190612338565b60c08101356123c4816101ce565b73ffffffffffffffffffffffffffffffffffffffff339116036124a6576109e66123ef9136906105fc565b6001612403825f5260cd60205260405f2090565b5460801c14612448576124216117b5825f5260cd60205260405f2090565b337f35ab4a1a0e9bec7fd7ae164679b9cc00e6568e4db238d8055a75b1862f62ec2e5f80a3565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f4c4f503a20616c72656164792066696c6c6564000000000000000000000000006044820152fd5b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f4c4f503a204163636573732064656e69656400000000000000000000000000006044820152fd5b516004811015611d1e5790565b6004821015611d1e5752565b61252990939193612d2e565b918251156125e757612547606061253f85611d7a565b515101612504565b9261255184611e56565b831580156125d4575b156125b2576125aa9461259b91612579612572610555565b9687612511565b602086015273ffffffffffffffffffffffffffffffffffffffff166040850152565b6060830152608082015261314d565b929391929091565b6125aa946125c591612579612572610555565b6060830152608082015261300a565b506125de84611e56565b6002841461255a565b5090506125f4915061370b565b5f9182918291565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b9190820180921161119f57565b9190820391821161119f57565b1561264a57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600b60248201527f6e6f7420616c6c6f7765640000000000000000000000000000000000000000006044820152fd5b90916126d673ffffffffffffffffffffffffffffffffffffffff8060ce5416331490811561181c5750612643565b815190835182036127c8575f5b82811061272457505050907fc3db6554492d97a6a5438d341beeab3232f4f79acc844de8e881ccf16330d31f9161271f60405192839283612916565b0390a1565b8061273160019287611d8c565b51158015906127c1575b61274490612826565b61276166ad566553da1bc36127598389611d8c565b5111156128b1565b61276b8187611d8c565b516127ba61279661277c8489611d8c565b5173ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff165f5260cc60205260405f2090565b55016126e3565b508261273b565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f4c4f503a206c656e677468206d69736d617463680000000000000000000000006044820152fd5b1561282d57565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602860248201527f4c4f503a207a65726f20666565206d75737420626520616c6c6f77656420657860448201527f706c696369746c790000000000000000000000000000000000000000000000006064820152fd5b156128b857565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f4c4f503a2066656520746f6f20686967680000000000000000000000000000006044820152fd5b909291604082019160408152845180935260608101926020809601905f5b8181106129515750505061085d9394506020818403910152610805565b825173ffffffffffffffffffffffffffffffffffffffff1686529487019491870191600101612934565b3d156129a5573d9061298c8261057c565b9161299a6040519384610507565b82523d5f602084013e565b606090565b9190811015611d875760051b0190565b73ffffffffffffffffffffffffffffffffffffffff906129de825f541633146119f4565b167fffffffffffffffffffffffff000000000000000000000000000000000000000060cb54161760cb55565b604290612a15613480565b90604051917f19010000000000000000000000000000000000000000000000000000000000008352600283015260228201522090565b15612a5257565b60846040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201527f6e697469616c697a696e670000000000000000000000000000000000000000006064820152fd5b15612add57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f4c4f503a20656d707479206261746368000000000000000000000000000000006044820152fd5b908160209103126101ec575190565b6040513d5f823e3d90fd5b15612b5c57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600f60248201527f4c4f503a205059206578706972656400000000000000000000000000000000006044820152fd5b15612bc157565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f4c4f503a206d69736d61746368207479706573000000000000000000000000006044820152fd5b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811461119f5760010190565b6040515f815261085d816104eb565b90612c658261074f565b604090612c756040519182610507565b8381527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0612ca3829561074f565b01915f5b838110612cb45750505050565b6020908251612cc281610444565b8351612ccd8161049e565b5f815283905f828201525f868201526060905f828201525f60808201525f60a08201525f60c08201525f60e08201525f6101008201525f6101208201525f610140820152816101608201528352818301525f85830152828601015201612ca7565b908151612d3c811515612ad6565b60a0612d6960a0612d4c86611d7a565b5151015173ffffffffffffffffffffffffffffffffffffffff1690565b606091612d7a606061253f88611d7a565b9073ffffffffffffffffffffffffffffffffffffffff80931693604091604051957fe184c9be0000000000000000000000000000000000000000000000000000000087526020968781600481855afa8015612fa057612de2915f91612f73575b504210612b55565b5f955f5b898110612e6a5750505050505050612e01612e069184612636565b612c5b565b935f915f5b848110612e19575050505050565b81612e248285611d8c565b51015151612e35575b600101612e0b565b92612e62600191612e468686611d8c565b51612e51828b611d8c565b52612e5c818a611d8c565b50612c1f565b939050612e2d565b612e74818d611d8c565b51518786820151612e8481611e56565b612e8d82611e56565b612e9681611e56565b1480612f44575b612ea690612bba565b8981015142109081612eed575b5015612ec2575b600101612de6565b96612ece600191612c1f565b978c8a612ee383612edd612c4c565b93611d8c565b5101529050612eba565b9050612f3b612f1760c08984015193015173ffffffffffffffffffffffffffffffffffffffff1690565b73ffffffffffffffffffffffffffffffffffffffff165f52606660205260405f2090565b5411155f612eb3565b50612ea68484612f6a8885015173ffffffffffffffffffffffffffffffffffffffff1690565b16149050612e9d565b612f939150893d8b11612f99575b612f8b8183610507565b810190612b3b565b5f612dda565b503d612f81565b612b4a565b15612fac57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f4c4f503a206d617854616b696e672065786365656465640000000000000000006044820152fd5b90602082019161301a83516138d9565b61303587949297969396518861302f81611da0565b91613b2e565b80519260208201519561304e6040840197885190612629565b9651978799869b61306560608401518b1115612fa5565b6001835161307281611e56565b61307b81611e56565b036131455750955b888a73ffffffffffffffffffffffffffffffffffffffff93855160408201516130bf9073ffffffffffffffffffffffffffffffffffffffff1690565b9a60808a019b878d519216926130d493613c22565b60800151916130e2936137dd565b973033928516926130f293613c9e565b805160a08401516131039184613d8f565b918860cb546131259073ffffffffffffffffffffffffffffffffffffffff1690565b61312e9261404f565b51935160c08301519260e00151936101fd95614153565b905095613083565b906020820190815161315e906138d9565b959285949291945161317090826142ae565b9686518661317d81611da0565b9061318792613b2e565b9081519860408301998a5161319b91612636565b9860208401519a5198898c9b809d60608c01518111156131ba90612fa5565b60408c01516131e190839073ffffffffffffffffffffffffffffffffffffffff168b61404f565b8260808d0151916131f1936137dd565b99516131fc81611e56565b61320581611e56565b155f1497613262926101fd996132765750965b61324384519860a08901998a519173ffffffffffffffffffffffffffffffffffffffff33911661445e565b60cb5473ffffffffffffffffffffffffffffffffffffffff169061404f565b5193519160e060c085015194015194614153565b905096613218565b90600182811c921680156132c5575b602083101461329857565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b91607f169161328d565b604051905f82600454916132e28361327e565b8083529260209060019081811690811561336c575060011461330d575b50506101fd92500383610507565b91509260045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b935f925b82841061335457506101fd9450505081016020015f806132ff565b85548885018301529485019487945092810192613339565b9050602093506101fd9592507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0091501682840152151560051b8201015f806132ff565b604051905f82600554916133c28361327e565b8083529260209060019081811690811561336c57506001146133ec5750506101fd92500383610507565b91509260055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0935f925b82841061343357506101fd9450505081016020015f806132ff565b85548885018301529485019487945092810192613418565b9060418151145f146134775761347391602082015190606060408401519301515f1a906144da565b9091565b50505f90600290565b613488614562565b6134906145ad565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815260c0810181811067ffffffffffffffff8211176104605760405251902090565b601f8111613502575050565b60045f527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b906020601f840160051c83019310613559575b601f0160051c01905b81811061354e575050565b5f8155600101613543565b909150819061353a565b601f811161356f575050565b60055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0906020601f840160051c830193106135c6575b601f0160051c01905b8181106135bb575050565b5f81556001016135b0565b90915081906135a7565b90815167ffffffffffffffff8111610460576135f6816135f160055461327e565b613563565b602080601f83116001146136495750819061364493945f926122d75750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8260011b9260031b1c19161790565b600555565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe083169461369960055f527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db090565b925f905b8782106136f35750508360019596106136bc575b505050811b01600555565b01517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60f88460031b161c191690555f80806136b1565b8060018596829496860151815501950193019061369d565b9060609180516137185750565b6137539192505f90604051809381927feb3a7d4700000000000000000000000000000000000000000000000000000000835260048301610ebe565b038183335af1908115612fa0575f9161376a575090565b90503d805f833e61377b8183610507565b8101906020818303126101ec5780519067ffffffffffffffff82116101ec570181601f820112156101ec5780516137b18161057c565b926137bf6040519485610507565b818452602082840101116101ec5761085d9160208085019101610e5a565b835160609594906137ef575b50505050565b5f9394955061382c9060405195869485947feb3a7d4700000000000000000000000000000000000000000000000000000000865260048601610ee1565b038183335af1908115612fa0575f9161384b575b50905f8080806137e9565b90503d805f833e61385c8183610507565b8101906020818303126101ec5780519067ffffffffffffffff82116101ec570181601f820112156101ec5780516138928161057c565b926138a06040519485610507565b818452602082840101116101ec576138be9160208085019101610e5a565b5f613840565b908160209103126101ec575161085d816101ce565b908151916138e68361200b565b925f5b8181106139e257505060a0612d4c61390092611d7a565b73ffffffffffffffffffffffffffffffffffffffff8116926040517fafd27bf50000000000000000000000000000000000000000000000000000000081526020908181600481895afa908115612fa05760049183915f916139c5575b5096604051928380927fd94073d40000000000000000000000000000000000000000000000000000000082525afa918215612fa0575f9261399c57505092565b6139bb9250803d106139be575b6139b38183610507565b8101906138c4565b92565b503d6139a9565b6139dc9150823d84116139be576139b38183610507565b5f61395c565b80604060016139f2819487611d8c565b51613ace8151613a72613a35613a0e6020938487015190611b8d565b92919890960195613a2e613a238289516145d3565b9889809303016145e5565b92016145e5565b92613a59613a41610562565b6fffffffffffffffffffffffffffffffff9095168552565b8301906fffffffffffffffffffffffffffffffff169052565b613a84855f5260cd60205260405f2090565b815160209092015160801b7fffffffffffffffffffffffffffffffff00000000000000000000000000000000166fffffffffffffffffffffffffffffffff92909216919091179055565b52613ad98288611d8c565b52016138e9565b60405190610100820182811067ffffffffffffffff82111761046057604052606060e0835f81525f60208201525f60408201525f838201528260808201528260a08201528260c08201520152565b919073ffffffffffffffffffffffffffffffffffffffff90613b4e613ae0565b5016604051907fe184c9be0000000000000000000000000000000000000000000000000000000082526020938483600481855afa8015612fa057613b9e86915f958691613c05575b504290612636565b926004604051809681937f1d52edc40000000000000000000000000000000000000000000000000000000083525af1928315612fa05761085d955f94613be6575b5050614667565b613bfd929450803d10612f9957612f8b8183610507565b915f80613bdf565b613c1c9150833d8511612f9957612f8b8183610507565b5f613b96565b90918251935f5b858110613c3857505050505050565b60019060c073ffffffffffffffffffffffffffffffffffffffff8082613c5e858b611d8c565b515101511681871614613c9757613c9191613c79848a611d8c565b515101511685613c898487611d8c565b51918861481a565b01613c29565b5050613c91565b92919082613cac5750505050565b613cb59361481a565b5f8080806137e9565b90670de0b6b3a76400009182810292818404149015171561119f57565b8181029291811591840414171561119f57565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b8115613d25570490565b613cee565b15613d3157565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600e60248201527f4c4f503a206661696c20736166650000000000000000000000000000000000006044820152fd5b909291835190613d9e8261200b565b945f80945b848210613db257505050505050565b608097949697959192939591613dcc83612d4c8688611d8c565b905f5b89821080614032575b15613e0157613df5613dfb91613dee848c611d8c565b5190612629565b91612c1f565b90613dcf565b999897959492939190969980156140295773ffffffffffffffffffffffffffffffffffffffff808316918187168314613fd3576001613e40878c612636565b03613ef557505050613e6f9150613e5c60e0612d4c8588611d8c565b9084613e688589611d8c565b519261493f565b613e79828a611d8c565b525b848110613e8e57505b8390949394613da3565b80613eaa613e9e60019386611d8c565b51516130859051061590565b613eb5575b01613e7b565b613ef0613ec28287611d8c565b51613ee9613ed0848d611d8c565b5191610140613edf868a611d8c565b5151015190614d61565b1115613d2a565b613eaf565b613f018185893061493f565b8d89888c8e5b8210613f1c5750505050505050505050613e7b565b81868682938d613f2c8589611d8c565b5151015173ffffffffffffffffffffffffffffffffffffffff1693613f5091611d8c565b5190613f5b91613cdb565b90613f6591613d1b565b613f6f8387611d8c565b52898186848b83168d141597613fac96613f9b9560e095612d4c9560019c613fb6575b50505050611d8c565b613fa58487611d8c565b519161404f565b018a908c8e613f07565b613fca93613fc391611d8c565b5191614cb5565b818f878c613f92565b50505050505b848110613fe65750613e84565b8061400d613ffb60e0612d4c60019588611d8c565b6140058388611d8c565b51908561404f565b6140178186611d8c565b51614022828b611d8c565b5201613fd9565b50505050613e84565b5061404a61404486612d4c858b611d8c565b8461487f565b613dd8565b821561414e5773ffffffffffffffffffffffffffffffffffffffff16806140e757505f80809381935af161408161297b565b501561408957565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600f60248201527f6574682073656e64206661696c656400000000000000000000000000000000006044820152fd5b6040517fa9059cbb00000000000000000000000000000000000000000000000000000000602082015273ffffffffffffffffffffffffffffffffffffffff9290921660248301526044808301939093529181526101fd91614149606483610507565b614ff1565b505050565b91939490948551955f5b87811061416e575050505050505050565b80878782808080808c8c8c8c6141848585611d8c565b51519761419091611d8c565b519860608801519a6141a18c611e56565b60a089015173ffffffffffffffffffffffffffffffffffffffff1660809099015173ffffffffffffffffffffffffffffffffffffffff16976141e291611d8c565b51956141ed91611d8c565b519a6141f891611d8c565b519661420391611d8c565b519161420e91611d8c565b515160c0015173ffffffffffffffffffffffffffffffffffffffff169061423488611e56565b6040805173ffffffffffffffffffffffffffffffffffffffff958616815260208101949094528301989098526060820194909452608081019690965291821660a08601523360c086015216927f338aa396bce529256f46f1d51f463cc5be80195004e47cf0a1527507d38404479060e090a460010161415d565b91909182516142bc8161200b565b935f90815b8381106142cf575050505050565b60809694969593959291926142e881612d4c8487611d8c565b945f935b8881108061442f575b15614363578061434061431060c0612d4c61435e958b611d8c565b9661432c60409889614322868d611d8c565b510151908c614d78565b87614337848b611d8c565b51015190612629565b9561434b8289611d8c565b510151614358828b611d8c565b52612c1f565b6142ec565b9590979493915097959773ffffffffffffffffffffffffffffffffffffffff808816908216148015614427575b61441f578161439f9188614e14565b915b8581106143b4575050505b8291926142c1565b6001906040806143c48388611d8c565b510151906143db856143d68885613cdb565b613d1b565b91826143ea613e9e868b611d8c565b614404575b50506143fb8388611d8c565b510152016143a1565b613ee961441892610140613edf888d611d8c565b5f826143ef565b5050506143ac565b508115614390565b5061443e83612d4c8389611d8c565b73ffffffffffffffffffffffffffffffffffffffff8089169116146142f5565b90928251935f5b85811061447457505050505050565b60019060e073ffffffffffffffffffffffffffffffffffffffff808261449a858b611d8c565b5151015116818616146144d3576144cd916144b5848a611d8c565b51510151166144c48387611d8c565b5190858861481a565b01614465565b50506144cd565b7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411614557576020935f9360ff60809460405194855216868401526040830152606082015282805260015afa15612fa0575f5173ffffffffffffffffffffffffffffffffffffffff81161561454f57905f90565b505f90600190565b505050505f90600390565b61456a6132cf565b805190811561457a576020012090565b505060025480156145885790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b6145b56133af565b80519081156145c5576020012090565b505060035480156145885790565b90808210156145e0575090565b905090565b6fffffffffffffffffffffffffffffffff908181116101ec571690565b1561460957565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f4c4f503a2063616e27742073776170203020616d6f756e7400000000000000006044820152fd5b9392909193614674613ae0565b948151936146818561200b565b608088015261468f8561200b565b60a088015261469d8561200b565b60c08801526146ab8561200b565b60e08801526146d86146d3826146cd6146c8606061253f89611d7a565b614f97565b96615410565b614fe7565b925f94602089019060408a01928a60608101985b8a8110614700575050505050505050505050565b8888826001946147108288611d8c565b51908860408301928d84511561480d57614802976147d69760e09688956147436147699561012061479098510151614fdd565b91516147538860808b0151611d8c565b526147628760808a0151611d8c565b5190615ad5565b9061478a8560a08897959701519360c08901519061478a838c8c0151611d8c565b52611d8c565b526147aa6147a28460a0840151611d8c565b511515614602565b6147c36147bb846080840151611d8c565b518251612629565b81526147de6147d68460a0840151611d8c565b518b51612629565b8a526147f96147f18460c0840151611d8c565b518c51612629565b8b520151611d8c565b8a525b018b906146ec565b5050505050505050614805565b90926101fd93604051937f23b872dd00000000000000000000000000000000000000000000000000000000602086015273ffffffffffffffffffffffffffffffffffffffff8092166024860152166044840152606483015260648252614149826104cf565b73ffffffffffffffffffffffffffffffffffffffff8080931691168181149283156148ef575b83156148b2575b50505090565b7f00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb816149150816148e6575b505f80806148ac565b9050155f6148dd565b92508015806148ff575b926148a5565b50827f00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb81682146148f9565b908160209103126101ec575161085d8161020a565b73ffffffffffffffffffffffffffffffffffffffff8381169594928615808015614bc4575b15614b1a5715614b1257817f00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8915b6040517f784367d600000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff881660048201526020969290911692918682602481875afa928315612fa057614a729388935f91614ae5575b5015614add5750879384915b5f6040518096819582947f769f8e5d00000000000000000000000000000000000000000000000000000000845230600485016080915f93959460a083019673ffffffffffffffffffffffffffffffffffffffff809316845260208401521660408201528260608201520152565b03925af1948515612fa0575f95614abe575b50508385819884841603614aad575b5050503090821603614aa457505050565b6101fd9261404f565b614ab692614cb5565b5f8385614a93565b614ad5929550803d10612f9957612f8b8183610507565b925f80614a84565b938491614a05565b614b059150843d8611614b0b575b614afd8183610507565b81019061492a565b5f6149f9565b503d614af3565b815f91614992565b5091614b9595965060209493915f91604051978896879586937f769f8e5d000000000000000000000000000000000000000000000000000000008552600485016080915f93959460a083019673ffffffffffffffffffffffffffffffffffffffff809316845260208401521660408201528260608201520152565b0393165af1908115612fa0575f91614bab575090565b61085d915060203d602011612f9957612f8b8183610507565b50827f00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8168814614964565b73ffffffffffffffffffffffffffffffffffffffff1680614c6357505f3b156101ec575f600491604051928380927fd0e30db0000000000000000000000000000000000000000000000000000000008252845af18015612fa057614c505750565b80614c5d6101fd926104bb565b80610a0c565b803b156101ec576040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815260048101929092525f908290818381602481015b03925af18015612fa057614c505750565b73ffffffffffffffffffffffffffffffffffffffff9190821680614d19575016803b156101ec575f906004604051809481937fd0e30db00000000000000000000000000000000000000000000000000000000083525af18015612fa057614c505750565b915050803b156101ec576040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815260048101929092525f90829081838160248101614ca4565b670de0b6b3a764000091614d7491613cdb565b0490565b90919073ffffffffffffffffffffffffffffffffffffffff1680614dff575090503403614da157565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f657468206d69736d6174636800000000000000000000000000000000000000006044820152fd5b81614e0957505050565b6101fd92309161481a565b7f00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8929173ffffffffffffffffffffffffffffffffffffffff8082168186161480614f01575b9084614b9596602096959493614eed575b5050614e768383615110565b818116614ee65783905b6040518097819682957f20e8c56500000000000000000000000000000000000000000000000000000000845230600485015f929493606092608083019673ffffffffffffffffffffffffffffffffffffffff809216845216602083015260408201520152565b5f90614e80565b614ef8929350614bef565b5f90835f614e6a565b506040517ffa5a4f0600000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff86166004820152939291906020856024818487165afa948515612fa057614b959660209686925f91614f7a575b5015929394955096509450614e59565b614f919150883d8a11614b0b57614afd8183610507565b5f614f6a565b6004811015611d1e5780614fab5750600190565b614fb481611e56565b60018103614fc25750600290565b80614fce600292611e56565b03614fd857600390565b600490565b90614fe791615410565b5f81126101ec5790565b60405161505b9173ffffffffffffffffffffffffffffffffffffffff1661501782610465565b5f806020958685527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656487860152868151910182855af161505561297b565b916159dc565b8051908282159283156150f8575b505050156150745750565b608490604051907f08c379a00000000000000000000000000000000000000000000000000000000082526004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152fd5b615108935082018101910161492a565b5f8281615069565b919073ffffffffffffffffffffffffffffffffffffffff928381169384156152d1576040519485917fdd62ed3e0000000000000000000000000000000000000000000000000000000083523060048401528416602483015281604460209788935afa8015612fa0576b7fffffffffffffffffffffff915f916152b4575b501061519a575b50509050565b6040517f095ea7b30000000000000000000000000000000000000000000000000000000085820190815273ffffffffffffffffffffffffffffffffffffffff841660248301525f60448301819052918291906151f98160648101611c8c565b519082855af161520761297b565b81615284575b50156152265761521e929350615450565b805f80615194565b606484604051907f08c379a00000000000000000000000000000000000000000000000000000000082526004820152600c60248201527f5361666520417070726f766500000000000000000000000000000000000000006044820152fd5b8051801592508690831561529c575b5050505f61520d565b6152ac935082018101910161492a565b5f8581615293565b6152cb9150863d8811612f9957612f8b8183610507565b5f61518d565b5050509050565b929391937ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000948583019280841161119f57670de0b6b3a764000061531f6153259388613cdb565b04613cdb565b8215613d255782900494810190811161119f5781615346614d749286613cdb565b0493613cbe565b61535c90949394929192613cbe565b918015613d255761536e920490615579565b917ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000810190811161119f576153ac670de0b6b3a76400009184613cdb565b04908290565b92939161531f916153cf91670de0b6b3a764000093849187613cdb565b04927ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c0000810181811161119f576154059084613cdb565b8115613d2557049190565b6301e133809161541f91613cdb565b047f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81116101ec5761085d90615602565b6040517f095ea7b3000000000000000000000000000000000000000000000000000000006020820190815273ffffffffffffffffffffffffffffffffffffffff90931660248201527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60448201525f9283929183906154d28160648101611c8c565b51925af16154de61297b565b8161554a575b50156154ec57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600c60248201527f5361666520417070726f766500000000000000000000000000000000000000006044820152fd5b805180159250821561555f575b50505f6154e4565b615572925060208091830101910161492a565b5f80615557565b90613d1b90613cbe565b1561558a57565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c6964206578706f6e656e74000000000000000000000000000000006044820152fd5b8015613d25576ec097ce7bc90715b34b9f10000000000590565b7ffffffffffffffffffffffffffffffffffffffffffffffffdc702bd3a30fc0000811215806159c9575b61563590615583565b5f81126159b5576064906806f05b59d3b20000008112615952577ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e0000000168056bc75e2d6310000082770195e54c5dd42177f53a27172fa9ec630262827000000000925b02819068ad78ebc5ac62000000811215615919575b6856bc75e2d6310000008112156158df575b682b5e3af16b188000008112156158a7575b6815af1d78b58c40000081121561586f575b680ad78ebc5ac6200000811215615838575b82811215615801575b6802b5e3af16b18800008112156157ca575b68015af1d78b58c40000811215615793575b60028382800205058360038184840205056004828583020505600583868302050560068487830205056007858883020505906008868984020505926009878a8602050594600a888b8802050596600b898c8a02050599600c8a8d8d0205059b0101010101010101010101010205020590565b6806f5f17757889379377ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000084920192020590615721565b6808f00f760a4b2db55d7ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800008492019202059061570f565b680ebc5fb417461211107ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf00000849201920205906156fd565b68280e60114edb805d037ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e00000849201920205906156f4565b690127fa27722cc06cc5e27fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00000849201920205906156e2565b693f1fce3da636ea5cf8507fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800000849201920205906156d0565b6b02df0ab5a80a22c61ab5a7007fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000000849201920205906156be565b6e01855144814a7ff805980ff008400091507fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000000016156ac565b6803782dace9d900000081126159a2577ffffffffffffffffffffffffffffffffffffffffffffffffc87d25316270000000168056bc75e2d63100000826b1425982cf597cd205cef738092615697565b68056bc75e2d6310000082600192615697565b6159c0905f03615602565b61085d906155e8565b5068070c1cc73b00c8000081131561562c565b91929015615a5757508151156159f0575090565b3b156159f95790565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152fd5b825190915015615a6a5750805190602001fd5b6115a4906040519182917f08c379a0000000000000000000000000000000000000000000000000000000008352602060048401526024830190610e7b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52605160045260245ffd5b939291909380600414615b1d5780600314615b135780600214615b0957600103615aa857615b02936153b2565b9192909190565b50615b029361534d565b50615b02936152d8565b507ffffffffffffffffffffffffffffffffffffffffffffffffff21f494c589c00009492919394938482019582871161119f5786615b5a91613cdb565b918015613d2557615b6c920490615579565b92810181811161119f57615b809084613cdb565b8115613d25570492670de0b6b3a76400009384810294818604149015171561119f578015613d2557615bb5816143d685613cbe565b929304919056fea2646970667358221220b522fa078c5f8ec0eaf741819c6dd9192cc3b341b3301883713488522331de3764736f6c63430008180033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8

-----Decoded View---------------
Arg [0] : _WNATIVE (address): 0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 00000000000000000000000078c1b0c915c4faa5fffa6cabf0219da63d7f4cb8


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
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.