ETH Price: $2,762.62 (+1.18%)

Contract

0x235e49CC709F9e262814795c00eabe73709ef8E2
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
SwapAction

Compiler Version
v0.8.19+commit.7dd6d404

Optimization Enabled:
Yes with 100 runs

Other Settings:
paris EvmVersion
File 1 of 36 : SwapAction.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import {IUniswapV3Router, ExactInputParams, ExactOutputParams, decodeLastToken} from "../vendor/IUniswapV3Router.sol";
import {IVault, SwapKind, BatchSwapStep, FundManagement} from "../vendor/IBalancerVault.sol";
import {TokenInput, LimitOrderData} from "pendle/interfaces/IPAllActionTypeV3.sol";
import {ApproxParams} from "pendle/router/base/MarketApproxLib.sol";
import {IPActionAddRemoveLiqV3} from "pendle/interfaces/IPActionAddRemoveLiqV3.sol";
import {IPPrincipalToken} from "pendle/interfaces/IPPrincipalToken.sol";
import {IStandardizedYield} from "pendle/interfaces/IStandardizedYield.sol";
import {IPYieldToken} from "pendle/interfaces/IPYieldToken.sol";
import {IPMarket} from "pendle/interfaces/IPMarket.sol";
import {toInt256, abs} from "../utils/Math.sol";
import {TransferAction, PermitParams} from "./TransferAction.sol";
import {ISwapRouter} from "src/interfaces/ISwapRouterTranchess.sol";
import {IStableSwap} from "src/interfaces/IStableSwapTranchess.sol";
import {ISpectraRouter} from "src/interfaces/ISpectraRouter.sol";

interface ILiquidityGauge {
    function stableSwap() external view returns (address);
}

/// @notice The swap protocol to use
enum SwapProtocol {
    BALANCER,
    UNIV3,
    PENDLE_IN,
    PENDLE_OUT,
    KYBER,
    TRANCHESS_IN,
    TRANCHESS_OUT,
    SPECTRA
}

/// @notice The type of swap to perform
enum SwapType {
    EXACT_IN,
    EXACT_OUT
}

/// @notice The parameters for a swap
struct SwapParams {
    SwapProtocol swapProtocol;
    SwapType swapType;
    address assetIn;
    uint256 amount; // Exact amount in or exact amount out depending on swapType
    uint256 limit; // Min amount out or max amount in depending on swapType
    address recipient;
    address residualRecipient; // Address to send any residual tokens to
    uint256 deadline;
    /// @dev `args` can be used for protocol specific parameters
    /// For Balancer, it is the `poolIds` and `assetPath`
    /// For Uniswap v3, it is the `path` for the swap
    bytes args;
}

/// @title SwapAction
contract SwapAction is TransferAction {
    /*//////////////////////////////////////////////////////////////
                               LIBRARIES
    //////////////////////////////////////////////////////////////*/

    using SafeERC20 for IERC20;

    /*//////////////////////////////////////////////////////////////
                                STORAGE
    //////////////////////////////////////////////////////////////*/

    /// @notice Balancer v2 Vault
    IVault public immutable balancerVault;
    /// @notice Uniswap v3 Router
    IUniswapV3Router public immutable uniRouter;
    /// @notice Pendle Router
    IPActionAddRemoveLiqV3 public immutable pendleRouter;
    /// @notice Kyber MetaAggregationRouterV2
    address public immutable kyberRouter;
    /// @notice Tranchess Swap Router
    ISwapRouter public immutable tranchessRouter;
    /// @notice Spectra Router
    ISpectraRouter public immutable spectraRouter;
    /*//////////////////////////////////////////////////////////////
                                 ERRORS
    //////////////////////////////////////////////////////////////*/

    error SwapAction__swap_notSupported();
    error SwapAction__revertBytes_emptyRevertBytes();
    error SwapAction__kyberSwap_slippageFailed();

    /*//////////////////////////////////////////////////////////////
                             INITIALIZATION
    //////////////////////////////////////////////////////////////*/

    constructor(
        IVault balancerVault_,
        IUniswapV3Router uniRouter_,
        IPActionAddRemoveLiqV3 pendleRouter_,
        address kyberRouter_,
        address tranchessRouter_,
        address spectraRouter_
    ) {
        balancerVault = balancerVault_;
        uniRouter = uniRouter_;
        pendleRouter = pendleRouter_;
        kyberRouter = kyberRouter_;
        tranchessRouter = ISwapRouter(tranchessRouter_);
        spectraRouter = ISpectraRouter(spectraRouter_);
    }

    /*//////////////////////////////////////////////////////////////
                             SWAP VARIANTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Execute a transfer from an EOA and then swap via `swapParams`
    /// @param from The address to transfer from
    /// @param permitParams The parameters for the permit
    /// @param swapParams The parameters for the swap
    /// @return _ Amount of tokens taken or received from the swap
    function transferAndSwap(
        address from,
        PermitParams calldata permitParams,
        SwapParams calldata swapParams
    ) external returns (uint256) {
        if (from != address(this)) {
            uint256 amount = swapParams.swapType == SwapType.EXACT_IN ? swapParams.amount : swapParams.limit;
            _transferFrom(swapParams.assetIn, from, address(this), amount, permitParams);
        }
        return swap(swapParams);
    }

    /// @notice Perform a swap using the protocol and swap-type specified in `swapParams`
    /// @param swapParams The parameters for the swap
    /// @return retAmount Amount of tokens taken or received from the swap
    function swap(SwapParams memory swapParams) public returns (uint256 retAmount) {
        if (block.timestamp > swapParams.deadline) {
            _revertBytes("SwapAction: swap deadline passed");
        }
        if (swapParams.swapProtocol == SwapProtocol.BALANCER) {
            (bytes32[] memory poolIds, address[] memory assetPath) = abi.decode(
                swapParams.args,
                (bytes32[], address[])
            );
            retAmount = balancerSwap(
                swapParams.swapType,
                swapParams.assetIn,
                poolIds,
                assetPath,
                swapParams.amount,
                swapParams.limit,
                swapParams.recipient,
                swapParams.deadline
            );
        } else if (swapParams.swapProtocol == SwapProtocol.KYBER && swapParams.swapType == SwapType.EXACT_IN) {
            retAmount = kyberSwap(swapParams.assetIn, swapParams.amount, swapParams.limit, swapParams.args);
        } else if (swapParams.swapProtocol == SwapProtocol.UNIV3) {
            retAmount = uniV3Swap(
                swapParams.swapType,
                swapParams.assetIn,
                swapParams.amount,
                swapParams.limit,
                swapParams.recipient,
                swapParams.deadline,
                swapParams.args
            );
        } else if (swapParams.swapProtocol == SwapProtocol.PENDLE_IN) {
            retAmount = pendleJoin(swapParams.recipient, swapParams.limit, swapParams.args);
        } else if (swapParams.swapProtocol == SwapProtocol.PENDLE_OUT) {
            retAmount = pendleExit(swapParams.recipient, swapParams.limit, swapParams.args);
        } else if (swapParams.swapProtocol == SwapProtocol.TRANCHESS_IN) {
            retAmount = tranchessJoin(swapParams);
        } else if (swapParams.swapProtocol == SwapProtocol.TRANCHESS_OUT) {
            retAmount = tranchessExit(swapParams.recipient, swapParams.limit, swapParams.args);
        } else if (swapParams.swapProtocol == SwapProtocol.SPECTRA) {
            retAmount = spectra(swapParams);
        } else revert SwapAction__swap_notSupported();
        // Transfer any remaining tokens to the residualRecipient or recipient
        if (swapParams.swapType == SwapType.EXACT_OUT && swapParams.recipient != address(this)) {
            if (swapParams.residualRecipient != address(0)) {
                IERC20(swapParams.assetIn).safeTransfer(swapParams.residualRecipient, swapParams.limit - retAmount);
            } else {
                IERC20(swapParams.assetIn).safeTransfer(swapParams.recipient, swapParams.limit - retAmount);
            }
        }
    }

    /// @notice Perform a batch swap on Balancer
    /// @dev
    ///      For EXACT_IN, the `poolIds` and `assets` are in sequential order. The `assetIn` must be the first index
    ///      of `assets` and the asset out must be the last index of `assets`.
    ///
    ///      For EXACT_OUT, the `poolIds` and `assets` are reversed. The asset out must be the first index of `assets`
    ///      and the `assetIn` must be the last index of `assets`.
    ///      ex.
    ///      EXACT_IN:  { [Asset In  ->  Asset X] -> [Asset X -> Asset Out] }
    ///      EXACT_OUT: { [Asset Out ->  Asset X] -> [Asset X -> Asset In ] }
    ///
    /// @dev `assets.length` should always be `poolIds.length` + 1
    /// @param swapType The type of swap to perform
    /// @param assetIn Asset to send during the swap
    /// @param poolIds The poolIds to use for the swap:
    ///                For EXACT_IN the poolIds must be in sequential order
    ///                For EXACT_OUT the poolIds must be in reverse sequential order
    /// @param assets The assets to use for the swap:
    ///               For EXACT_IN the assets must be in sequential order
    ///               For EXACT_OUT the assets must be in reverse sequential order
    /// @param amount EXACT_IN:  `amount` is the amount of `assetIn` to send
    ///               EXACT_OUT: `amount` is the amount of asset out to receive
    /// @param limit  EXACT_IN:  `limit` is the minimum acceptable amount to receive from the swap
    ///               EXACT_OUT: `limit` is the maximum acceptable amount to send on the swap
    /// @param recipient Address to send the swapped tokens to
    /// @param deadline Timestamp after which the swap will revert
    /// @return _ Amount of tokens taken or received from the swap
    function balancerSwap(
        SwapType swapType,
        address assetIn,
        bytes32[] memory poolIds,
        address[] memory assets,
        uint256 amount,
        uint256 limit,
        address recipient,
        uint256 deadline
    ) internal returns (uint256) {
        uint256 pathLength = poolIds.length;
        int256[] memory limits = new int256[](pathLength + 1); // limit for each asset, leave as 0 to autocalculate

        // construct the BatchSwapStep array
        BatchSwapStep[] memory swaps = new BatchSwapStep[](pathLength);
        {
            // In an 'EXACT_IN' swap, 'BatchSwapStep.assetInIndex' must equal the previous swap's `assetOutIndex`.
            // For an 'EXACT_OUT' swap, `BatchSwapStep.assetOutIndex` must equal the previous swap's `assetInIndex`.
            //
            // For `EXACT_IN`, we can accomplish this by incrementing the `assetOutIndex` by 1,
            // and for `EXACT_OUT` by incrementing the `assetInIndex` by 1.
            // EX.
            //  1. Swapping an exact amount in of USDC for BAL
            //     swapType = `EXACT_IN` and `assets` = [USDC, DAI, WETH, BAL]
            //     ╔══════════╦══════════╦═══════════╗
            //     ║ EXACT_IN ║ Asset In ║ Asset Out ║
            //     ╠══════════╬══════════╬═══════════╣
            //     ║ Swap 1   ║ USDC     ║ DAI       ║
            //     ╠══════════╬══════════╬═══════════╣
            //     ║ Swap 2   ║ DAI      ║ WETH      ║
            //     ╠══════════╬══════════╬═══════════╣
            //     ║ Swap 3   ║ WETH     ║ BAL       ║
            //     ╚══════════╩══════════╩═══════════╝
            //      * Swap n "Asset Out" must equal Swap n+1 "Asset In"
            //
            //  2. Swapping in USDC for an exact amount out of BAL
            //     swapType = `EXACT_OUT` and `assets` = [BAL, WETH, DAI, USDC]:
            //     ╔═══════════╦══════════╦═══════════╗
            //     ║ EXACT_OUT ║ Asset In ║ Asset Out ║
            //     ╠═══════════╬══════════╬═══════════╣
            //     ║ Swap 1    ║ WETH     ║ BAL       ║
            //     ╠═══════════╬══════════╬═══════════╣
            //     ║ Swap 2    ║ DAI      ║ WETH      ║
            //     ╠═══════════╬══════════╬═══════════╣
            //     ║ Swap 3    ║ USDC     ║ DAI       ║
            //     ╚═══════════╩══════════╩═══════════╝
            //      * Swap n "Asset In" must equal Swap n+1 "Asset Out"
            //
            // more info: https://docs.balancer.fi/reference/swaps/batch-swaps.html

            bytes memory userData; // empty bytes, not used
            uint256 inIncrement;
            uint256 outIncrement;
            if (swapType == SwapType.EXACT_IN) outIncrement = 1;
            else inIncrement = 1;

            for (uint256 i; i < pathLength; ) {
                unchecked {
                    swaps[i] = BatchSwapStep({
                        poolId: poolIds[i],
                        assetInIndex: i + inIncrement,
                        assetOutIndex: i + outIncrement,
                        amount: 0, // 0 to autocalculate
                        userData: userData
                    });
                    ++i;
                }
            }
            swaps[0].amount = amount; // amount always pertains to the first swap
        }

        // configure swap-type dependent variables
        SwapKind kind;
        uint256 amountToApprove;
        if (swapType == SwapType.EXACT_IN) {
            kind = SwapKind.GIVEN_IN;
            amountToApprove = amount;
            limits[0] = toInt256(amount); // positive signifies tokens going into the vault from the caller
            limits[pathLength] = -toInt256(limit); // negative signifies tokens going out of the vault to the caller
        } else {
            kind = SwapKind.GIVEN_OUT;
            amountToApprove = limit;
            limits[0] = -toInt256(amount);
            limits[pathLength] = toInt256(limit);
        }

        IERC20(assetIn).forceApprove(address(balancerVault), amountToApprove);

        // execute swap and return the value of the last index in the asset delta array to get amountIn/amountOut
        return
            abs(
                balancerVault.batchSwap(
                    kind,
                    swaps,
                    assets,
                    FundManagement({
                        sender: address(this),
                        fromInternalBalance: false,
                        recipient: payable(recipient),
                        toInternalBalance: false
                    }),
                    limits,
                    deadline
                )[pathLength]
            );
    }

    /// @notice Perform an swap using Kyber MetaAggregationRouterV2
    /// @param assetIn Token to swap from
    /// @param amountIn Amount of `assetIn` to swap
    /// @param minOut Minimum amount of assets to receive
    /// @param payload tx calldata to use when calling the kyber router,
    /// this calldata can be generated using the kyber swap api
    /// @return _ Amount of tokens received from the swap
    function kyberSwap(
        address assetIn,
        uint256 amountIn,
        uint256 minOut,
        bytes memory payload
    ) internal returns (uint256) {
        IERC20(assetIn).forceApprove(address(kyberRouter), amountIn);
        (bool success, bytes memory result) = kyberRouter.call(payload);
        if (!success) _revertBytes(result);
        (uint256 returnAmount /*uint256 gasUsed*/, ) = abi.decode(result, (uint256, uint256));
        if (returnAmount < minOut) revert SwapAction__kyberSwap_slippageFailed();
        return returnAmount;
    }

    /// @notice Perform a swap using uniswap v3 exactInput or exactOutput function
    /// @param swapType The type of swap to perform
    /// @param assetIn Asset to send during the swap:
    /// @param amount EXACT_IN:  `amount` is the amount of `assetIn` to send
    ///               EXACT_OUT: `amount` is the amount of asset out to receive
    /// @param limit EXACT_IN:  `limit` is the minimum acceptable amount to receive from the swap
    ///              EXACT_OUT: `limit` is the maximum acceptable amount to send on the swap
    /// @param recipient Address to send the swapped tokens to
    /// @param args Uniswap V3 path parameter, EXACT_OUT must be calculated in reverse order
    /// EXACT_IN:  { [Asset In,  Fee, Asset X], [Asset X, Fee, Asset Out] }
    /// EXACT_OUT: { [Asset Out, Fee, Asset X], [Asset X, Fee, Asset In ] }
    /// @param deadline Timestamp after which the swap will revert
    /// @return retAmount Amount of tokens taken or received from the swap
    function uniV3Swap(
        SwapType swapType,
        address assetIn,
        uint256 amount,
        uint256 limit,
        address recipient,
        uint256 deadline,
        bytes memory args
    ) internal returns (uint256) {
        if (swapType == SwapType.EXACT_IN) {
            IERC20(assetIn).forceApprove(address(uniRouter), amount);
            return
                uniRouter.exactInput(
                    ExactInputParams({
                        path: args,
                        recipient: recipient,
                        amountIn: amount,
                        amountOutMinimum: limit,
                        deadline: deadline
                    })
                );
        } else {
            IERC20(assetIn).forceApprove(address(uniRouter), limit);
            return
                uniRouter.exactOutput(
                    ExactOutputParams({
                        path: args,
                        recipient: recipient,
                        amountOut: amount,
                        amountInMaximum: limit,
                        deadline: deadline
                    })
                );
        }
    }

    /// @notice Perform a join using the Pendle protocol
    /// @param recipient Address to send the swapped tokens to
    /// @param minOut Minimum amount of LP tokens to receive
    /// @param data The parameters for joinng the pool
    /// @dev For more information regarding the Pendle join function check Pendle
    /// documentation
    function pendleJoin(address recipient, uint256 minOut, bytes memory data) internal returns (uint256 netLpOut) {
        (
            address market,
            ApproxParams memory guessPtReceivedFromSy,
            TokenInput memory input,
            LimitOrderData memory limit
        ) = abi.decode(data, (address, ApproxParams, TokenInput, LimitOrderData));

        if (input.tokenIn != address(0)) {
            input.netTokenIn = IERC20(input.tokenIn).balanceOf(address(this));
            IERC20(input.tokenIn).forceApprove(address(pendleRouter), input.netTokenIn);
        }

        (netLpOut, , ) = pendleRouter.addLiquiditySingleToken(
            recipient,
            market,
            minOut,
            guessPtReceivedFromSy,
            input,
            limit
        );
    }

    function pendleExit(address recipient, uint256 minOut, bytes memory data) internal returns (uint256 retAmount) {
        (address market, uint256 netLpIn, address tokenOut) = abi.decode(data, (address, uint256, address));

        (IStandardizedYield SY, IPPrincipalToken PT, IPYieldToken YT) = IPMarket(market).readTokens();

        if (recipient != address(this)) {
            IPMarket(market).transferFrom(recipient, market, netLpIn);
        } else {
            IPMarket(market).transfer(market, netLpIn);
        }

        uint256 netSyToRedeem;

        if (PT.isExpired()) {
            (uint256 netSyRemoved, ) = IPMarket(market).burn(address(SY), address(YT), netLpIn);
            uint256 netSyFromPt = YT.redeemPY(address(SY));
            netSyToRedeem = netSyRemoved + netSyFromPt;
        } else {
            (uint256 netSyRemoved, uint256 netPtRemoved) = IPMarket(market).burn(address(SY), market, netLpIn);
            bytes memory empty;
            (uint256 netSySwappedOut, ) = IPMarket(market).swapExactPtForSy(address(SY), netPtRemoved, empty);
            netSyToRedeem = netSyRemoved + netSySwappedOut;
        }

        return SY.redeem(recipient, netSyToRedeem, tokenOut, minOut, true);
    }

    function tranchessJoin(SwapParams memory swapParams) internal returns (uint256 retAmount) {
        (address lpToken, uint256 baseDelta, uint256 quoteDelta, uint256 version) = abi.decode(
            swapParams.args,
            (address, uint256, uint256, uint256)
        );

        //IStableSwap stableSwap = IStableSwap(ILiquidityGauge(lpToken).stableSwap());
        address baseAddress = IStableSwap(ILiquidityGauge(lpToken).stableSwap()).baseAddress();
        address quoteAddress = IStableSwap(ILiquidityGauge(lpToken).stableSwap()).quoteAddress();
        if (baseDelta != 0) {
            IERC20(baseAddress).forceApprove(address(tranchessRouter), baseDelta);
        }
        if (quoteDelta != 0) {
            IERC20(quoteAddress).forceApprove(address(tranchessRouter), quoteDelta);
        }

        tranchessRouter.addLiquidity(
            baseAddress,
            quoteAddress,
            baseDelta,
            quoteDelta,
            swapParams.limit,
            version,
            swapParams.deadline
        );

        retAmount = IERC20(lpToken).balanceOf(address(this));

        if (swapParams.recipient != address(this)) {
            IERC20(lpToken).safeTransfer(swapParams.recipient, retAmount);
        }
    }

    function tranchessExit(address recipient, uint256 minOut, bytes memory data) internal returns (uint256 retAmount) {
        (uint256 version, address lpToken, uint256 lpIn) = abi.decode(data, (uint256, address, uint256));

        IStableSwap stableSwap = IStableSwap(ILiquidityGauge(lpToken).stableSwap());
        retAmount = stableSwap.removeQuoteLiquidity(version, lpIn, minOut);

        if (recipient != address(this)) {
            IERC20(stableSwap.quoteAddress()).safeTransfer(recipient, retAmount);
        }
    }

    function spectra(SwapParams memory swapParams) internal returns (uint256 retAmount) {
        (bytes memory commands, bytes[] memory inputs, address tokenOut, uint256 deadline) = abi.decode(
            swapParams.args,
            (bytes, bytes[], address, uint256)
        );
        uint256 balBefore = IERC20(tokenOut).balanceOf(swapParams.recipient);
        (address tokenIn, uint256 amountIn) = abi.decode(inputs[0], (address, uint256));
        IERC20(tokenIn).forceApprove(address(spectraRouter), amountIn);
        spectraRouter.execute(commands, inputs, deadline);
        retAmount = IERC20(tokenOut).balanceOf(swapParams.recipient) - balBefore;
    }

    /// @notice Helper function that decodes the swap params and returns the token that will be swapped into
    /// @param swapParams The parameters for the swap
    /// @return token The token that will be swapped into
    function getSwapToken(SwapParams calldata swapParams) public pure returns (address token) {
        if (swapParams.swapProtocol == SwapProtocol.BALANCER) {
            (, address[] memory primarySwapPath) = abi.decode(swapParams.args, (bytes32[], address[]));

            if (swapParams.swapType == SwapType.EXACT_OUT) {
                // For EXACT_OUT, the token that will be swapped into is the first token in the path
                token = primarySwapPath[0];
            } else {
                // For EXACT_IN, the token that will be swapped into is the last token in the path
                token = primarySwapPath[primarySwapPath.length - 1];
            }
        } else if (swapParams.swapProtocol == SwapProtocol.UNIV3) {
            token = decodeLastToken(swapParams.args);
        } else {
            revert SwapAction__swap_notSupported();
        }
    }

    /// @notice Reverts with the provided error message
    /// @dev if errMsg is empty, reverts with a default error message
    /// @param errMsg Error message to revert with.
    function _revertBytes(bytes memory errMsg) internal pure {
        if (errMsg.length != 0) {
            assembly {
                revert(add(32, errMsg), mload(errMsg))
            }
        }
        revert SwapAction__revertBytes_emptyRevertBytes();
    }
}

File 2 of 36 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (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. Compatible with tokens that require the approval to be set to
     * 0 before setting it to a non-zero value.
     */
    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));
    }
}

File 3 of 36 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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);
}

File 4 of 36 : IUniswapV3Router.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.19;

struct ExactInputParams {
    bytes path;
    address recipient;
    uint256 deadline;
    uint256 amountIn;
    uint256 amountOutMinimum;
}

struct ExactOutputParams {
    bytes path;
    address recipient;
    uint256 deadline;
    uint256 amountOut;
    uint256 amountInMaximum;
}

error UniswapV3Router_toAddress_overflow();
error UniswapV3Router_toAddress_outOfBounds();
error UniswapV3Router_decodeLastToken_invalidPath();

function toAddress(bytes memory _bytes, uint256 _start) pure returns (address) {
    if (_start + 20 < _start) revert UniswapV3Router_toAddress_overflow();
    if (_bytes.length < _start + 20) revert UniswapV3Router_toAddress_outOfBounds();
    address tempAddress;

    assembly {
        tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
    }

    return tempAddress;
}

/// @notice Decodes the last token in the path
/// @param path The bytes encoded swap path
/// @return token The last token of the given path
function decodeLastToken(bytes memory path) pure returns (address token) {
    if (path.length < 20) revert UniswapV3Router_decodeLastToken_invalidPath();
    token = toAddress(path, path.length - 20);
}

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3Router {
    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

File 5 of 36 : IBalancerVault.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity ^0.8.19;
import {IAsset} from "src/vendor/IAsset.sol";

enum SwapKind {
    GIVEN_IN,
    GIVEN_OUT
}
/**
 * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
 * the `kind` value.
 *
 * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
 * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
 *
 * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
 * used to extend swap behavior.
 */
///@dev NOTE - we are using address type for all instances of IAsset to simplify
struct SingleSwap {
    bytes32 poolId;
    SwapKind kind;
    address assetIn;
    address assetOut;
    uint256 amount;
    bytes userData;
}

/**
 * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
 * `recipient` account.
 *
 * If the caller is not `sender`, it must be an authorized relayer for them.
 *
 * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
 * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
 * `joinPool`.
 *
 * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
 * transferred. This matches the behavior of `exitPool`.
 *
 * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
 * revert.
 */
struct FundManagement {
    address sender;
    bool fromInternalBalance;
    address payable recipient;
    bool toInternalBalance;
}

/**
 * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the
 * `assets` array passed to that function, and ETH assets are converted to WETH.
 *
 * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out
 * from the previous swap, depending on the swap kind.
 *
 * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
 * used to extend swap behavior.
 */
struct BatchSwapStep {
    bytes32 poolId;
    uint256 assetInIndex;
    uint256 assetOutIndex;
    uint256 amount;
    bytes userData;
}

/**
 * @dev See `joinPool` for more details.
 */
struct JoinPoolRequest {
    address[] assets;
    uint256[] maxAmountsIn;
    bytes userData;
    bool fromInternalBalance;
}

/**
 * @dev All possible `JoinKind`'s. See specific pool implementations for available `JoinKind`'s.
 */
enum JoinKind {
    INIT,
    EXACT_TOKENS_IN_FOR_BPT_OUT,
    TOKEN_IN_FOR_EXACT_BPT_OUT,
    ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
}

/**
 * @dev WeightedPool ExitKinds
 */
enum ExitKind {
    EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
    EXACT_BPT_IN_FOR_TOKENS_OUT,
    BPT_IN_FOR_EXACT_TOKENS_OUT,
    MANAGEMENT_FEE_TOKENS_OUT // for InvestmentPool
}

/**
 * @dev See `exitPool` for more details.
 */
struct ExitPoolRequest {
    address[] assets;
    uint256[] minAmountsOut;
    bytes userData;
    bool toInternalBalance;
}

///@dev Entry point for all Balancer V2 swaps.
interface IVault {
    /**
     * @dev Performs a swap with a single Pool.
     *
     * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
     * taken from the Pool, which must be greater than or equal to `limit`.
     *
     * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
     * sent to the Pool, which must be less than or equal to `limit`.
     *
     * Internal Balance usage and the recipient are determined by the `funds` struct.
     *
     * Emits a `Swap` event.
     */
    function swap(
        SingleSwap memory singleSwap,
        FundManagement memory funds,
        uint256 limit,
        uint256 deadline
    ) external payable returns (uint256);

    /**
     * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either
     * the amount of tokens sent to or received from the Pool, depending on the `kind` value.
     *
     * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the
     * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at
     * the same index in the `assets` array.
     *
     * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a
     * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or
     * `amountOut` depending on the swap kind.
     *
     * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out
     * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal
     * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`.
     * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses,
     * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and
     * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to
     * or unwrapped from WETH by the Vault.
     *
     * Internal Balance usage, sender, and recipient are determined by the `funds` struct.
     *
     * The `limits` array specifies the minimum or maximum amount of each token the vault is allowed to transfer.
     *
     * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the
     * equivalent `swap` call.
     *
     * Emits `Swap` events.
     */
    function batchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        address[] memory assets,
        FundManagement memory funds,
        int256[] memory limits,
        uint256 deadline
    ) external payable returns (int256[] memory);

    /**
     * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
     * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
     * Pool shares.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
     * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
     * these maximums.
     *
     * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
     * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
     * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
     * back to the caller (not the sender, which is important for relayers).
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
     * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
     * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
     *
     * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
     * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
     * withdrawn from Internal Balance: attempting to do so will trigger a revert.
     *
     * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
     * directly to the Pool's contract, as is `recipient`.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function joinPool(
        bytes32 poolId,
        address sender,
        address recipient,
        JoinPoolRequest memory request
    ) external payable;

    /**
     * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
     * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
     * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
     * `getPoolTokenInfo`).
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
     * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
     * it just enforces these minimums.
     *
     * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
     * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
     * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
     * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
     * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
     *
     * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
     * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
     * do so will trigger a revert.
     *
     * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
     * `tokens` array. This array must match the Pool's registered tokens.
     *
     * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
     * passed directly to the Pool's contract.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function exitPool(
        bytes32 poolId,
        address sender,
        address payable recipient,
        ExitPoolRequest memory request
    ) external;

    /**
     * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
     * the tokens' `balances` changed.
     *
     * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
     * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
     *
     * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
     * order as passed to `registerTokens`.
     *
     * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
     * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
     * instead.
     */
    function getPoolTokens(
        bytes32 poolId
    ) external view returns (address[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock);

    /**
     * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be
     * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result.
     *
     * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH)
     * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it
     * receives are the same that an equivalent `batchSwap` call would receive.
     *
     * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct.
     * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens,
     * approve them for the Vault, or even know a user's address.
     *
     * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute
     * eth_call instead of eth_sendTransaction.
     */
    function queryBatchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        address[] memory assets,
        FundManagement memory funds
    ) external view returns (int256[] memory assetDeltas);

    /**
     * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer)
     * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as
     * it lets integrators reuse a user's Vault allowance.
     *
     * For each operation, if the caller is not `sender`, it must be an authorized relayer for them.
     */
    function manageUserBalance(UserBalanceOp[] memory ops) external payable;

    /**
     * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received
     without manual WETH wrapping or unwrapping.
     */
    struct UserBalanceOp {
        UserBalanceOpKind kind;
        IAsset asset;
        uint256 amount;
        address sender;
        address payable recipient;
    }
    enum UserBalanceOpKind {
        DEPOSIT_INTERNAL,
        WITHDRAW_INTERNAL,
        TRANSFER_INTERNAL,
        TRANSFER_EXTERNAL
    }
    // Pools
    //
    // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
    // functionality:
    //
    //  - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
    // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
    // which increase with the number of registered tokens.
    //
    //  - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
    // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
    // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
    // independent of the number of registered tokens.
    //
    //  - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
    // minimal swap info Pools, these are called via IMinimalSwapInfoPool.

    enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }

    /**
     * @dev Returns a Pool's contract address and specialization setting.
     */
    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);
}

File 6 of 36 : IPAllActionTypeV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity ^0.8.0;

import "../router/swap-aggregator/IPSwapAggregator.sol";
import "./IPLimitRouter.sol";

struct TokenInput {
    // Token/Sy data
    address tokenIn;
    uint256 netTokenIn;
    address tokenMintSy;
    // aggregator data
    address pendleSwap;
    SwapData swapData;
}

struct TokenOutput {
    // Token/Sy data
    address tokenOut;
    uint256 minTokenOut;
    address tokenRedeemSy;
    // aggregator data
    address pendleSwap;
    SwapData swapData;
}

struct LimitOrderData {
    address limitRouter;
    uint256 epsSkipMarket; // only used for swap operations, will be ignored otherwise
    FillOrderParams[] normalFills;
    FillOrderParams[] flashFills;
    bytes optData;
}

File 7 of 36 : MarketApproxLib.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "../../core/libraries/math/PMath.sol";
import "../../core/Market/MarketMathCore.sol";

struct ApproxParams {
    uint256 guessMin;
    uint256 guessMax;
    uint256 guessOffchain; // pass 0 in to skip this variable
    uint256 maxIteration; // every iteration, the diff between guessMin and guessMax will be divided by 2
    uint256 eps; // the max eps between the returned result & the correct result, base 1e18. Normally this number will be set
    // to 1e15 (1e18/1000 = 0.1%)
}

/// Further explanation of the eps. Take swapExactSyForPt for example. To calc the corresponding amount of Pt to swap out,
/// it's necessary to run an approximation algorithm, because by default there only exists the Pt to Sy formula
/// To approx, the 5 values above will have to be provided, and the approx process will run as follows:
/// mid = (guessMin + guessMax) / 2 // mid here is the current guess of the amount of Pt out
/// netSyNeed = calcSwapSyForExactPt(mid)
/// if (netSyNeed > exactSyIn) guessMax = mid - 1 // since the maximum Sy in can't exceed the exactSyIn
/// else guessMin = mid (1)
/// For the (1), since netSyNeed <= exactSyIn, the result might be usable. If the netSyNeed is within eps of
/// exactSyIn (ex eps=0.1% => we have used 99.9% the amount of Sy specified), mid will be chosen as the final guess result

/// for guessOffchain, this is to provide a shortcut to guessing. The offchain SDK can precalculate the exact result
/// before the tx is sent. When the tx reaches the contract, the guessOffchain will be checked first, and if it satisfies the
/// approximation, it will be used (and save all the guessing). It's expected that this shortcut will be used in most cases
/// except in cases that there is a trade in the same market right before the tx

library MarketApproxPtInLib {
    using MarketMathCore for MarketState;
    using PYIndexLib for PYIndex;
    using PMath for uint256;
    using PMath for int256;
    using LogExpMath for int256;

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swap in
     *     - Try swapping & get netSyOut
     *     - Stop when netSyOut greater & approx minSyOut
     *     - guess & approx is for netPtIn
     */
    function approxSwapPtForExactSy(
        MarketState memory market,
        PYIndex index,
        uint256 minSyOut,
        uint256 blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netPtIn*/ uint256, /*netSyOut*/ uint256 /*netSyFee*/) {
        MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
        if (approx.guessOffchain == 0) {
            // no limit on min
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp));
            validateApprox(approx);
        }

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);
            (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess);

            if (netSyOut >= minSyOut) {
                if (PMath.isAGreaterApproxB(netSyOut, minSyOut, approx.eps)) {
                    return (guess, netSyOut, netSyFee);
                }
                approx.guessMax = guess;
            } else {
                approx.guessMin = guess;
            }
        }
        revert Errors.ApproxFail();
    }

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swap in
     *     - Flashswap the corresponding amount of SY out
     *     - Pair those amount with exactSyIn SY to tokenize into PT & YT
     *     - PT to repay the flashswap, YT transferred to user
     *     - Stop when the amount of SY to be pulled to tokenize PT to repay loan approx the exactSyIn
     *     - guess & approx is for netYtOut (also netPtIn)
     */
    function approxSwapExactSyForYt(
        MarketState memory market,
        PYIndex index,
        uint256 exactSyIn,
        uint256 blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netYtOut*/ uint256 /*netSyFee*/) {
        MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
        if (approx.guessOffchain == 0) {
            approx.guessMin = PMath.max(approx.guessMin, index.syToAsset(exactSyIn));
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp));
            validateApprox(approx);
        }

        // at minimum we will flashswap exactSyIn since we have enough SY to payback the PT loan

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);

            (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess);

            uint256 netSyToTokenizePt = index.assetToSyUp(guess);

            // for sure netSyToTokenizePt >= netSyOut since we are swapping PT to SY
            uint256 netSyToPull = netSyToTokenizePt - netSyOut;

            if (netSyToPull <= exactSyIn) {
                if (PMath.isASmallerApproxB(netSyToPull, exactSyIn, approx.eps)) {
                    return (guess, netSyFee);
                }
                approx.guessMin = guess;
            } else {
                approx.guessMax = guess - 1;
            }
        }
        revert Errors.ApproxFail();
    }

    struct Args5 {
        MarketState market;
        PYIndex index;
        uint256 totalPtIn;
        uint256 netSyHolding;
        uint256 blockTime;
        ApproxParams approx;
    }

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swap to SY
     *     - Swap PT to SY
     *     - Pair the remaining PT with the SY to add liquidity
     *     - Stop when the ratio of PT / totalPt & SY / totalSy is approx
     *     - guess & approx is for netPtSwap
     */
    function approxSwapPtToAddLiquidity(
        MarketState memory _market,
        PYIndex _index,
        uint256 _totalPtIn,
        uint256 _netSyHolding,
        uint256 _blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netPtSwap*/ uint256, /*netSyFromSwap*/ uint256 /*netSyFee*/) {
        Args5 memory a = Args5(_market, _index, _totalPtIn, _netSyHolding, _blockTime, approx);
        MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime);
        if (approx.guessOffchain == 0) {
            // no limit on min
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(a.market, comp));
            approx.guessMax = PMath.min(approx.guessMax, a.totalPtIn);
            validateApprox(approx);
            require(a.market.totalLp != 0, "no existing lp");
        }

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);

            (uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, ) = calcNumerators(
                a.market,
                a.index,
                a.totalPtIn,
                a.netSyHolding,
                comp,
                guess
            );

            if (PMath.isAApproxB(syNumerator, ptNumerator, approx.eps)) {
                return (guess, netSyOut, netSyFee);
            }

            if (syNumerator <= ptNumerator) {
                // needs more SY --> swap more PT
                approx.guessMin = guess + 1;
            } else {
                // needs less SY --> swap less PT
                approx.guessMax = guess - 1;
            }
        }
        revert Errors.ApproxFail();
    }

    function calcNumerators(
        MarketState memory market,
        PYIndex index,
        uint256 totalPtIn,
        uint256 netSyHolding,
        MarketPreCompute memory comp,
        uint256 guess
    )
        internal
        pure
        returns (uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve)
    {
        (netSyOut, netSyFee, netSyToReserve) = calcSyOut(market, comp, index, guess);

        uint256 newTotalPt = uint256(market.totalPt) + guess;
        uint256 newTotalSy = (uint256(market.totalSy) - netSyOut - netSyToReserve);

        // it is desired that
        // (netSyOut + netSyHolding) / newTotalSy = netPtRemaining / newTotalPt
        // which is equivalent to
        // (netSyOut + netSyHolding) * newTotalPt = netPtRemaining * newTotalSy

        syNumerator = (netSyOut + netSyHolding) * newTotalPt;
        ptNumerator = (totalPtIn - guess) * newTotalSy;
    }

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swap to SY
     *     - Flashswap the corresponding amount of SY out
     *     - Tokenize all the SY into PT + YT
     *     - PT to repay the flashswap, YT transferred to user
     *     - Stop when the additional amount of PT to pull to repay the loan approx the exactPtIn
     *     - guess & approx is for totalPtToSwap
     */
    function approxSwapExactPtForYt(
        MarketState memory market,
        PYIndex index,
        uint256 exactPtIn,
        uint256 blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netYtOut*/ uint256, /*totalPtToSwap*/ uint256 /*netSyFee*/) {
        MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
        if (approx.guessOffchain == 0) {
            approx.guessMin = PMath.max(approx.guessMin, exactPtIn);
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp));
            validateApprox(approx);
        }

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);

            (uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess);

            uint256 netAssetOut = index.syToAsset(netSyOut);

            // guess >= netAssetOut since we are swapping PT to SY
            uint256 netPtToPull = guess - netAssetOut;

            if (netPtToPull <= exactPtIn) {
                if (PMath.isASmallerApproxB(netPtToPull, exactPtIn, approx.eps)) {
                    return (netAssetOut, guess, netSyFee);
                }
                approx.guessMin = guess;
            } else {
                approx.guessMax = guess - 1;
            }
        }
        revert Errors.ApproxFail();
    }

    ////////////////////////////////////////////////////////////////////////////////

    function calcSyOut(
        MarketState memory market,
        MarketPreCompute memory comp,
        PYIndex index,
        uint256 netPtIn
    ) internal pure returns (uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve) {
        (int256 _netSyOut, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, -int256(netPtIn));
        netSyOut = uint256(_netSyOut);
        netSyFee = uint256(_netSyFee);
        netSyToReserve = uint256(_netSyToReserve);
    }

    function nextGuess(ApproxParams memory approx, uint256 iter) internal pure returns (uint256) {
        if (iter == 0 && approx.guessOffchain != 0) return approx.guessOffchain;
        if (approx.guessMin <= approx.guessMax) return (approx.guessMin + approx.guessMax) / 2;
        revert Errors.ApproxFail();
    }

    /// INTENDED TO BE CALLED BY WHEN GUESS.OFFCHAIN == 0 ONLY ///

    function validateApprox(ApproxParams memory approx) internal pure {
        if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) {
            revert Errors.ApproxParamsInvalid(approx.guessMin, approx.guessMax, approx.eps);
        }
    }

    function calcMaxPtIn(MarketState memory market, MarketPreCompute memory comp) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 hi = uint256(comp.totalAsset) - 1;

        while (low != hi) {
            uint256 mid = (low + hi + 1) / 2;
            if (calcSlope(comp, market.totalPt, int256(mid)) < 0) hi = mid - 1;
            else low = mid;
        }
        return low;
    }

    function calcSlope(MarketPreCompute memory comp, int256 totalPt, int256 ptToMarket) internal pure returns (int256) {
        int256 diffAssetPtToMarket = comp.totalAsset - ptToMarket;
        int256 sumPt = ptToMarket + totalPt;

        require(diffAssetPtToMarket > 0 && sumPt > 0, "invalid ptToMarket");

        int256 part1 = (ptToMarket * (totalPt + comp.totalAsset)).divDown(sumPt * diffAssetPtToMarket);

        int256 part2 = sumPt.divDown(diffAssetPtToMarket).ln();
        int256 part3 = PMath.IONE.divDown(comp.rateScalar);

        return comp.rateAnchor - (part1 - part2).mulDown(part3);
    }
}

library MarketApproxPtOutLib {
    using MarketMathCore for MarketState;
    using PYIndexLib for PYIndex;
    using PMath for uint256;
    using PMath for int256;
    using LogExpMath for int256;

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swapExactOut
     *     - Calculate the amount of SY needed
     *     - Stop when the netSyIn is smaller approx exactSyIn
     *     - guess & approx is for netSyIn
     */
    function approxSwapExactSyForPt(
        MarketState memory market,
        PYIndex index,
        uint256 exactSyIn,
        uint256 blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netPtOut*/ uint256 /*netSyFee*/) {
        MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
        if (approx.guessOffchain == 0) {
            // no limit on min
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt));
            validateApprox(approx);
        }

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);

            (uint256 netSyIn, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess);

            if (netSyIn <= exactSyIn) {
                if (PMath.isASmallerApproxB(netSyIn, exactSyIn, approx.eps)) {
                    return (guess, netSyFee);
                }
                approx.guessMin = guess;
            } else {
                approx.guessMax = guess - 1;
            }
        }

        revert Errors.ApproxFail();
    }

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swapExactOut
     *     - Flashswap that amount of PT & pair with YT to redeem SY
     *     - Use the SY to repay the flashswap debt and the remaining is transferred to user
     *     - Stop when the netSyOut is greater approx the minSyOut
     *     - guess & approx is for netSyOut
     */
    function approxSwapYtForExactSy(
        MarketState memory market,
        PYIndex index,
        uint256 minSyOut,
        uint256 blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netYtIn*/ uint256, /*netSyOut*/ uint256 /*netSyFee*/) {
        MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
        if (approx.guessOffchain == 0) {
            // no limit on min
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt));
            validateApprox(approx);
        }

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);

            (uint256 netSyOwed, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess);

            uint256 netAssetToRepay = index.syToAssetUp(netSyOwed);
            uint256 netSyOut = index.assetToSy(guess - netAssetToRepay);

            if (netSyOut >= minSyOut) {
                if (PMath.isAGreaterApproxB(netSyOut, minSyOut, approx.eps)) {
                    return (guess, netSyOut, netSyFee);
                }
                approx.guessMax = guess;
            } else {
                approx.guessMin = guess + 1;
            }
        }
        revert Errors.ApproxFail();
    }

    struct Args6 {
        MarketState market;
        PYIndex index;
        uint256 totalSyIn;
        uint256 netPtHolding;
        uint256 blockTime;
        ApproxParams approx;
    }

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swapExactOut
     *     - Swap that amount of PT out
     *     - Pair the remaining PT with the SY to add liquidity
     *     - Stop when the ratio of PT / totalPt & SY / totalSy is approx
     *     - guess & approx is for netPtFromSwap
     */
    function approxSwapSyToAddLiquidity(
        MarketState memory _market,
        PYIndex _index,
        uint256 _totalSyIn,
        uint256 _netPtHolding,
        uint256 _blockTime,
        ApproxParams memory _approx
    ) internal pure returns (uint256, /*netPtFromSwap*/ uint256, /*netSySwap*/ uint256 /*netSyFee*/) {
        Args6 memory a = Args6(_market, _index, _totalSyIn, _netPtHolding, _blockTime, _approx);

        MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime);
        if (a.approx.guessOffchain == 0) {
            // no limit on min
            a.approx.guessMax = PMath.min(a.approx.guessMax, calcMaxPtOut(comp, a.market.totalPt));
            validateApprox(a.approx);
            require(a.market.totalLp != 0, "no existing lp");
        }

        for (uint256 iter = 0; iter < a.approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(a.approx, iter);

            (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) = calcSyIn(a.market, comp, a.index, guess);

            if (netSyIn > a.totalSyIn) {
                a.approx.guessMax = guess - 1;
                continue;
            }

            uint256 syNumerator;
            uint256 ptNumerator;

            {
                uint256 newTotalPt = uint256(a.market.totalPt) - guess;
                uint256 netTotalSy = uint256(a.market.totalSy) + netSyIn - netSyToReserve;

                // it is desired that
                // (netPtFromSwap + netPtHolding) / newTotalPt = netSyRemaining / netTotalSy
                // which is equivalent to
                // (netPtFromSwap + netPtHolding) * netTotalSy = netSyRemaining * newTotalPt

                ptNumerator = (guess + a.netPtHolding) * netTotalSy;
                syNumerator = (a.totalSyIn - netSyIn) * newTotalPt;
            }

            if (PMath.isAApproxB(ptNumerator, syNumerator, a.approx.eps)) {
                return (guess, netSyIn, netSyFee);
            }

            if (ptNumerator <= syNumerator) {
                // needs more PT
                a.approx.guessMin = guess + 1;
            } else {
                // needs less PT
                a.approx.guessMax = guess - 1;
            }
        }
        revert Errors.ApproxFail();
    }

    /**
     * @dev algorithm:
     *     - Bin search the amount of PT to swapExactOut
     *     - Flashswap that amount of PT out
     *     - Pair all the PT with the YT to redeem SY
     *     - Use the SY to repay the flashswap debt
     *     - Stop when the amount of YT required to pair with PT is approx exactYtIn
     *     - guess & approx is for netPtFromSwap
     */
    function approxSwapExactYtForPt(
        MarketState memory market,
        PYIndex index,
        uint256 exactYtIn,
        uint256 blockTime,
        ApproxParams memory approx
    ) internal pure returns (uint256, /*netPtOut*/ uint256, /*totalPtSwapped*/ uint256 /*netSyFee*/) {
        MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
        if (approx.guessOffchain == 0) {
            approx.guessMin = PMath.max(approx.guessMin, exactYtIn);
            approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt));
            validateApprox(approx);
        }

        for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
            uint256 guess = nextGuess(approx, iter);

            (uint256 netSyOwed, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess);

            uint256 netYtToPull = index.syToAssetUp(netSyOwed);

            if (netYtToPull <= exactYtIn) {
                if (PMath.isASmallerApproxB(netYtToPull, exactYtIn, approx.eps)) {
                    return (guess - netYtToPull, guess, netSyFee);
                }
                approx.guessMin = guess;
            } else {
                approx.guessMax = guess - 1;
            }
        }
        revert Errors.ApproxFail();
    }

    ////////////////////////////////////////////////////////////////////////////////

    function calcSyIn(
        MarketState memory market,
        MarketPreCompute memory comp,
        PYIndex index,
        uint256 netPtOut
    ) internal pure returns (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) {
        (int256 _netSyIn, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, int256(netPtOut));

        // all safe since totalPt and totalSy is int128
        netSyIn = uint256(-_netSyIn);
        netSyFee = uint256(_netSyFee);
        netSyToReserve = uint256(_netSyToReserve);
    }

    function calcMaxPtOut(MarketPreCompute memory comp, int256 totalPt) internal pure returns (uint256) {
        int256 logitP = (comp.feeRate - comp.rateAnchor).mulDown(comp.rateScalar).exp();
        int256 proportion = logitP.divDown(logitP + PMath.IONE);
        int256 numerator = proportion.mulDown(totalPt + comp.totalAsset);
        int256 maxPtOut = totalPt - numerator;
        // only get 99.9% of the theoretical max to accommodate some precision issues
        return (uint256(maxPtOut) * 999) / 1000;
    }

    function nextGuess(ApproxParams memory approx, uint256 iter) internal pure returns (uint256) {
        if (iter == 0 && approx.guessOffchain != 0) return approx.guessOffchain;
        if (approx.guessMin <= approx.guessMax) return (approx.guessMin + approx.guessMax) / 2;
        revert Errors.ApproxFail();
    }

    function validateApprox(ApproxParams memory approx) internal pure {
        if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) {
            revert Errors.ApproxParamsInvalid(approx.guessMin, approx.guessMax, approx.eps);
        }
    }
}

File 8 of 36 : IPActionAddRemoveLiqV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "../router/base/MarketApproxLib.sol";
import "./IPAllActionTypeV3.sol";

interface IPActionAddRemoveLiqV3 {
    event AddLiquidityDualSyAndPt(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netSyUsed,
        uint256 netPtUsed,
        uint256 netLpOut
    );

    event AddLiquidityDualTokenAndPt(
        address indexed caller,
        address indexed market,
        address indexed tokenIn,
        address receiver,
        uint256 netTokenUsed,
        uint256 netPtUsed,
        uint256 netLpOut,
        uint256 netSyInterm
    );

    event AddLiquiditySinglePt(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netPtIn,
        uint256 netLpOut
    );

    event AddLiquiditySingleSy(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netSyIn,
        uint256 netLpOut
    );

    event AddLiquiditySingleToken(
        address indexed caller,
        address indexed market,
        address indexed token,
        address receiver,
        uint256 netTokenIn,
        uint256 netLpOut,
        uint256 netSyInterm
    );

    event AddLiquiditySingleSyKeepYt(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netSyIn,
        uint256 netSyMintPy,
        uint256 netLpOut,
        uint256 netYtOut
    );

    event AddLiquiditySingleTokenKeepYt(
        address indexed caller,
        address indexed market,
        address indexed token,
        address receiver,
        uint256 netTokenIn,
        uint256 netLpOut,
        uint256 netYtOut,
        uint256 netSyMintPy,
        uint256 netSyInterm
    );

    event RemoveLiquidityDualSyAndPt(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netLpToRemove,
        uint256 netPtOut,
        uint256 netSyOut
    );

    event RemoveLiquidityDualTokenAndPt(
        address indexed caller,
        address indexed market,
        address indexed tokenOut,
        address receiver,
        uint256 netLpToRemove,
        uint256 netPtOut,
        uint256 netTokenOut,
        uint256 netSyInterm
    );

    event RemoveLiquiditySinglePt(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netLpToRemove,
        uint256 netPtOut
    );

    event RemoveLiquiditySingleSy(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        uint256 netLpToRemove,
        uint256 netSyOut
    );

    event RemoveLiquiditySingleToken(
        address indexed caller,
        address indexed market,
        address indexed token,
        address receiver,
        uint256 netLpToRemove,
        uint256 netTokenOut,
        uint256 netSyInterm
    );

    function addLiquidityDualTokenAndPt(
        address receiver,
        address market,
        TokenInput calldata input,
        uint256 netPtDesired,
        uint256 minLpOut
    ) external payable returns (uint256 netLpOut, uint256 netPtUsed, uint256 netSyInterm);

    function addLiquidityDualSyAndPt(
        address receiver,
        address market,
        uint256 netSyDesired,
        uint256 netPtDesired,
        uint256 minLpOut
    ) external returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed);

    function addLiquiditySinglePt(
        address receiver,
        address market,
        uint256 netPtIn,
        uint256 minLpOut,
        ApproxParams calldata guessPtSwapToSy,
        LimitOrderData calldata limit
    ) external returns (uint256 netLpOut, uint256 netSyFee);

    function addLiquiditySingleToken(
        address receiver,
        address market,
        uint256 minLpOut,
        ApproxParams calldata guessPtReceivedFromSy,
        TokenInput calldata input,
        LimitOrderData calldata limit
    ) external payable returns (uint256 netLpOut, uint256 netSyFee, uint256 netSyInterm);

    function addLiquiditySingleSy(
        address receiver,
        address market,
        uint256 netSyIn,
        uint256 minLpOut,
        ApproxParams calldata guessPtReceivedFromSy,
        LimitOrderData calldata limit
    ) external returns (uint256 netLpOut, uint256 netSyFee);

    function addLiquiditySingleTokenKeepYt(
        address receiver,
        address market,
        uint256 minLpOut,
        uint256 minYtOut,
        TokenInput calldata input
    ) external payable returns (uint256 netLpOut, uint256 netYtOut, uint256 netSyMintPy, uint256 netSyInterm);

    function addLiquiditySingleSyKeepYt(
        address receiver,
        address market,
        uint256 netSyIn,
        uint256 minLpOut,
        uint256 minYtOut
    ) external returns (uint256 netLpOut, uint256 netYtOut, uint256 netSyMintPy);

    function removeLiquidityDualTokenAndPt(
        address receiver,
        address market,
        uint256 netLpToRemove,
        TokenOutput calldata output,
        uint256 minPtOut
    ) external returns (uint256 netTokenOut, uint256 netPtOut, uint256 netSyInterm);

    function removeLiquidityDualSyAndPt(
        address receiver,
        address market,
        uint256 netLpToRemove,
        uint256 minSyOut,
        uint256 minPtOut
    ) external returns (uint256 netSyOut, uint256 netPtOut);

    function removeLiquiditySinglePt(
        address receiver,
        address market,
        uint256 netLpToRemove,
        uint256 minPtOut,
        ApproxParams calldata guessPtReceivedFromSy,
        LimitOrderData calldata limit
    ) external returns (uint256 netPtOut, uint256 netSyFee);

    function removeLiquiditySingleToken(
        address receiver,
        address market,
        uint256 netLpToRemove,
        TokenOutput calldata output,
        LimitOrderData calldata limit
    ) external returns (uint256 netTokenOut, uint256 netSyFee, uint256 netSyInterm);

    function removeLiquiditySingleSy(
        address receiver,
        address market,
        uint256 netLpToRemove,
        uint256 minSyOut,
        LimitOrderData calldata limit
    ) external returns (uint256 netSyOut, uint256 netSyFee);
}

File 9 of 36 : IPPrincipalToken.sol
// 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);
}

File 10 of 36 : IStandardizedYield.sol
// 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);
}

File 11 of 36 : IPYieldToken.sol
// 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);
}

File 12 of 36 : IPMarket.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IPPrincipalToken.sol";
import "./IPYieldToken.sol";
import "./IStandardizedYield.sol";
import "./IPGauge.sol";
import "../core/Market/MarketMathCore.sol";

interface IPMarket is IERC20Metadata, IPGauge {
    event Mint(address indexed receiver, uint256 netLpMinted, uint256 netSyUsed, uint256 netPtUsed);

    event Burn(
        address indexed receiverSy,
        address indexed receiverPt,
        uint256 netLpBurned,
        uint256 netSyOut,
        uint256 netPtOut
    );

    event Swap(
        address indexed caller,
        address indexed receiver,
        int256 netPtOut,
        int256 netSyOut,
        uint256 netSyFee,
        uint256 netSyToReserve
    );

    event UpdateImpliedRate(uint256 indexed timestamp, uint256 lnLastImpliedRate);

    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    function mint(
        address receiver,
        uint256 netSyDesired,
        uint256 netPtDesired
    ) external returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed);

    function burn(
        address receiverSy,
        address receiverPt,
        uint256 netLpToBurn
    ) external returns (uint256 netSyOut, uint256 netPtOut);

    function swapExactPtForSy(
        address receiver,
        uint256 exactPtIn,
        bytes calldata data
    ) external returns (uint256 netSyOut, uint256 netSyFee);

    function swapSyForExactPt(
        address receiver,
        uint256 exactPtOut,
        bytes calldata data
    ) external returns (uint256 netSyIn, uint256 netSyFee);

    function redeemRewards(address user) external returns (uint256[] memory);

    function readState(address router) external view returns (MarketState memory market);

    function observe(uint32[] memory secondsAgos) external view returns (uint216[] memory lnImpliedRateCumulative);

    function increaseObservationsCardinalityNext(uint16 cardinalityNext) external;

    function readTokens() external view returns (IStandardizedYield _SY, IPPrincipalToken _PT, IPYieldToken _YT);

    function getRewardTokens() external view returns (address[] memory);

    function isExpired() external view returns (bool);

    function expiry() external view returns (uint256);

    function observations(
        uint256 index
    ) external view returns (uint32 blockTimestamp, uint216 lnImpliedRateCumulative, bool initialized);

    function _storage()
        external
        view
        returns (
            int128 totalPt,
            int128 totalSy,
            uint96 lastLnImpliedRate,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext
        );
}

File 13 of 36 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

/* solhint-disable func-visibility, no-inline-assembly */

error Math__toInt256_overflow();
error Math__toUint64_overflow();
error Math__add_overflow_signed();
error Math__sub_overflow_signed();
error Math__mul_overflow_signed();
error Math__mul_overflow();
error Math__div_overflow();

uint256 constant WAD = 1e18;

/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/SafeCastLib.sol#L367
function toInt256(uint256 x) pure returns (int256) {
    if (x >= 1 << 255) revert Math__toInt256_overflow();
    return int256(x);
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/SafeCastLib.sol#L53
function toUint64(uint256 x) pure returns (uint64) {
    if (x >= 1 << 64) revert Math__toUint64_overflow();
    return uint64(x);
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/FixedPointMathLib.sol#L602
function abs(int256 x) pure returns (uint256 z) {
    assembly ("memory-safe") {
        let mask := sub(0, shr(255, x))
        z := xor(mask, add(mask, x))
    }
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/FixedPointMathLib.sol#L620
function min(uint256 x, uint256 y) pure returns (uint256 z) {
    assembly ("memory-safe") {
        z := xor(x, mul(xor(x, y), lt(y, x)))
    }
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/FixedPointMathLib.sol#L628
function min(int256 x, int256 y) pure returns (int256 z) {
    assembly ("memory-safe") {
        z := xor(x, mul(xor(x, y), slt(y, x)))
    }
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/FixedPointMathLib.sol#L636
function max(uint256 x, uint256 y) pure returns (uint256 z) {
    assembly ("memory-safe") {
        z := xor(x, mul(xor(x, y), gt(y, x)))
    }
}

/// @dev Taken from https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/vat.sol#L74
function add(uint256 x, int256 y) pure returns (uint256 z) {
    assembly ("memory-safe") {
        z := add(x, y)
    }
    if ((y > 0 && z < x) || (y < 0 && z > x)) revert Math__add_overflow_signed();
}

/// @dev Taken from https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/vat.sol#L79
function sub(uint256 x, int256 y) pure returns (uint256 z) {
    assembly ("memory-safe") {
        z := sub(x, y)
    }
    if ((y > 0 && z > x) || (y < 0 && z < x)) revert Math__sub_overflow_signed();
}

/// @dev Taken from https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/vat.sol#L84
function mul(uint256 x, int256 y) pure returns (int256 z) {
    unchecked {
        z = int256(x) * y;
        if (int256(x) < 0 || (y != 0 && z / y != int256(x))) revert Math__mul_overflow_signed();
    }
}

/// @dev Equivalent to `(x * y) / WAD` rounded down.
/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/FixedPointMathLib.sol#L54
function wmul(uint256 x, uint256 y) pure returns (uint256 z) {
    assembly ("memory-safe") {
        // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
        if mul(y, gt(x, div(not(0), y))) {
            // Store the function selector of `Math__mul_overflow()`.
            mstore(0x00, 0xc4c5d7f5)

            // Revert with (offset, size).
            revert(0x1c, 0x04)
        }
        z := div(mul(x, y), WAD)
    }
}

function wmul(uint256 x, int256 y) pure returns (int256 z) {
    unchecked {
        z = mul(x, y) / int256(WAD);
    }
}

/// @dev Equivalent to `(x * y) / WAD` rounded up.
/// @dev Taken from https://github.com/Vectorized/solady/blob/969a78905274b32cdb7907398c443f7ea212e4f4/src/utils/FixedPointMathLib.sol#L69C22-L69C22
function wmulUp(uint256 x, uint256 y) pure returns (uint256 z) {
    /// @solidity memory-safe-assembly
    assembly {
        // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
        if mul(y, gt(x, div(not(0), y))) {
            // Store the function selector of `Math__mul_overflow()`.
            mstore(0x00, 0xc4c5d7f5)
            // Revert with (offset, size).
            revert(0x1c, 0x04)
        }
        z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
    }
}

/// @dev Equivalent to `(x * WAD) / y` rounded down.
/// @dev Taken from https://github.com/Vectorized/solady/blob/6d706e05ef43cbed234c648f83c55f3a4bb0a520/src/utils/FixedPointMathLib.sol#L84
function wdiv(uint256 x, uint256 y) pure returns (uint256 z) {
    assembly ("memory-safe") {
        // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
        if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
            // Store the function selector of `Math__div_overflow()`.
            mstore(0x00, 0xbcbede65)

            // Revert with (offset, size).
            revert(0x1c, 0x04)
        }
        z := div(mul(x, WAD), y)
    }
}

/// @dev Equivalent to `(x * WAD) / y` rounded up.
/// @dev Taken from https://github.com/Vectorized/solady/blob/969a78905274b32cdb7907398c443f7ea212e4f4/src/utils/FixedPointMathLib.sol#L99
function wdivUp(uint256 x, uint256 y) pure returns (uint256 z) {
    /// @solidity memory-safe-assembly
    assembly {
        // Equivalent to `require(y != 0 && (WAD == 0 || x <= type(uint256).max / WAD))`.
        if iszero(mul(y, iszero(mul(WAD, gt(x, div(not(0), WAD)))))) {
            // Store the function selector of `Math__div_overflow()`.
            mstore(0x00, 0xbcbede65)
            // Revert with (offset, size).
            revert(0x1c, 0x04)
        }
        z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
    }
}

/// @dev Taken from https://github.com/makerdao/dss/blob/fa4f6630afb0624d04a003e920b0d71a00331d98/src/jug.sol#L62
function wpow(uint256 x, uint256 n, uint256 b) pure returns (uint256 z) {
    unchecked {
        assembly ("memory-safe") {
            switch n
            case 0 {
                z := b
            }
            default {
                switch x
                case 0 {
                    z := 0
                }
                default {
                    switch mod(n, 2)
                    case 0 {
                        z := b
                    }
                    default {
                        z := x
                    }
                    let half := div(b, 2) // for rounding.
                    for {
                        n := div(n, 2)
                    } n {
                        n := div(n, 2)
                    } {
                        let xx := mul(x, x)
                        if shr(128, x) {
                            revert(0, 0)
                        }
                        let xxRound := add(xx, half)
                        if lt(xxRound, xx) {
                            revert(0, 0)
                        }
                        x := div(xxRound, b)
                        if mod(n, 2) {
                            let zx := mul(z, x)
                            if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
                                revert(0, 0)
                            }
                            let zxRound := add(zx, half)
                            if lt(zxRound, zx) {
                                revert(0, 0)
                            }
                            z := div(zxRound, b)
                        }
                    }
                }
            }
        }
    }
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/cde0a5fb594da8655ba6bfcdc2e40a7c870c0cc0/src/utils/FixedPointMathLib.sol#L110
/// @dev Equivalent to `x` to the power of `y`.
/// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
function wpow(int256 x, int256 y) pure returns (int256) {
    // Using `ln(x)` means `x` must be greater than 0.
    return wexp((wln(x) * y) / int256(WAD));
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/cde0a5fb594da8655ba6bfcdc2e40a7c870c0cc0/src/utils/FixedPointMathLib.sol#L116
/// @dev Returns `exp(x)`, denominated in `WAD`.
function wexp(int256 x) pure returns (int256 r) {
    unchecked {
        // When the result is < 0.5 we return zero. This happens when
        // x <= floor(log(0.5e18) * 1e18) ~ -42e18
        if (x <= -42139678854452767551) return r;

        /// @solidity memory-safe-assembly
        assembly {
            // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
            // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
            if iszero(slt(x, 135305999368893231589)) {
                mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                revert(0x1c, 0x04)
            }
        }

        // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
        // for more intermediate precision and a binary basis. This base conversion
        // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
        x = (x << 78) / 5 ** 18;

        // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
        // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
        // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
        int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
        x = x - k * 54916777467707473351141471128;

        // k is in the range [-61, 195].

        // Evaluate using a (6, 7)-term rational approximation.
        // p is made monic, we'll multiply by a scale factor later.
        int256 y = x + 1346386616545796478920950773328;
        y = ((y * x) >> 96) + 57155421227552351082224309758442;
        int256 p = y + x - 94201549194550492254356042504812;
        p = ((p * y) >> 96) + 28719021644029726153956944680412240;
        p = p * x + (4385272521454847904659076985693276 << 96);

        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        int256 q = x - 2855989394907223263936484059900;
        q = ((q * x) >> 96) + 50020603652535783019961831881945;
        q = ((q * x) >> 96) - 533845033583426703283633433725380;
        q = ((q * x) >> 96) + 3604857256930695427073651918091429;
        q = ((q * x) >> 96) - 14423608567350463180887372962807573;
        q = ((q * x) >> 96) + 26449188498355588339934803723976023;

        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial won't have zeros in the domain as all its roots are complex.
            // No scaling is necessary because p is already 2**96 too large.
            r := sdiv(p, q)
        }

        // r should be in the range (0.09, 0.25) * 2**96.

        // We now need to multiply r by:
        // * the scale factor s = ~6.031367120.
        // * the 2**k factor from the range reduction.
        // * the 1e18 / 2**96 factor for base conversion.
        // We do this all at once, with an intermediate result in 2**213
        // basis, so the final right shift is always by a positive amount.
        r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
    }
}

/// @dev Taken from https://github.com/Vectorized/solady/blob/cde0a5fb594da8655ba6bfcdc2e40a7c870c0cc0/src/utils/FixedPointMathLib.sol#L184
/// @dev Returns `ln(x)`, denominated in `WAD`.
function wln(int256 x) pure returns (int256 r) {
    unchecked {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
        }

        // We want to convert x from 10**18 fixed point to 2**96 fixed point.
        // We do this by multiplying by 2**96 / 10**18. But since
        // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
        // and add ln(2**96 / 10**18) at the end.

        // Compute k = log2(x) - 96, t = 159 - k = 255 - log2(x) = 255 ^ log2(x).
        int256 t;
        /// @solidity memory-safe-assembly
        assembly {
            t := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            t := or(t, shl(6, lt(0xffffffffffffffff, shr(t, x))))
            t := or(t, shl(5, lt(0xffffffff, shr(t, x))))
            t := or(t, shl(4, lt(0xffff, shr(t, x))))
            t := or(t, shl(3, lt(0xff, shr(t, x))))
            // forgefmt: disable-next-item
            t := xor(
                t,
                byte(
                    and(0x1f, shr(shr(t, x), 0x8421084210842108cc6318c6db6d54be)),
                    0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff
                )
            )
        }

        // Reduce range of x to (1, 2) * 2**96
        // ln(2^k * x) = k * ln(2) + ln(x)
        x = int256(uint256(x << uint256(t)) >> 159);

        // Evaluate using a (8, 8)-term rational approximation.
        // p is made monic, we will multiply by a scale factor later.
        int256 p = x + 3273285459638523848632254066296;
        p = ((p * x) >> 96) + 24828157081833163892658089445524;
        p = ((p * x) >> 96) + 43456485725739037958740375743393;
        p = ((p * x) >> 96) - 11111509109440967052023855526967;
        p = ((p * x) >> 96) - 45023709667254063763336534515857;
        p = ((p * x) >> 96) - 14706773417378608786704636184526;
        p = p * x - (795164235651350426258249787498 << 96);

        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        // q is monic by convention.
        int256 q = x + 5573035233440673466300451813936;
        q = ((q * x) >> 96) + 71694874799317883764090561454958;
        q = ((q * x) >> 96) + 283447036172924575727196451306956;
        q = ((q * x) >> 96) + 401686690394027663651624208769553;
        q = ((q * x) >> 96) + 204048457590392012362485061816622;
        q = ((q * x) >> 96) + 31853899698501571402653359427138;
        q = ((q * x) >> 96) + 909429971244387300277376558375;
        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already 2**96 too large.
            r := sdiv(p, q)
        }

        // r is in the range (0, 0.125) * 2**96

        // Finalization, we need to:
        // * multiply by the scale factor s = 5.549…
        // * add ln(2**96 / 10**18)
        // * add k * ln(2)
        // * multiply by 10**18 / 2**96 = 5**18 >> 78

        // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
        r *= 1677202110996718588342820967067443963516166;
        // add ln(2) * k * 5e18 * 2**192
        r += 16597577552685614221487285958193947469193820559219878177908093499208371 * (159 - t);
        // add ln(2**96 / 10**18) * 5e18 * 2**192
        r += 600920179829731861736702779321621459595472258049074101567377883020018308;
        // base conversion: mul 2**18 / 2**192
        r >>= 174;
    }
}

File 14 of 36 : TransferAction.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import {ISignatureTransfer} from "permit2/interfaces/ISignatureTransfer.sol";

enum ApprovalType {
    STANDARD,
    PERMIT,
    PERMIT2
}

struct PermitParams {
    ApprovalType approvalType;
    uint256 approvalAmount;
    uint256 nonce;
    uint256 deadline;
    uint8 v;
    bytes32 r;
    bytes32 s;
}

abstract contract TransferAction {
    /*//////////////////////////////////////////////////////////////
                               LIBRARIES
    //////////////////////////////////////////////////////////////*/

    using SafeERC20 for IERC20;
    using SafeERC20 for IERC20Permit;

    /*//////////////////////////////////////////////////////////////
                               CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /// @notice Permit2
    address public constant permit2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /*//////////////////////////////////////////////////////////////
                               FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Perform a permit2, a ERC20 permit transferFrom, or a standard transferFrom
    function _transferFrom(
        address token,
        address from,
        address to,
        uint256 amount,
        PermitParams memory params
    ) internal {
        if (params.approvalType == ApprovalType.PERMIT2) {
            // Consume a permit2 message and transfer tokens.
            ISignatureTransfer(permit2).permitTransferFrom(
                ISignatureTransfer.PermitTransferFrom({
                    permitted: ISignatureTransfer.TokenPermissions({token: token, amount: params.approvalAmount}),
                    nonce: params.nonce,
                    deadline: params.deadline
                }),
                ISignatureTransfer.SignatureTransferDetails({to: to, requestedAmount: amount}),
                from,
                bytes.concat(params.r, params.s, bytes1(params.v)) // Construct signature
            );
        } else if (params.approvalType == ApprovalType.PERMIT) {
            // Consume a standard ERC20 permit message
            IERC20Permit(token).safePermit(
                from,
                to,
                params.approvalAmount,
                params.deadline,
                params.v,
                params.r,
                params.s
            );
            IERC20(token).safeTransferFrom(from, to, amount);
        } else {
            // No signature provided, just transfer tokens.
            IERC20(token).safeTransferFrom(from, to, amount);
        }
    }
}

File 15 of 36 : ISwapRouterTranchess.sol
pragma solidity ^0.8.4;

interface ISwapRouter {
    function addLiquidity(
        address baseToken,
        address quoteToken,
        uint256 baseDelta,
        uint256 quoteDelta,
        uint256 minMintAmount,
        uint256 version,
        uint256 deadline
    ) external payable;
}

File 16 of 36 : IStableSwapTranchess.sol
pragma solidity ^0.8.4;

interface IStableSwap {
    function baseTranche() external view returns (uint256);

    function baseAddress() external view returns (address);

    function quoteAddress() external view returns (address);

    function allBalances() external view returns (uint256, uint256);

    function getOraclePrice() external view returns (uint256);

    function getCurrentD() external view returns (uint256);

    function getCurrentPriceOverOracle() external view returns (uint256);

    function getCurrentPrice() external view returns (uint256);

    function getPriceOverOracleIntegral() external view returns (uint256);

    function addLiquidity(uint256 version, address recipient) external returns (uint256);

    function removeLiquidity(
        uint256 version,
        uint256 lpIn,
        uint256 minBaseOut,
        uint256 minQuoteOut
    ) external returns (uint256 baseOut, uint256 quoteOut);

    function removeLiquidityUnwrap(
        uint256 version,
        uint256 lpIn,
        uint256 minBaseOut,
        uint256 minQuoteOut
    ) external returns (uint256 baseOut, uint256 quoteOut);

    function removeBaseLiquidity(uint256 version, uint256 lpIn, uint256 minBaseOut) external returns (uint256 baseOut);

    function removeQuoteLiquidity(
        uint256 version,
        uint256 lpIn,
        uint256 minQuoteOut
    ) external returns (uint256 quoteOut);

    function removeQuoteLiquidityUnwrap(
        uint256 version,
        uint256 lpIn,
        uint256 minQuoteOut
    ) external returns (uint256 quoteOut);
}

File 17 of 36 : ISpectraRouter.sol
pragma solidity ^0.8.19;

interface ISpectraRouter {
    /**
     * @dev Executes encoded commands along with provided inputs
     * Reverts if deadline has expired
     * @param _commands A set of concatenated commands, each 1 byte in length
     * @param _inputs An array of byte strings containing ABI-encoded inputs for each command
     * @param _deadline The deadline by which the transaction must be executed
     */
    function execute(bytes calldata _commands, bytes[] calldata _inputs, uint256 _deadline) external payable;
}

File 18 of 36 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}

File 19 of 36 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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.5.11/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 20 of 36 : IAsset.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.7.0 <0.9.0;

/**
 * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
 * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
 * types.
 *
 * This concept is unrelated to a Pool's Asset Managers.
 */
interface IAsset {
    // solhint-disable-previous-line no-empty-blocks
}

File 21 of 36 : IPSwapAggregator.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

struct SwapData {
    SwapType swapType;
    address extRouter;
    bytes extCalldata;
    bool needScale;
}

enum SwapType {
    NONE,
    KYBERSWAP,
    ONE_INCH,
    // ETH_WETH not used in Aggregator
    ETH_WETH
}

interface IPSwapAggregator {
    function swap(address tokenIn, uint256 amountIn, SwapData calldata swapData) external payable;
}

File 22 of 36 : IPLimitRouter.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

File 23 of 36 : 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;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

File 24 of 36 : MarketMathCore.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

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

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

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

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

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

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

    using PMath for uint256;
    using PMath for int256;

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

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

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

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

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

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

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

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

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

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

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

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

        if (lpToAccount <= 0) 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
        );
    }
}

File 25 of 36 : IERC20Metadata.sol
// 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);
}

File 26 of 36 : IRewardManager.sol
// 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);
}

File 27 of 36 : IPInterestManagerYT.sol
// 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);
}

File 28 of 36 : IPGauge.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPGauge {
    function totalActiveSupply() external view returns (uint256);

    function activeBalance(address user) external view returns (uint256);

    // only available for newer factories. please check the verified contracts
    event RedeemRewards(address indexed user, uint256[] rewardsOut);
}

File 29 of 36 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// EIP-2612 is Final as of 2022-11-01. This file is deprecated.

import "./IERC20Permit.sol";

File 30 of 36 : ISignatureTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import {IEIP712} from "./IEIP712.sol";

/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
    /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
    /// @param maxAmount The maximum amount a spender can request to transfer
    error InvalidAmount(uint256 maxAmount);

    /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
    /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
    error LengthMismatch();

    /// @notice Emits an event when the owner successfully invalidates an unordered nonce.
    event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);

    /// @notice The token and amount details for a transfer signed in the permit transfer signature
    struct TokenPermissions {
        // ERC20 token address
        address token;
        // the maximum amount that can be spent
        uint256 amount;
    }

    /// @notice The signed permit message for a single token transfer
    struct PermitTransferFrom {
        TokenPermissions permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice Specifies the recipient address and amount for batched transfers.
    /// @dev Recipients and amounts correspond to the index of the signed token permissions array.
    /// @dev Reverts if the requested amount is greater than the permitted signed amount.
    struct SignatureTransferDetails {
        // recipient address
        address to;
        // spender requested amount
        uint256 requestedAmount;
    }

    /// @notice Used to reconstruct the signed permit message for multiple token transfers
    /// @dev Do not need to pass in spender address as it is required that it is msg.sender
    /// @dev Note that a user still signs over a spender address
    struct PermitBatchTransferFrom {
        // the tokens and corresponding amounts permitted for a transfer
        TokenPermissions[] permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
    /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
    /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
    /// @dev It returns a uint256 bitmap
    /// @dev The index, or wordPosition is capped at type(uint248).max
    function nonceBitmap(address, uint256) external view returns (uint256);

    /// @notice Transfers a token using a signed permit message
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers a token using a signed permit message
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Invalidates the bits specified in mask for the bitmap at the word position
    /// @dev The wordPos is maxed at type(uint248).max
    /// @param wordPos A number to index the nonceBitmap at
    /// @param mask A bitmap masked against msg.sender's current bitmap at the word position
    function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}

File 31 of 36 : PYIndex.sol
// 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();
    }
}

File 32 of 36 : LogExpMath.sol
// 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 33 of 36 : MiniHelpers.sol
// 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
    }
}

File 34 of 36 : 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);

    // Liquidity Mining
    error VCInactivePool(address pool);
    error VCPoolAlreadyActive(address pool);
    error VCZeroVePendle(address user);
    error VCExceededMaxWeight(uint256 totalWeight, uint256 maxWeight);
    error VCEpochNotFinalized(uint256 wTime);
    error VCPoolAlreadyAddAndRemoved(address pool);

    error VEInvalidNewExpiry(uint256 newExpiry);
    error VEExceededMaxLockTime();
    error VEInsufficientLockTime();
    error VENotAllowedReduceExpiry();
    error VEZeroAmountLocked();
    error VEPositionNotExpired();
    error VEZeroPosition();
    error VEZeroSlope(uint128 bias, uint128 slope);
    error VEReceiveOldSupply(uint256 msgTime);

    error GCNotPendleMarket(address caller);
    error GCNotVotingController(address caller);

    error InvalidWTime(uint256 wTime);
    error ExpiryInThePast(uint256 expiry);
    error ChainNotSupported(uint256 chainId);

    error FDTotalAmountFundedNotMatch(uint256 actualTotalAmount, uint256 expectedTotalAmount);
    error FDEpochLengthMismatch();
    error FDInvalidPool(address pool);
    error FDPoolAlreadyExists(address pool);
    error FDInvalidNewFinishedEpoch(uint256 oldFinishedEpoch, uint256 newFinishedEpoch);
    error FDInvalidStartEpoch(uint256 startEpoch);
    error FDInvalidWTimeFund(uint256 lastFunded, uint256 wTime);
    error FDFutureFunding(uint256 lastFunded, uint256 currentWTime);

    error BDInvalidEpoch(uint256 epoch, uint256 startTime);

    // Cross-Chain
    error MsgNotFromSendEndpoint(uint16 srcChainId, bytes path);
    error MsgNotFromReceiveEndpoint(address sender);
    error InsufficientFeeToSendMsg(uint256 currentFee, uint256 requiredFee);
    error ApproxDstExecutionGasNotSet();
    error InvalidRetryData();

    // GENERIC MSG
    error ArrayLengthMismatch();
    error ArrayEmpty();
    error ArrayOutOfBounds();
    error ZeroAddress();
    error FailedToSendEther();
    error InvalidMerkleProof();

    error OnlyLayerZeroEndpoint();
    error OnlyYT();
    error OnlyYCFactory();
    error OnlyWhitelisted();

    // Swap Aggregator
    error SAInsufficientTokenIn(address tokenIn, uint256 amountExpected, uint256 amountActual);
    error UnsupportedSelector(uint256 aggregatorType, bytes4 selector);
}

File 35 of 36 : IEIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 36 of 36 : SYUtils.sol
// 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;
    }
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "permit2/=lib/permit2/src/",
    "forge-std/=lib/forge-std/src/",
    "prb-proxy/=lib/prb-proxy/src/",
    "layerzerolabs/=lib/layerzerolabs/contracts/",
    "aave-address-book/=lib/aave-address-book/src/",
    "@gearbox-protocol/core-v3/contracts/=lib/core-v3/contracts/",
    "@gearbox-protocol/core-v2/contracts/=lib/core-v2/contracts/",
    "pendle/=lib/pendle/contracts/",
    "tranchess/=lib/contract-core/contracts/",
    "@1inch/=lib/core-v3/node_modules/@1inch/",
    "@aave/core-v3/=lib/aave-address-book/lib/aave-v3-core/",
    "@aave/periphery-v3/=lib/aave-address-book/lib/aave-v3-periphery/",
    "@chainlink/=lib/core-v3/node_modules/@chainlink/",
    "@prb/test/=lib/prb-proxy/lib/prb-test/src/",
    "aave-v3-core/=lib/aave-address-book/lib/aave-v3-core/",
    "aave-v3-periphery/=lib/aave-address-book/lib/aave-v3-periphery/",
    "core-v2/=lib/core-v2/contracts/",
    "core-v3/=lib/core-v3/contracts/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "hardhat-deploy/=node_modules/hardhat-deploy/",
    "hardhat/=node_modules/hardhat/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "prb-test/=lib/prb-proxy/lib/prb-test/src/",
    "solmate/=lib/permit2/lib/solmate/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 100
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "viaIR": false,
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"contract IVault","name":"balancerVault_","type":"address"},{"internalType":"contract IUniswapV3Router","name":"uniRouter_","type":"address"},{"internalType":"contract IPActionAddRemoveLiqV3","name":"pendleRouter_","type":"address"},{"internalType":"address","name":"kyberRouter_","type":"address"},{"internalType":"address","name":"tranchessRouter_","type":"address"},{"internalType":"address","name":"spectraRouter_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"Math__toInt256_overflow","type":"error"},{"inputs":[],"name":"SwapAction__kyberSwap_slippageFailed","type":"error"},{"inputs":[],"name":"SwapAction__revertBytes_emptyRevertBytes","type":"error"},{"inputs":[],"name":"SwapAction__swap_notSupported","type":"error"},{"inputs":[],"name":"UniswapV3Router_decodeLastToken_invalidPath","type":"error"},{"inputs":[],"name":"UniswapV3Router_toAddress_outOfBounds","type":"error"},{"inputs":[],"name":"UniswapV3Router_toAddress_overflow","type":"error"},{"inputs":[],"name":"balancerVault","outputs":[{"internalType":"contract IVault","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"enum SwapProtocol","name":"swapProtocol","type":"uint8"},{"internalType":"enum SwapType","name":"swapType","type":"uint8"},{"internalType":"address","name":"assetIn","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"residualRecipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"args","type":"bytes"}],"internalType":"struct SwapParams","name":"swapParams","type":"tuple"}],"name":"getSwapToken","outputs":[{"internalType":"address","name":"token","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"kyberRouter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendleRouter","outputs":[{"internalType":"contract IPActionAddRemoveLiqV3","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"permit2","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"spectraRouter","outputs":[{"internalType":"contract ISpectraRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"enum SwapProtocol","name":"swapProtocol","type":"uint8"},{"internalType":"enum SwapType","name":"swapType","type":"uint8"},{"internalType":"address","name":"assetIn","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"residualRecipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"args","type":"bytes"}],"internalType":"struct SwapParams","name":"swapParams","type":"tuple"}],"name":"swap","outputs":[{"internalType":"uint256","name":"retAmount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"tranchessRouter","outputs":[{"internalType":"contract ISwapRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"components":[{"internalType":"enum ApprovalType","name":"approvalType","type":"uint8"},{"internalType":"uint256","name":"approvalAmount","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct PermitParams","name":"permitParams","type":"tuple"},{"components":[{"internalType":"enum SwapProtocol","name":"swapProtocol","type":"uint8"},{"internalType":"enum SwapType","name":"swapType","type":"uint8"},{"internalType":"address","name":"assetIn","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"residualRecipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bytes","name":"args","type":"bytes"}],"internalType":"struct SwapParams","name":"swapParams","type":"tuple"}],"name":"transferAndSwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uniRouter","outputs":[{"internalType":"contract IUniswapV3Router","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

6101406040523480156200001257600080fd5b5060405162003af738038062003af783398101604081905262000035916200007e565b6001600160a01b0395861660805293851660a05291841660c052831660e052821661010052166101205262000112565b6001600160a01b03811681146200007b57600080fd5b50565b60008060008060008060c087890312156200009857600080fd5b8651620000a58162000065565b6020880151909650620000b88162000065565b6040880151909550620000cb8162000065565b6060880151909450620000de8162000065565b6080880151909350620000f18162000065565b60a0880151909250620001048162000065565b809150509295509295509295565b60805160a05160c05160e051610100516101205161392e620001c9600039600081816101a401528181611b810152611bbd01526000818160fb0152818161174e0152818161178801526118030152600081816101de01528181610cac0152610cd601526000818161012201528181611029015261106501526000818161016a01528181610dcf01528181610df601528181610ec80152610eef01526000818160d401528181610b640152610b8e015261392e6000f3fe608060405234801561001057600080fd5b506004361061009e5760003560e01c8063a0e47bf611610066578063a0e47bf614610165578063a49cc0cd1461018c578063a639bbfe1461019f578063c0d4a416146101c6578063f63ca6e4146101d957600080fd5b806312261ee7146100a3578063158274a5146100cf5780631fc96635146100f6578063206aeab31461011d578063746f700a14610144575b600080fd5b6100b96e22d473030f116ddee9f6b43ac78ba381565b6040516100c691906122ca565b60405180910390f35b6100b97f000000000000000000000000000000000000000000000000000000000000000081565b6100b97f000000000000000000000000000000000000000000000000000000000000000081565b6100b97f000000000000000000000000000000000000000000000000000000000000000081565b610157610152366004612314565b610200565b6040519081526020016100c6565b6100b97f000000000000000000000000000000000000000000000000000000000000000081565b6100b961019a366004612381565b61028d565b6100b97f000000000000000000000000000000000000000000000000000000000000000081565b6101576101d4366004612605565b6103e2565b6100b97f000000000000000000000000000000000000000000000000000000000000000081565b60006001600160a01b038416301461027957600080610225604085016020860161264f565b600181111561023657610236612639565b1461024557826080013561024b565b82606001355b90506102776102606060850160408601612671565b863084610272368a90038a018a61269f565b6106aa565b505b6102856101d483612736565b949350505050565b60008061029d6020840184612742565b60078111156102ae576102ae612639565b0361034e5760006102c361010084018461275d565b8101906102d0919061283c565b9150600190506102e6604085016020860161264f565b60018111156102f7576102f7612639565b0361031e578060008151811061030f5761030f6128f4565b60200260200101519150610348565b806001825161032d9190612920565b8151811061033d5761033d6128f4565b602002602001015191505b50919050565b600161035d6020840184612742565b600781111561036e5761036e612639565b036103c4576103be61038461010084018461275d565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061087592505050565b92915050565b60405163e11d7ccb60e01b815260040160405180910390fd5b919050565b60008160e0015142111561042e5761042e6040518060400160405280602081526020017f53776170416374696f6e3a207377617020646561646c696e65207061737365648152506108b1565b60008251600781111561044357610443612639565b036104995760008083610100015180602001905181019061046491906129a2565b91509150610490846020015185604001518484886060015189608001518a60a001518b60e001516108d9565b9250505061061b565b6004825160078111156104ae576104ae612639565b1480156104d057506000826020015160018111156104ce576104ce612639565b145b156104f9576104f2826040015183606001518460800151856101000151610c9b565b905061061b565b60018251600781111561050e5761050e612639565b0361053f576104f282602001518360400151846060015185608001518660a001518760e00151886101000151610da6565b60028251600781111561055457610554612639565b03610571576104f28260a001518360800151846101000151610f68565b60038251600781111561058657610586612639565b036105a3576104f28260a0015183608001518461010001516110f6565b6005825160078111156105b8576105b8612639565b036105c6576104f282611582565b6006825160078111156105db576105db612639565b036105f8576104f28260a00151836080015184610100015161190a565b60078251600781111561060d5761060d612639565b036103c4576104f282611a9e565b60018260200151600181111561063357610633612639565b14801561064d575060a08201516001600160a01b03163014155b156103dd5760c08201516001600160a01b031615610692576103dd8260c0015182846080015161067d9190612920565b60408501516001600160a01b03169190611cb1565b6103dd8260a0015182846080015161067d9190612920565b6002815160028111156106bf576106bf612639565b036107e9576e22d473030f116ddee9f6b43ac78ba36001600160a01b03166330f28b7a604051806060016040528060405180604001604052808a6001600160a01b03168152602001866020015181525081526020018460400151815260200184606001518152506040518060400160405280876001600160a01b0316815260200186815250878560a001518660c00151876080015160f81b6040516020016107849392919092835260208301919091526001600160f81b031916604082015260410190565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016107b29493929190612aa3565b600060405180830381600087803b1580156107cc57600080fd5b505af11580156107e0573d6000803e3d6000fd5b5050505061086e565b6001815160028111156107fe576107fe612639565b036108595761083f84848360200151846060015185608001518660a001518760c001518c6001600160a01b0316611d0c90979695949392919063ffffffff16565b6108546001600160a01b038616858585611eec565b61086e565b61086e6001600160a01b038616858585611eec565b5050505050565b600060148251101561089a5760405163d3d6273f60e01b815260040160405180910390fd5b6103be82601484516108ac9190612920565b611f13565b8051156108c057805181602001fd5b604051634811b8df60e11b815260040160405180910390fd5b8551600090816108ea826001612b1c565b6001600160401b03811115610901576109016123b5565b60405190808252806020026020018201604052801561092a578160200160208202803683370190505b5090506000826001600160401b03811115610947576109476123b5565b6040519080825280602002602001820160405280156109ad57816020015b61099a6040518060a0016040528060008019168152602001600081526020016000815260200160008152602001606081525090565b8152602001906001900390816109655790505b5090506060600080808f60018111156109c8576109c8612639565b036109d5575060016109da565b600191505b60005b86811015610a4f576040518060a001604052808f8381518110610a0257610a026128f4565b60200260200101518152602001848301815260200183830181526020016000815260200185815250858281518110610a3c57610a3c6128f4565b60209081029190910101526001016109dd565b508a84600081518110610a6457610a646128f4565b6020908102919091010151606001525060009150819050808e6001811115610a8e57610a8e612639565b03610af657506000905088610aa281611f7c565b84600081518110610ab557610ab56128f4565b602002602001018181525050610aca89611f7c565b610ad390612b2f565b848681518110610ae557610ae56128f4565b602002602001018181525050610b55565b506001905087610b058a611f7c565b610b0e90612b2f565b84600081518110610b2157610b216128f4565b602002602001018181525050610b3689611f7c565b848681518110610b4857610b486128f4565b6020026020010181815250505b610b896001600160a01b038e167f000000000000000000000000000000000000000000000000000000000000000083611fa6565b610c897f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663945bcec984868f6040518060800160405280306001600160a01b031681526020016000151581526020018f6001600160a01b03168152602001600015158152508a8e6040518763ffffffff1660e01b8152600401610c1a96959493929190612bbf565b6000604051808303816000875af1158015610c39573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610c619190810190612ce1565b8681518110610c7257610c726128f4565b602002602001015160ff81901c6000039081011890565b9e9d5050505050505050505050505050565b6000610cd16001600160a01b0386167f000000000000000000000000000000000000000000000000000000000000000086611fa6565b6000807f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031684604051610d0c9190612d66565b6000604051808303816000865af19150503d8060008114610d49576040519150601f19603f3d011682016040523d82523d6000602084013e610d4e565b606091505b509150915081610d6157610d61816108b1565b600081806020019051810190610d779190612d82565b50905085811015610d9b57604051632205896160e01b815260040160405180910390fd5b979650505050505050565b600080886001811115610dbb57610dbb612639565b03610eb957610df46001600160a01b0388167f000000000000000000000000000000000000000000000000000000000000000088611fa6565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663c04b8d596040518060a00160405280858152602001876001600160a01b03168152602001868152602001898152602001888152506040518263ffffffff1660e01b8152600401610e6f9190612df7565b6020604051808303816000875af1158015610e8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eb29190612e0a565b9050610d9b565b610eed6001600160a01b0388167f000000000000000000000000000000000000000000000000000000000000000087611fa6565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f28c04986040518060a00160405280858152602001876001600160a01b03168152602001868152602001898152602001888152506040518263ffffffff1660e01b8152600401610e6f9190612df7565b600080600080600085806020019051810190610f8491906131e4565b8151939750919550935091506001600160a01b03161561104e5781516040516370a0823160e01b81526001600160a01b03909116906370a0823190610fcd9030906004016122ca565b602060405180830381865afa158015610fea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061100e9190612e0a565b60208301819052825161104e916001600160a01b03909116907f000000000000000000000000000000000000000000000000000000000000000090611fa6565b60405163092ccd6360e11b81526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906312599ac6906110a4908b9088908c90899089908990600401613490565b6060604051808303816000875af11580156110c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e79190613589565b50909998505050505050505050565b6000806000808480602001905181019061111091906135b7565b9250925092506000806000856001600160a01b0316632c8ce6bc6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611159573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117d91906135fa565b919450925090506001600160a01b038a16301461120d576040516323b872dd60e01b81526001600160a01b038716906323b872dd906111c4908d908a908a9060040161363c565b6020604051808303816000875af11580156111e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112079190613660565b50611280565b60405163a9059cbb60e01b81526001600160a01b0387169063a9059cbb9061123b908990899060040161367b565b6020604051808303816000875af115801561125a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127e9190613660565b505b6000826001600160a01b0316632f13b60c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e49190613660565b156113e757604051633dae446f60e21b81526000906001600160a01b0389169063f6b911bc9061131c90889087908c9060040161363c565b60408051808303816000875af115801561133a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061135e9190612d82565b5090506000836001600160a01b031663bcb7ea5d876040518263ffffffff1660e01b815260040161138f91906122ca565b6020604051808303816000875af11580156113ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d29190612e0a565b90506113de8183612b1c565b925050506114ea565b600080886001600160a01b031663f6b911bc878b8b6040518463ffffffff1660e01b815260040161141a9392919061363c565b60408051808303816000875af1158015611438573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061145c9190612d82565b91509150606060008a6001600160a01b03166329910b118985856040518463ffffffff1660e01b815260040161149493929190613694565b60408051808303816000875af11580156114b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114d69190612d82565b5090506114e38185612b1c565b9450505050505b60405163769f8e5d60e01b81526001600160a01b038c81166004830152602482018390528681166044830152606482018c90526001608483015285169063769f8e5d9060a4016020604051808303816000875af115801561154f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115739190612e0a565b9b9a5050505050505050505050565b60008060008060008561010001518060200190518101906115a391906136bb565b93509350935093506000846001600160a01b0316639e548b7f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061160f91906136fa565b6001600160a01b0316630589a4786040518163ffffffff1660e01b8152600401602060405180830381865afa15801561164c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061167091906136fa565b90506000856001600160a01b0316639e548b7f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d691906136fa565b6001600160a01b031663f0a0b44e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611713573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061173791906136fa565b90508415611773576117736001600160a01b0383167f000000000000000000000000000000000000000000000000000000000000000087611fa6565b83156117ad576117ad6001600160a01b0382167f000000000000000000000000000000000000000000000000000000000000000086611fa6565b608088015160e0890151604051630f5c0dcb60e31b81526001600160a01b03858116600483015284811660248301526044820189905260648201889052608482019390935260a4810186905260c48101919091527f000000000000000000000000000000000000000000000000000000000000000090911690637ae06e589060e401600060405180830381600087803b15801561184957600080fd5b505af115801561185d573d6000803e3d6000fd5b50506040516370a0823160e01b81526001600160a01b03891692506370a08231915061188d9030906004016122ca565b602060405180830381865afa1580156118aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118ce9190612e0a565b60a08901519097506001600160a01b031630146118ff5760a08801516118ff906001600160a01b0388169089611cb1565b505050505050919050565b600080600080848060200190518101906119249190613717565b9250925092506000826001600160a01b0316639e548b7f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561196a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061198e91906136fa565b6040516318594a0160e11b81526004810186905260248101849052604481018990529091506001600160a01b038216906330b29402906064016020604051808303816000875af11580156119e6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a0a9190612e0a565b94506001600160a01b0388163014611a9357611a938886836001600160a01b031663f0a0b44e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a5f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a8391906136fa565b6001600160a01b03169190611cb1565b505050509392505050565b6000806000806000856101000151806020019051810190611abf9190613750565b93509350935093506000826001600160a01b03166370a082318860a001516040518263ffffffff1660e01b8152600401611af991906122ca565b602060405180830381865afa158015611b16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b3a9190612e0a565b905060008085600081518110611b5257611b526128f4565b6020026020010151806020019051810190611b6d919061383c565b9092509050611ba66001600160a01b0383167f000000000000000000000000000000000000000000000000000000000000000083611fa6565b604051630d64d59360e21b81526001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690633593564c90611bf6908a908a90899060040161386a565b600060405180830381600087803b158015611c1057600080fd5b505af1158015611c24573d6000803e3d6000fd5b5050505060a08901516040516370a0823160e01b815284916001600160a01b038816916370a0823191611c59916004016122ca565b602060405180830381865afa158015611c76573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c9a9190612e0a565b611ca49190612920565b9998505050505050505050565b611d078363a9059cbb60e01b8484604051602401611cd092919061367b565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261203b565b505050565b604051623f675f60e91b81526000906001600160a01b038a1690637ecebe0090611d3a908b906004016122ca565b602060405180830381865afa158015611d57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d7b9190612e0a565b60405163d505accf60e01b81526001600160a01b038a811660048301528981166024830152604482018990526064820188905260ff8716608483015260a4820186905260c48201859052919250908a169063d505accf9060e401600060405180830381600087803b158015611def57600080fd5b505af1158015611e03573d6000803e3d6000fd5b5050604051623f675f60e91b8152600092506001600160a01b038c169150637ecebe0090611e35908c906004016122ca565b602060405180830381865afa158015611e52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e769190612e0a565b9050611e83826001612b1c565b8114611ee05760405162461bcd60e51b815260206004820152602160248201527f5361666545524332303a207065726d697420646964206e6f74207375636365656044820152601960fa1b60648201526084015b60405180910390fd5b50505050505050505050565b611f0d846323b872dd60e01b858585604051602401611cd09392919061363c565b50505050565b600081611f21816014612b1c565b1015611f4057604051634b5ecc6360e11b815260040160405180910390fd5b611f4b826014612b1c565b83511015611f6c5760405163a261974560e01b815260040160405180910390fd5b500160200151600160601b900490565b6000600160ff1b8210611fa257604051632db27c5360e01b815260040160405180910390fd5b5090565b600063095ea7b360e01b8383604051602401611fc392919061367b565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915290506120018482612110565b611f0d576040516001600160a01b03841660248201526000604482015261203590859063095ea7b360e01b90606401611cd0565b611f0d84825b6000612090826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166121b79092919063ffffffff16565b90508051600014806120b15750808060200190518101906120b19190613660565b611d075760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401611ed7565b6000806000846001600160a01b03168460405161212d9190612d66565b6000604051808303816000865af19150503d806000811461216a576040519150601f19603f3d011682016040523d82523d6000602084013e61216f565b606091505b50915091508180156121995750805115806121995750808060200190518101906121999190613660565b80156121ae57506001600160a01b0385163b15155b95945050505050565b6060610285848460008585600080866001600160a01b031685876040516121de9190612d66565b60006040518083038185875af1925050503d806000811461221b576040519150601f19603f3d011682016040523d82523d6000602084013e612220565b606091505b5091509150610d9b878383876060831561229b578251600003612294576001600160a01b0385163b6122945760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611ed7565b5081610285565b61028583838151156122b05781518083602001fd5b8060405162461bcd60e51b8152600401611ed791906138e5565b6001600160a01b0391909116815260200190565b6001600160a01b03811681146122f357600080fd5b50565b80356103dd816122de565b6000610120828403121561034857600080fd5b600080600083850361012081121561232b57600080fd5b8435612336816122de565b935060e0601f198201121561234a57600080fd5b506020840191506101008401356001600160401b0381111561236b57600080fd5b61237786828701612301565b9150509250925092565b60006020828403121561239357600080fd5b81356001600160401b038111156123a957600080fd5b61028584828501612301565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b03811182821017156123ee576123ee6123b5565b60405290565b60405160a081016001600160401b03811182821017156123ee576123ee6123b5565b604051608081016001600160401b03811182821017156123ee576123ee6123b5565b604051606081016001600160401b03811182821017156123ee576123ee6123b5565b60405161018081016001600160401b03811182821017156123ee576123ee6123b5565b604051601f8201601f191681016001600160401b03811182821017156124a5576124a56123b5565b604052919050565b8035600881106103dd57600080fd5b8035600281106103dd57600080fd5b60006001600160401b038211156124e4576124e46123b5565b50601f01601f191660200190565b600082601f83011261250357600080fd5b8135612516612511826124cb565b61247d565b81815284602083860101111561252b57600080fd5b816020850160208301376000918101602001919091529392505050565b6000610120828403121561255b57600080fd5b6125636123cb565b905061256e826124ad565b815261257c602083016124bc565b602082015261258d604083016122f6565b604082015260608201356060820152608082013560808201526125b260a083016122f6565b60a08201526125c360c083016122f6565b60c082015260e082013560e0820152610100808301356001600160401b038111156125ed57600080fd5b6125f9858286016124f2565b82840152505092915050565b60006020828403121561261757600080fd5b81356001600160401b0381111561262d57600080fd5b61028584828501612548565b634e487b7160e01b600052602160045260246000fd5b60006020828403121561266157600080fd5b61266a826124bc565b9392505050565b60006020828403121561268357600080fd5b813561266a816122de565b803560ff811681146103dd57600080fd5b600060e082840312156126b157600080fd5b60405160e081018181106001600160401b03821117156126d3576126d36123b5565b6040528235600381106126e557600080fd5b808252506020830135602082015260408301356040820152606083013560608201526127136080840161268e565b608082015260a083013560a082015260c083013560c08201528091505092915050565b60006103be3683612548565b60006020828403121561275457600080fd5b61266a826124ad565b6000808335601e1984360301811261277457600080fd5b8301803591506001600160401b0382111561278e57600080fd5b6020019150368190038213156127a357600080fd5b9250929050565b60006001600160401b038211156127c3576127c36123b5565b5060051b60200190565b600082601f8301126127de57600080fd5b813560206127ee612511836127aa565b82815260059290921b8401810191818101908684111561280d57600080fd5b8286015b84811015612831578035612824816122de565b8352918301918301612811565b509695505050505050565b6000806040838503121561284f57600080fd5b82356001600160401b038082111561286657600080fd5b818501915085601f83011261287a57600080fd5b8135602061288a612511836127aa565b82815260059290921b840181019181810190898411156128a957600080fd5b948201945b838610156128c7578535825294820194908201906128ae565b965050860135925050808211156128dd57600080fd5b506128ea858286016127cd565b9150509250929050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b818103818111156103be576103be61290a565b80516103dd816122de565b600082601f83011261294f57600080fd5b8151602061295f612511836127aa565b82815260059290921b8401810191818101908684111561297e57600080fd5b8286015b84811015612831578051612995816122de565b8352918301918301612982565b600080604083850312156129b557600080fd5b82516001600160401b03808211156129cc57600080fd5b818501915085601f8301126129e057600080fd5b815160206129f0612511836127aa565b82815260059290921b84018101918181019089841115612a0f57600080fd5b948201945b83861015612a2d57855182529482019490820190612a14565b91880151919650909350505080821115612a4657600080fd5b506128ea8582860161293e565b60005b83811015612a6e578181015183820152602001612a56565b50506000910152565b60008151808452612a8f816020860160208601612a53565b601f01601f19169290920160200192915050565b6000610100612ac683885180516001600160a01b03168252602090810151910152565b6020870151604084015260408701516060840152612afa608084018780516001600160a01b03168252602090810151910152565b6001600160a01b03851660c084015260e08301819052610d9b81840185612a77565b808201808211156103be576103be61290a565b6000600160ff1b8201612b4457612b4461290a565b5060000390565b600081518084526020808501945080840160005b83811015612b845781516001600160a01b031687529582019590820190600101612b5f565b509495945050505050565b600081518084526020808501945080840160005b83811015612b8457815187529582019590820190600101612ba3565b600061012080830160028a10612bd757612bd7612639565b89845260208085019290925288519081905261014080850192600583901b8601909101918a820160005b82811015612c645787850361013f190186528151805186528481015185870152604080820151908701526060808201519087015260809081015160a091870182905290612c5081880183612a77565b978601979650505090830190600101612c01565b505050508381036040850152612c7a8189612b4b565b915050612cba606084018780516001600160a01b039081168352602080830151151590840152604080830151909116908301526060908101511515910152565b82810360e0840152612ccc8186612b8f565b91505082610100830152979650505050505050565b60006020808385031215612cf457600080fd5b82516001600160401b03811115612d0a57600080fd5b8301601f81018513612d1b57600080fd5b8051612d29612511826127aa565b81815260059190911b82018301908381019087831115612d4857600080fd5b928401925b82841015610d9b57835182529284019290840190612d4d565b60008251612d78818460208701612a53565b9190910192915050565b60008060408385031215612d9557600080fd5b505080516020909101519092909150565b6000815160a08452612dbb60a0850182612a77565b6020848101516001600160a01b031690860152604080850151908601526060808501519086015260809384015193909401929092525090919050565b60208152600061266a6020830184612da6565b600060208284031215612e1c57600080fd5b5051919050565b600481106122f357600080fd5b80516103dd81612e23565b600082601f830112612e4c57600080fd5b8151612e5a612511826124cb565b818152846020838601011115612e6f57600080fd5b610285826020830160208701612a53565b805180151581146103dd57600080fd5b600060a08284031215612ea257600080fd5b612eaa6123f4565b90508151612eb7816122de565b8152602082810151908201526040820151612ed1816122de565b60408201526060820151612ee4816122de565b606082015260808201516001600160401b0380821115612f0357600080fd5b9083019060808286031215612f1757600080fd5b612f1f612416565b8251612f2a81612e23565b81526020830151612f3a816122de565b6020820152604083015182811115612f5157600080fd5b612f5d87828601612e3b565b604083015250612f6f60608401612e80565b6060820152608084015250909392505050565b600082601f830112612f9357600080fd5b81516020612fa3612511836127aa565b82815260059290921b84018101918181019086841115612fc257600080fd5b8286015b848110156128315780516001600160401b0380821115612fe557600080fd5b90880190601f196060838c0382011215612ffe57600080fd5b613006612438565b878401518381111561301757600080fd5b8401610180818e038401121561302c57600080fd5b61303461245a565b92508881015183526040810151898401526060810151604084015261305b60808201612e30565b606084015261306c60a08201612933565b608084015261307d60c08201612933565b60a084015261308e60e08201612933565b60c08401526101006130a1818301612933565b60e08501526101208083015182860152610140915081830151818601525061016080830151828601526101808301519150858211156130df57600080fd5b6130ed8f8c84860101612e3b565b9085015250509081526040830151908282111561310957600080fd5b6131178c8984870101612e3b565b8189015260609390930151604084015250508352918301918301612fc6565b600060a0828403121561314857600080fd5b6131506123f4565b905061315b82612933565b81526020820151602082015260408201516001600160401b038082111561318157600080fd5b61318d85838601612f82565b604084015260608401519150808211156131a657600080fd5b6131b285838601612f82565b606084015260808401519150808211156131cb57600080fd5b506131d884828501612e3b565b60808301525092915050565b6000806000808486036101008112156131fc57600080fd5b8551613207816122de565b945060a0601f198201121561321b57600080fd5b506132246123f4565b6020860151815260408601516020820152606086015160408201526080860151606082015260a086015160808201528093505060c08501516001600160401b038082111561327157600080fd5b61327d88838901612e90565b935060e087015191508082111561329357600080fd5b506132a087828801613136565b91505092959194509250565b600481106122f3576122f3612639565b6132c5816132ac565b9052565b600081518084526020808501808196508360051b8101915082860160005b8581101561341f57828403895281516060815181875280518288015287810151608081818a0152604091508183015160a081818c015285850151955060c09150613333828c01876132bc565b91840151945060e0916133508b8401876001600160a01b03169052565b840151945061010061336c8b8201876001600160a01b03169052565b9084015194506101209061338a8b8301876001600160a01b03169052565b918401519450610140916133a88b8401876001600160a01b03169052565b8401516101608b81019190915290840151610180808c0191909152918401516101a08b01528301516101c08a019190915292506133e96101e0890184612a77565b9250888401519150878303898901526134028383612a77565b9381015197019690965250988501989350908401906001016132e7565b5091979650505050505050565b60018060a01b038151168252602081015160208301526000604082015160a0604085015261345d60a08501826132c9565b90506060830151848203606086015261347682826132c9565b915050608083015184820360808601526121ae8282612a77565b600061014060018060a01b03808a16845280891660208501528760408501528651606085015260208701516080850152604087015160a0850152606087015160c0850152608087015160e0850152816101008501528086511682850152602086015161016085015280604087015116610180850152806060870151166101a08501526080860151915060a06101c0850152815161352c816132ac565b6101e085015260208201511661020084015260408101516080610220850152613559610260850182612a77565b90506060820151151561024085015283810361012085015261357b818661342c565b9a9950505050505050505050565b60008060006060848603121561359e57600080fd5b8351925060208401519150604084015190509250925092565b6000806000606084860312156135cc57600080fd5b83516135d7816122de565b6020850151604086015191945092506135ef816122de565b809150509250925092565b60008060006060848603121561360f57600080fd5b835161361a816122de565b602085015190935061362b816122de565b60408501519092506135ef816122de565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006020828403121561367257600080fd5b61266a82612e80565b6001600160a01b03929092168252602082015260400190565b60018060a01b03841681528260208201526060604082015260006121ae6060830184612a77565b600080600080608085870312156136d157600080fd5b84516136dc816122de565b60208601516040870151606090970151919890975090945092505050565b60006020828403121561370c57600080fd5b815161266a816122de565b60008060006060848603121561372c57600080fd5b83519250602084015161373e816122de565b80925050604084015190509250925092565b6000806000806080858703121561376657600080fd5b84516001600160401b038082111561377d57600080fd5b61378988838901612e3b565b95506020915081870151818111156137a057600080fd5b8701601f810189136137b157600080fd5b80516137bf612511826127aa565b81815260059190911b8201840190848101908b8311156137de57600080fd5b8584015b83811015613816578051868111156137fa5760008081fd5b6138088e8983890101612e3b565b8452509186019186016137e2565b5080985050505050505061382c60408601612933565b6060959095015193969295505050565b6000806040838503121561384f57600080fd5b825161385a816122de565b6020939093015192949293505050565b60608152600061387d6060830186612a77565b6020838203818501528186518084528284019150828160051b85010183890160005b838110156138cd57601f198784030185526138bb838351612a77565b9486019492509085019060010161389f565b50508095505050505050826040830152949350505050565b60208152600061266a6020830184612a7756fea26469706673582212207697af2c3ba2006f9a0bcb5eb14caac37419539a71934523e3db0c16251decef64736f6c63430008130033000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000e592427a0aece92de3edee1f18e0157c0586156400000000000000000000000000000000005bbb0ef59571e58418f9a4357b68a00000000000000000000000006131b5fae19ea4f9d964eac0408e4408b66337b500000000000000000000000063baee33649e589cc70435f898671461b624cbcc0000000000000000000000003d20601ac0ba9cae4564ddf7870825c505b69f1a

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061009e5760003560e01c8063a0e47bf611610066578063a0e47bf614610165578063a49cc0cd1461018c578063a639bbfe1461019f578063c0d4a416146101c6578063f63ca6e4146101d957600080fd5b806312261ee7146100a3578063158274a5146100cf5780631fc96635146100f6578063206aeab31461011d578063746f700a14610144575b600080fd5b6100b96e22d473030f116ddee9f6b43ac78ba381565b6040516100c691906122ca565b60405180910390f35b6100b97f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c881565b6100b97f00000000000000000000000063baee33649e589cc70435f898671461b624cbcc81565b6100b97f00000000000000000000000000000000005bbb0ef59571e58418f9a4357b68a081565b610157610152366004612314565b610200565b6040519081526020016100c6565b6100b97f000000000000000000000000e592427a0aece92de3edee1f18e0157c0586156481565b6100b961019a366004612381565b61028d565b6100b97f0000000000000000000000003d20601ac0ba9cae4564ddf7870825c505b69f1a81565b6101576101d4366004612605565b6103e2565b6100b97f0000000000000000000000006131b5fae19ea4f9d964eac0408e4408b66337b581565b60006001600160a01b038416301461027957600080610225604085016020860161264f565b600181111561023657610236612639565b1461024557826080013561024b565b82606001355b90506102776102606060850160408601612671565b863084610272368a90038a018a61269f565b6106aa565b505b6102856101d483612736565b949350505050565b60008061029d6020840184612742565b60078111156102ae576102ae612639565b0361034e5760006102c361010084018461275d565b8101906102d0919061283c565b9150600190506102e6604085016020860161264f565b60018111156102f7576102f7612639565b0361031e578060008151811061030f5761030f6128f4565b60200260200101519150610348565b806001825161032d9190612920565b8151811061033d5761033d6128f4565b602002602001015191505b50919050565b600161035d6020840184612742565b600781111561036e5761036e612639565b036103c4576103be61038461010084018461275d565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061087592505050565b92915050565b60405163e11d7ccb60e01b815260040160405180910390fd5b919050565b60008160e0015142111561042e5761042e6040518060400160405280602081526020017f53776170416374696f6e3a207377617020646561646c696e65207061737365648152506108b1565b60008251600781111561044357610443612639565b036104995760008083610100015180602001905181019061046491906129a2565b91509150610490846020015185604001518484886060015189608001518a60a001518b60e001516108d9565b9250505061061b565b6004825160078111156104ae576104ae612639565b1480156104d057506000826020015160018111156104ce576104ce612639565b145b156104f9576104f2826040015183606001518460800151856101000151610c9b565b905061061b565b60018251600781111561050e5761050e612639565b0361053f576104f282602001518360400151846060015185608001518660a001518760e00151886101000151610da6565b60028251600781111561055457610554612639565b03610571576104f28260a001518360800151846101000151610f68565b60038251600781111561058657610586612639565b036105a3576104f28260a0015183608001518461010001516110f6565b6005825160078111156105b8576105b8612639565b036105c6576104f282611582565b6006825160078111156105db576105db612639565b036105f8576104f28260a00151836080015184610100015161190a565b60078251600781111561060d5761060d612639565b036103c4576104f282611a9e565b60018260200151600181111561063357610633612639565b14801561064d575060a08201516001600160a01b03163014155b156103dd5760c08201516001600160a01b031615610692576103dd8260c0015182846080015161067d9190612920565b60408501516001600160a01b03169190611cb1565b6103dd8260a0015182846080015161067d9190612920565b6002815160028111156106bf576106bf612639565b036107e9576e22d473030f116ddee9f6b43ac78ba36001600160a01b03166330f28b7a604051806060016040528060405180604001604052808a6001600160a01b03168152602001866020015181525081526020018460400151815260200184606001518152506040518060400160405280876001600160a01b0316815260200186815250878560a001518660c00151876080015160f81b6040516020016107849392919092835260208301919091526001600160f81b031916604082015260410190565b6040516020818303038152906040526040518563ffffffff1660e01b81526004016107b29493929190612aa3565b600060405180830381600087803b1580156107cc57600080fd5b505af11580156107e0573d6000803e3d6000fd5b5050505061086e565b6001815160028111156107fe576107fe612639565b036108595761083f84848360200151846060015185608001518660a001518760c001518c6001600160a01b0316611d0c90979695949392919063ffffffff16565b6108546001600160a01b038616858585611eec565b61086e565b61086e6001600160a01b038616858585611eec565b5050505050565b600060148251101561089a5760405163d3d6273f60e01b815260040160405180910390fd5b6103be82601484516108ac9190612920565b611f13565b8051156108c057805181602001fd5b604051634811b8df60e11b815260040160405180910390fd5b8551600090816108ea826001612b1c565b6001600160401b03811115610901576109016123b5565b60405190808252806020026020018201604052801561092a578160200160208202803683370190505b5090506000826001600160401b03811115610947576109476123b5565b6040519080825280602002602001820160405280156109ad57816020015b61099a6040518060a0016040528060008019168152602001600081526020016000815260200160008152602001606081525090565b8152602001906001900390816109655790505b5090506060600080808f60018111156109c8576109c8612639565b036109d5575060016109da565b600191505b60005b86811015610a4f576040518060a001604052808f8381518110610a0257610a026128f4565b60200260200101518152602001848301815260200183830181526020016000815260200185815250858281518110610a3c57610a3c6128f4565b60209081029190910101526001016109dd565b508a84600081518110610a6457610a646128f4565b6020908102919091010151606001525060009150819050808e6001811115610a8e57610a8e612639565b03610af657506000905088610aa281611f7c565b84600081518110610ab557610ab56128f4565b602002602001018181525050610aca89611f7c565b610ad390612b2f565b848681518110610ae557610ae56128f4565b602002602001018181525050610b55565b506001905087610b058a611f7c565b610b0e90612b2f565b84600081518110610b2157610b216128f4565b602002602001018181525050610b3689611f7c565b848681518110610b4857610b486128f4565b6020026020010181815250505b610b896001600160a01b038e167f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c883611fa6565b610c897f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b031663945bcec984868f6040518060800160405280306001600160a01b031681526020016000151581526020018f6001600160a01b03168152602001600015158152508a8e6040518763ffffffff1660e01b8152600401610c1a96959493929190612bbf565b6000604051808303816000875af1158015610c39573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610c619190810190612ce1565b8681518110610c7257610c726128f4565b602002602001015160ff81901c6000039081011890565b9e9d5050505050505050505050505050565b6000610cd16001600160a01b0386167f0000000000000000000000006131b5fae19ea4f9d964eac0408e4408b66337b586611fa6565b6000807f0000000000000000000000006131b5fae19ea4f9d964eac0408e4408b66337b56001600160a01b031684604051610d0c9190612d66565b6000604051808303816000865af19150503d8060008114610d49576040519150601f19603f3d011682016040523d82523d6000602084013e610d4e565b606091505b509150915081610d6157610d61816108b1565b600081806020019051810190610d779190612d82565b50905085811015610d9b57604051632205896160e01b815260040160405180910390fd5b979650505050505050565b600080886001811115610dbb57610dbb612639565b03610eb957610df46001600160a01b0388167f000000000000000000000000e592427a0aece92de3edee1f18e0157c0586156488611fa6565b7f000000000000000000000000e592427a0aece92de3edee1f18e0157c058615646001600160a01b031663c04b8d596040518060a00160405280858152602001876001600160a01b03168152602001868152602001898152602001888152506040518263ffffffff1660e01b8152600401610e6f9190612df7565b6020604051808303816000875af1158015610e8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eb29190612e0a565b9050610d9b565b610eed6001600160a01b0388167f000000000000000000000000e592427a0aece92de3edee1f18e0157c0586156487611fa6565b7f000000000000000000000000e592427a0aece92de3edee1f18e0157c058615646001600160a01b031663f28c04986040518060a00160405280858152602001876001600160a01b03168152602001868152602001898152602001888152506040518263ffffffff1660e01b8152600401610e6f9190612df7565b600080600080600085806020019051810190610f8491906131e4565b8151939750919550935091506001600160a01b03161561104e5781516040516370a0823160e01b81526001600160a01b03909116906370a0823190610fcd9030906004016122ca565b602060405180830381865afa158015610fea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061100e9190612e0a565b60208301819052825161104e916001600160a01b03909116907f00000000000000000000000000000000005bbb0ef59571e58418f9a4357b68a090611fa6565b60405163092ccd6360e11b81526001600160a01b037f00000000000000000000000000000000005bbb0ef59571e58418f9a4357b68a016906312599ac6906110a4908b9088908c90899089908990600401613490565b6060604051808303816000875af11580156110c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e79190613589565b50909998505050505050505050565b6000806000808480602001905181019061111091906135b7565b9250925092506000806000856001600160a01b0316632c8ce6bc6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611159573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117d91906135fa565b919450925090506001600160a01b038a16301461120d576040516323b872dd60e01b81526001600160a01b038716906323b872dd906111c4908d908a908a9060040161363c565b6020604051808303816000875af11580156111e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112079190613660565b50611280565b60405163a9059cbb60e01b81526001600160a01b0387169063a9059cbb9061123b908990899060040161367b565b6020604051808303816000875af115801561125a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061127e9190613660565b505b6000826001600160a01b0316632f13b60c6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156112c0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e49190613660565b156113e757604051633dae446f60e21b81526000906001600160a01b0389169063f6b911bc9061131c90889087908c9060040161363c565b60408051808303816000875af115801561133a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061135e9190612d82565b5090506000836001600160a01b031663bcb7ea5d876040518263ffffffff1660e01b815260040161138f91906122ca565b6020604051808303816000875af11580156113ae573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113d29190612e0a565b90506113de8183612b1c565b925050506114ea565b600080886001600160a01b031663f6b911bc878b8b6040518463ffffffff1660e01b815260040161141a9392919061363c565b60408051808303816000875af1158015611438573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061145c9190612d82565b91509150606060008a6001600160a01b03166329910b118985856040518463ffffffff1660e01b815260040161149493929190613694565b60408051808303816000875af11580156114b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114d69190612d82565b5090506114e38185612b1c565b9450505050505b60405163769f8e5d60e01b81526001600160a01b038c81166004830152602482018390528681166044830152606482018c90526001608483015285169063769f8e5d9060a4016020604051808303816000875af115801561154f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115739190612e0a565b9b9a5050505050505050505050565b60008060008060008561010001518060200190518101906115a391906136bb565b93509350935093506000846001600160a01b0316639e548b7f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156115eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061160f91906136fa565b6001600160a01b0316630589a4786040518163ffffffff1660e01b8152600401602060405180830381865afa15801561164c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061167091906136fa565b90506000856001600160a01b0316639e548b7f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d691906136fa565b6001600160a01b031663f0a0b44e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611713573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061173791906136fa565b90508415611773576117736001600160a01b0383167f00000000000000000000000063baee33649e589cc70435f898671461b624cbcc87611fa6565b83156117ad576117ad6001600160a01b0382167f00000000000000000000000063baee33649e589cc70435f898671461b624cbcc86611fa6565b608088015160e0890151604051630f5c0dcb60e31b81526001600160a01b03858116600483015284811660248301526044820189905260648201889052608482019390935260a4810186905260c48101919091527f00000000000000000000000063baee33649e589cc70435f898671461b624cbcc90911690637ae06e589060e401600060405180830381600087803b15801561184957600080fd5b505af115801561185d573d6000803e3d6000fd5b50506040516370a0823160e01b81526001600160a01b03891692506370a08231915061188d9030906004016122ca565b602060405180830381865afa1580156118aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118ce9190612e0a565b60a08901519097506001600160a01b031630146118ff5760a08801516118ff906001600160a01b0388169089611cb1565b505050505050919050565b600080600080848060200190518101906119249190613717565b9250925092506000826001600160a01b0316639e548b7f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561196a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061198e91906136fa565b6040516318594a0160e11b81526004810186905260248101849052604481018990529091506001600160a01b038216906330b29402906064016020604051808303816000875af11580156119e6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a0a9190612e0a565b94506001600160a01b0388163014611a9357611a938886836001600160a01b031663f0a0b44e6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a5f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a8391906136fa565b6001600160a01b03169190611cb1565b505050509392505050565b6000806000806000856101000151806020019051810190611abf9190613750565b93509350935093506000826001600160a01b03166370a082318860a001516040518263ffffffff1660e01b8152600401611af991906122ca565b602060405180830381865afa158015611b16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b3a9190612e0a565b905060008085600081518110611b5257611b526128f4565b6020026020010151806020019051810190611b6d919061383c565b9092509050611ba66001600160a01b0383167f0000000000000000000000003d20601ac0ba9cae4564ddf7870825c505b69f1a83611fa6565b604051630d64d59360e21b81526001600160a01b037f0000000000000000000000003d20601ac0ba9cae4564ddf7870825c505b69f1a1690633593564c90611bf6908a908a90899060040161386a565b600060405180830381600087803b158015611c1057600080fd5b505af1158015611c24573d6000803e3d6000fd5b5050505060a08901516040516370a0823160e01b815284916001600160a01b038816916370a0823191611c59916004016122ca565b602060405180830381865afa158015611c76573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c9a9190612e0a565b611ca49190612920565b9998505050505050505050565b611d078363a9059cbb60e01b8484604051602401611cd092919061367b565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915261203b565b505050565b604051623f675f60e91b81526000906001600160a01b038a1690637ecebe0090611d3a908b906004016122ca565b602060405180830381865afa158015611d57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d7b9190612e0a565b60405163d505accf60e01b81526001600160a01b038a811660048301528981166024830152604482018990526064820188905260ff8716608483015260a4820186905260c48201859052919250908a169063d505accf9060e401600060405180830381600087803b158015611def57600080fd5b505af1158015611e03573d6000803e3d6000fd5b5050604051623f675f60e91b8152600092506001600160a01b038c169150637ecebe0090611e35908c906004016122ca565b602060405180830381865afa158015611e52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e769190612e0a565b9050611e83826001612b1c565b8114611ee05760405162461bcd60e51b815260206004820152602160248201527f5361666545524332303a207065726d697420646964206e6f74207375636365656044820152601960fa1b60648201526084015b60405180910390fd5b50505050505050505050565b611f0d846323b872dd60e01b858585604051602401611cd09392919061363c565b50505050565b600081611f21816014612b1c565b1015611f4057604051634b5ecc6360e11b815260040160405180910390fd5b611f4b826014612b1c565b83511015611f6c5760405163a261974560e01b815260040160405180910390fd5b500160200151600160601b900490565b6000600160ff1b8210611fa257604051632db27c5360e01b815260040160405180910390fd5b5090565b600063095ea7b360e01b8383604051602401611fc392919061367b565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915290506120018482612110565b611f0d576040516001600160a01b03841660248201526000604482015261203590859063095ea7b360e01b90606401611cd0565b611f0d84825b6000612090826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166121b79092919063ffffffff16565b90508051600014806120b15750808060200190518101906120b19190613660565b611d075760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401611ed7565b6000806000846001600160a01b03168460405161212d9190612d66565b6000604051808303816000865af19150503d806000811461216a576040519150601f19603f3d011682016040523d82523d6000602084013e61216f565b606091505b50915091508180156121995750805115806121995750808060200190518101906121999190613660565b80156121ae57506001600160a01b0385163b15155b95945050505050565b6060610285848460008585600080866001600160a01b031685876040516121de9190612d66565b60006040518083038185875af1925050503d806000811461221b576040519150601f19603f3d011682016040523d82523d6000602084013e612220565b606091505b5091509150610d9b878383876060831561229b578251600003612294576001600160a01b0385163b6122945760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401611ed7565b5081610285565b61028583838151156122b05781518083602001fd5b8060405162461bcd60e51b8152600401611ed791906138e5565b6001600160a01b0391909116815260200190565b6001600160a01b03811681146122f357600080fd5b50565b80356103dd816122de565b6000610120828403121561034857600080fd5b600080600083850361012081121561232b57600080fd5b8435612336816122de565b935060e0601f198201121561234a57600080fd5b506020840191506101008401356001600160401b0381111561236b57600080fd5b61237786828701612301565b9150509250925092565b60006020828403121561239357600080fd5b81356001600160401b038111156123a957600080fd5b61028584828501612301565b634e487b7160e01b600052604160045260246000fd5b60405161012081016001600160401b03811182821017156123ee576123ee6123b5565b60405290565b60405160a081016001600160401b03811182821017156123ee576123ee6123b5565b604051608081016001600160401b03811182821017156123ee576123ee6123b5565b604051606081016001600160401b03811182821017156123ee576123ee6123b5565b60405161018081016001600160401b03811182821017156123ee576123ee6123b5565b604051601f8201601f191681016001600160401b03811182821017156124a5576124a56123b5565b604052919050565b8035600881106103dd57600080fd5b8035600281106103dd57600080fd5b60006001600160401b038211156124e4576124e46123b5565b50601f01601f191660200190565b600082601f83011261250357600080fd5b8135612516612511826124cb565b61247d565b81815284602083860101111561252b57600080fd5b816020850160208301376000918101602001919091529392505050565b6000610120828403121561255b57600080fd5b6125636123cb565b905061256e826124ad565b815261257c602083016124bc565b602082015261258d604083016122f6565b604082015260608201356060820152608082013560808201526125b260a083016122f6565b60a08201526125c360c083016122f6565b60c082015260e082013560e0820152610100808301356001600160401b038111156125ed57600080fd5b6125f9858286016124f2565b82840152505092915050565b60006020828403121561261757600080fd5b81356001600160401b0381111561262d57600080fd5b61028584828501612548565b634e487b7160e01b600052602160045260246000fd5b60006020828403121561266157600080fd5b61266a826124bc565b9392505050565b60006020828403121561268357600080fd5b813561266a816122de565b803560ff811681146103dd57600080fd5b600060e082840312156126b157600080fd5b60405160e081018181106001600160401b03821117156126d3576126d36123b5565b6040528235600381106126e557600080fd5b808252506020830135602082015260408301356040820152606083013560608201526127136080840161268e565b608082015260a083013560a082015260c083013560c08201528091505092915050565b60006103be3683612548565b60006020828403121561275457600080fd5b61266a826124ad565b6000808335601e1984360301811261277457600080fd5b8301803591506001600160401b0382111561278e57600080fd5b6020019150368190038213156127a357600080fd5b9250929050565b60006001600160401b038211156127c3576127c36123b5565b5060051b60200190565b600082601f8301126127de57600080fd5b813560206127ee612511836127aa565b82815260059290921b8401810191818101908684111561280d57600080fd5b8286015b84811015612831578035612824816122de565b8352918301918301612811565b509695505050505050565b6000806040838503121561284f57600080fd5b82356001600160401b038082111561286657600080fd5b818501915085601f83011261287a57600080fd5b8135602061288a612511836127aa565b82815260059290921b840181019181810190898411156128a957600080fd5b948201945b838610156128c7578535825294820194908201906128ae565b965050860135925050808211156128dd57600080fd5b506128ea858286016127cd565b9150509250929050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b818103818111156103be576103be61290a565b80516103dd816122de565b600082601f83011261294f57600080fd5b8151602061295f612511836127aa565b82815260059290921b8401810191818101908684111561297e57600080fd5b8286015b84811015612831578051612995816122de565b8352918301918301612982565b600080604083850312156129b557600080fd5b82516001600160401b03808211156129cc57600080fd5b818501915085601f8301126129e057600080fd5b815160206129f0612511836127aa565b82815260059290921b84018101918181019089841115612a0f57600080fd5b948201945b83861015612a2d57855182529482019490820190612a14565b91880151919650909350505080821115612a4657600080fd5b506128ea8582860161293e565b60005b83811015612a6e578181015183820152602001612a56565b50506000910152565b60008151808452612a8f816020860160208601612a53565b601f01601f19169290920160200192915050565b6000610100612ac683885180516001600160a01b03168252602090810151910152565b6020870151604084015260408701516060840152612afa608084018780516001600160a01b03168252602090810151910152565b6001600160a01b03851660c084015260e08301819052610d9b81840185612a77565b808201808211156103be576103be61290a565b6000600160ff1b8201612b4457612b4461290a565b5060000390565b600081518084526020808501945080840160005b83811015612b845781516001600160a01b031687529582019590820190600101612b5f565b509495945050505050565b600081518084526020808501945080840160005b83811015612b8457815187529582019590820190600101612ba3565b600061012080830160028a10612bd757612bd7612639565b89845260208085019290925288519081905261014080850192600583901b8601909101918a820160005b82811015612c645787850361013f190186528151805186528481015185870152604080820151908701526060808201519087015260809081015160a091870182905290612c5081880183612a77565b978601979650505090830190600101612c01565b505050508381036040850152612c7a8189612b4b565b915050612cba606084018780516001600160a01b039081168352602080830151151590840152604080830151909116908301526060908101511515910152565b82810360e0840152612ccc8186612b8f565b91505082610100830152979650505050505050565b60006020808385031215612cf457600080fd5b82516001600160401b03811115612d0a57600080fd5b8301601f81018513612d1b57600080fd5b8051612d29612511826127aa565b81815260059190911b82018301908381019087831115612d4857600080fd5b928401925b82841015610d9b57835182529284019290840190612d4d565b60008251612d78818460208701612a53565b9190910192915050565b60008060408385031215612d9557600080fd5b505080516020909101519092909150565b6000815160a08452612dbb60a0850182612a77565b6020848101516001600160a01b031690860152604080850151908601526060808501519086015260809384015193909401929092525090919050565b60208152600061266a6020830184612da6565b600060208284031215612e1c57600080fd5b5051919050565b600481106122f357600080fd5b80516103dd81612e23565b600082601f830112612e4c57600080fd5b8151612e5a612511826124cb565b818152846020838601011115612e6f57600080fd5b610285826020830160208701612a53565b805180151581146103dd57600080fd5b600060a08284031215612ea257600080fd5b612eaa6123f4565b90508151612eb7816122de565b8152602082810151908201526040820151612ed1816122de565b60408201526060820151612ee4816122de565b606082015260808201516001600160401b0380821115612f0357600080fd5b9083019060808286031215612f1757600080fd5b612f1f612416565b8251612f2a81612e23565b81526020830151612f3a816122de565b6020820152604083015182811115612f5157600080fd5b612f5d87828601612e3b565b604083015250612f6f60608401612e80565b6060820152608084015250909392505050565b600082601f830112612f9357600080fd5b81516020612fa3612511836127aa565b82815260059290921b84018101918181019086841115612fc257600080fd5b8286015b848110156128315780516001600160401b0380821115612fe557600080fd5b90880190601f196060838c0382011215612ffe57600080fd5b613006612438565b878401518381111561301757600080fd5b8401610180818e038401121561302c57600080fd5b61303461245a565b92508881015183526040810151898401526060810151604084015261305b60808201612e30565b606084015261306c60a08201612933565b608084015261307d60c08201612933565b60a084015261308e60e08201612933565b60c08401526101006130a1818301612933565b60e08501526101208083015182860152610140915081830151818601525061016080830151828601526101808301519150858211156130df57600080fd5b6130ed8f8c84860101612e3b565b9085015250509081526040830151908282111561310957600080fd5b6131178c8984870101612e3b565b8189015260609390930151604084015250508352918301918301612fc6565b600060a0828403121561314857600080fd5b6131506123f4565b905061315b82612933565b81526020820151602082015260408201516001600160401b038082111561318157600080fd5b61318d85838601612f82565b604084015260608401519150808211156131a657600080fd5b6131b285838601612f82565b606084015260808401519150808211156131cb57600080fd5b506131d884828501612e3b565b60808301525092915050565b6000806000808486036101008112156131fc57600080fd5b8551613207816122de565b945060a0601f198201121561321b57600080fd5b506132246123f4565b6020860151815260408601516020820152606086015160408201526080860151606082015260a086015160808201528093505060c08501516001600160401b038082111561327157600080fd5b61327d88838901612e90565b935060e087015191508082111561329357600080fd5b506132a087828801613136565b91505092959194509250565b600481106122f3576122f3612639565b6132c5816132ac565b9052565b600081518084526020808501808196508360051b8101915082860160005b8581101561341f57828403895281516060815181875280518288015287810151608081818a0152604091508183015160a081818c015285850151955060c09150613333828c01876132bc565b91840151945060e0916133508b8401876001600160a01b03169052565b840151945061010061336c8b8201876001600160a01b03169052565b9084015194506101209061338a8b8301876001600160a01b03169052565b918401519450610140916133a88b8401876001600160a01b03169052565b8401516101608b81019190915290840151610180808c0191909152918401516101a08b01528301516101c08a019190915292506133e96101e0890184612a77565b9250888401519150878303898901526134028383612a77565b9381015197019690965250988501989350908401906001016132e7565b5091979650505050505050565b60018060a01b038151168252602081015160208301526000604082015160a0604085015261345d60a08501826132c9565b90506060830151848203606086015261347682826132c9565b915050608083015184820360808601526121ae8282612a77565b600061014060018060a01b03808a16845280891660208501528760408501528651606085015260208701516080850152604087015160a0850152606087015160c0850152608087015160e0850152816101008501528086511682850152602086015161016085015280604087015116610180850152806060870151166101a08501526080860151915060a06101c0850152815161352c816132ac565b6101e085015260208201511661020084015260408101516080610220850152613559610260850182612a77565b90506060820151151561024085015283810361012085015261357b818661342c565b9a9950505050505050505050565b60008060006060848603121561359e57600080fd5b8351925060208401519150604084015190509250925092565b6000806000606084860312156135cc57600080fd5b83516135d7816122de565b6020850151604086015191945092506135ef816122de565b809150509250925092565b60008060006060848603121561360f57600080fd5b835161361a816122de565b602085015190935061362b816122de565b60408501519092506135ef816122de565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006020828403121561367257600080fd5b61266a82612e80565b6001600160a01b03929092168252602082015260400190565b60018060a01b03841681528260208201526060604082015260006121ae6060830184612a77565b600080600080608085870312156136d157600080fd5b84516136dc816122de565b60208601516040870151606090970151919890975090945092505050565b60006020828403121561370c57600080fd5b815161266a816122de565b60008060006060848603121561372c57600080fd5b83519250602084015161373e816122de565b80925050604084015190509250925092565b6000806000806080858703121561376657600080fd5b84516001600160401b038082111561377d57600080fd5b61378988838901612e3b565b95506020915081870151818111156137a057600080fd5b8701601f810189136137b157600080fd5b80516137bf612511826127aa565b81815260059190911b8201840190848101908b8311156137de57600080fd5b8584015b83811015613816578051868111156137fa5760008081fd5b6138088e8983890101612e3b565b8452509186019186016137e2565b5080985050505050505061382c60408601612933565b6060959095015193969295505050565b6000806040838503121561384f57600080fd5b825161385a816122de565b6020939093015192949293505050565b60608152600061387d6060830186612a77565b6020838203818501528186518084528284019150828160051b85010183890160005b838110156138cd57601f198784030185526138bb838351612a77565b9486019492509085019060010161389f565b50508095505050505050826040830152949350505050565b60208152600061266a6020830184612a7756fea26469706673582212207697af2c3ba2006f9a0bcb5eb14caac37419539a71934523e3db0c16251decef64736f6c63430008130033

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

000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8000000000000000000000000e592427a0aece92de3edee1f18e0157c0586156400000000000000000000000000000000005bbb0ef59571e58418f9a4357b68a00000000000000000000000006131b5fae19ea4f9d964eac0408e4408b66337b500000000000000000000000063baee33649e589cc70435f898671461b624cbcc0000000000000000000000003d20601ac0ba9cae4564ddf7870825c505b69f1a

-----Decoded View---------------
Arg [0] : balancerVault_ (address): 0xBA12222222228d8Ba445958a75a0704d566BF2C8
Arg [1] : uniRouter_ (address): 0xE592427A0AEce92De3Edee1F18E0157C05861564
Arg [2] : pendleRouter_ (address): 0x00000000005BBB0EF59571E58418F9a4357b68A0
Arg [3] : kyberRouter_ (address): 0x6131B5fae19EA4f9D964eAc0408E4408b66337b5
Arg [4] : tranchessRouter_ (address): 0x63BAEe33649E589Cc70435F898671461B624CBCc
Arg [5] : spectraRouter_ (address): 0x3d20601ac0Ba9CAE4564dDf7870825c505B69F1a

-----Encoded View---------------
6 Constructor Arguments found :
Arg [0] : 000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8
Arg [1] : 000000000000000000000000e592427a0aece92de3edee1f18e0157c05861564
Arg [2] : 00000000000000000000000000000000005bbb0ef59571e58418f9a4357b68a0
Arg [3] : 0000000000000000000000006131b5fae19ea4f9d964eac0408e4408b66337b5
Arg [4] : 00000000000000000000000063baee33649e589cc70435f898671461b624cbcc
Arg [5] : 0000000000000000000000003d20601ac0ba9cae4564ddf7870825c505b69f1a


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
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.