ETH Price: $3,580.32 (-3.60%)

Contract

0xCf34556C495cf5637a3131526CEF98d8a7d99888
 
Transaction Hash
Method
Block
From
To
Redeem Py To Tok...121294602024-12-01 15:58:5526 hrs ago1733068735IN
0xCf34556C...8a7d99888
0 ETH0.000000320.00156918
0xb7d75b8b121293872024-12-01 15:56:2926 hrs ago1733068589IN
0xCf34556C...8a7d99888
0 ETH0.000000330.00157551
0xb7d75b8b121287712024-12-01 15:35:5726 hrs ago1733067357IN
0xCf34556C...8a7d99888
0 ETH0.000000350.00167397
Redeem Due Inter...120555602024-11-29 22:55:352 days ago1732920935IN
0xCf34556C...8a7d99888
0 ETH0.000000080.00307482
Redeem Py To Tok...120297782024-11-29 8:36:113 days ago1732869371IN
0xCf34556C...8a7d99888
0 ETH0.000001160.00499783
Redeem Py To Tok...120153822024-11-29 0:36:193 days ago1732840579IN
0xCf34556C...8a7d99888
0 ETH0.000000870.00423781
Redeem Due Inter...119847242024-11-28 7:34:234 days ago1732779263IN
0xCf34556C...8a7d99888
0 ETH0.00000010.00398856
Redeem Py To Tok...119280932024-11-27 0:06:415 days ago1732666001IN
0xCf34556C...8a7d99888
0 ETH0.000000390.00193928
Redeem Py To Tok...119273962024-11-26 23:43:275 days ago1732664607IN
0xCf34556C...8a7d99888
0 ETH0.000000060.00027575
0xb7d75b8b119251832024-11-26 22:29:415 days ago1732660181IN
0xCf34556C...8a7d99888
0 ETH0.000000080.00045609
Redeem Due Inter...119251152024-11-26 22:27:255 days ago1732660045IN
0xCf34556C...8a7d99888
0 ETH0.000000070.00043624
Redeem Py To Tok...119208632024-11-26 20:05:415 days ago1732651541IN
0xCf34556C...8a7d99888
0 ETH0.000000150.00065382
Redeem Due Inter...119183242024-11-26 18:41:035 days ago1732646463IN
0xCf34556C...8a7d99888
0 ETH0.000000110.00069961
0xb7d75b8b119182892024-11-26 18:39:535 days ago1732646393IN
0xCf34556C...8a7d99888
0 ETH0.000000130.00068324
0xb7d75b8b119178612024-11-26 18:25:375 days ago1732645537IN
0xCf34556C...8a7d99888
0 ETH0.000000370.00174831
Redeem Py To Tok...119162032024-11-26 17:30:216 days ago1732642221IN
0xCf34556C...8a7d99888
0 ETH0.000000320.00162138
Redeem Py To Tok...119142322024-11-26 16:24:396 days ago1732638279IN
0xCf34556C...8a7d99888
0 ETH0.000000110.00047749
0xb7d75b8b119139632024-11-26 16:15:416 days ago1732637741IN
0xCf34556C...8a7d99888
0 ETH0.00000010.00047862
Redeem Py To Tok...118994282024-11-26 8:11:116 days ago1732608671IN
0xCf34556C...8a7d99888
0 ETH0.000000260.00127671
0xb7d75b8b118993902024-11-26 8:09:556 days ago1732608595IN
0xCf34556C...8a7d99888
0 ETH0.000000260.00126216
Redeem Due Inter...118906352024-11-26 3:18:056 days ago1732591085IN
0xCf34556C...8a7d99888
0 ETH0.000000050.00209291
0xb7d75b8b118852192024-11-26 0:17:336 days ago1732580253IN
0xCf34556C...8a7d99888
0 ETH0.000000630.00320869
Redeem Due Inter...118852092024-11-26 0:17:136 days ago1732580233IN
0xCf34556C...8a7d99888
0 ETH0.000000560.00320958
0xb7d75b8b118851432024-11-26 0:15:016 days ago1732580101IN
0xCf34556C...8a7d99888
0 ETH0.000000590.00304107
Redeem Due Inter...118851252024-11-26 0:14:256 days ago1732580065IN
0xCf34556C...8a7d99888
0 ETH0.000000530.00305914
View all transactions

Parent Transaction Hash Block From To
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PendleRouterV3

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
File 1 of 29 : PendleRouterV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/proxy/Proxy.sol";
import "../interfaces/IPAllActionV3.sol";
import "../interfaces/IDiamondLoupe.sol";
import "../interfaces/IDiamondCut.sol";
import "../interfaces/Blast/IBlast.sol";

// solhint-disable no-empty-blocks
contract PendleRouterV3 is Proxy, IDiamondLoupe {
    IBlast public constant BLAST = IBlast(0x4300000000000000000000000000000000000002);
    
    address internal immutable ACTION_ADD_REMOVE_LIQ;
    address internal immutable ACTION_SWAP_PT;
    address internal immutable ACTION_SWAP_YT;
    address internal immutable ACTION_MISC;
    address internal immutable ACTION_CALLBACK;

    event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);

    constructor(
        address _ACTION_ADD_REMOVE_LIQ,
        address _ACTION_SWAP_PT,
        address _ACTION_SWAP_YT,
        address _ACTION_MISC,
        address _ACTION_CALLBACK,
        address _governor
    ) {
        ACTION_ADD_REMOVE_LIQ = _ACTION_ADD_REMOVE_LIQ;
        ACTION_SWAP_PT = _ACTION_SWAP_PT;
        ACTION_SWAP_YT = _ACTION_SWAP_YT;
        ACTION_MISC = _ACTION_MISC;
        ACTION_CALLBACK = _ACTION_CALLBACK;
        _emitEvents();
        BLAST.configureClaimableGas();
        BLAST.configureGovernor(_governor); 
    }

    function _emitEvents() internal {
        Facet[] memory facets_ = facets();

        uint256 nFacets = facets_.length;

        IDiamondCut.FacetCut[] memory cuts = new IDiamondCut.FacetCut[](nFacets);
        for (uint256 i; i < nFacets; ) {
            cuts[i].facetAddress = facets_[i].facetAddress;
            cuts[i].action = IDiamondCut.FacetCutAction.Add;
            cuts[i].functionSelectors = facets_[i].functionSelectors;
            unchecked {
                ++i;
            }
        }

        emit DiamondCut(cuts, address(0), "");
    }

    receive() external payable virtual override {}

    /// @notice Gets all facet addresses and their four byte function selectors.
    /// @return facets_ Facet
    function facets() public view returns (Facet[] memory facets_) {
        address[] memory facetAddresses_ = facetAddresses();
        uint256 numFacets = facetAddresses_.length;

        facets_ = new Facet[](numFacets);
        for (uint256 i; i < numFacets; ) {
            facets_[i].facetAddress = facetAddresses_[i];
            facets_[i].functionSelectors = facetFunctionSelectors(facetAddresses_[i]);
            unchecked {
                i++;
            }
        }
    }

    function facetFunctionSelectors(address facet) public view returns (bytes4[] memory res) {
        if (facet == address(this)) {
            res = new bytes4[](4);
            res[0] = 0x52ef6b2c; // facetAddresses
            res[1] = 0x7a0ed627; // facets
            res[2] = 0xadfca15e; // facetFunctionSelectors
            res[3] = 0xcdffacc6; // facetAddress
        }
        if (facet == ACTION_ADD_REMOVE_LIQ) {
            res = new bytes4[](12);
            res[0] = 0x12599ac6; // addLiquiditySingleToken
            res[1] = 0x2756ce06; // addLiquidityDualTokenAndPt
            res[2] = 0x3dbe1c55; // addLiquiditySingleTokenKeepYt
            res[3] = 0x4e390267; // addLiquiditySinglePt
            res[4] = 0x58bda475; // addLiquiditySingleSy
            res[5] = 0x60da0860; // removeLiquiditySingleToken
            res[6] = 0x6b77ac9e; // removeLiquiditySinglePt
            res[7] = 0x844384aa; // addLiquiditySingleSyKeepYt
            res[8] = 0x97ee279e; // addLiquidityDualSyAndPt
            res[9] = 0xb00f09d7; // removeLiquidityDualTokenAndPt
            res[10] = 0xb7d75b8b; // removeLiquidityDualSyAndPt
            res[11] = 0xd13b4fdc; // removeLiquiditySingleSy
        }
        if (facet == ACTION_SWAP_YT) {
            res = new bytes4[](6);
            res[0] = 0x05eb5327; // swapExactYtForToken
            res[1] = 0x448b9b95; // swapExactYtForPt
            res[2] = 0x7b8b4b95; // swapExactSyForYt
            res[3] = 0x80c4d566; // swapExactYtForSy
            res[4] = 0xc861a898; // swapExactPtForYt
            res[5] = 0xed48907e; // swapExactTokenForYt
        }
        if (facet == ACTION_SWAP_PT) {
            res = new bytes4[](4);
            res[0] = 0x2a50917c; // swapExactSyForPt
            res[1] = 0x3346d3a3; // swapExactPtForSy
            res[2] = 0x594a88cc; // swapExactPtForToken
            res[3] = 0xc81f847a; // swapExactTokenForPt
        }
        if (facet == ACTION_CALLBACK) {
            res = new bytes4[](2);
            res[0] = 0xeb3a7d47; // limitRouterCallback
            res[1] = 0xfa483e72; // swapCallback
        }
        if (facet == ACTION_MISC) {
            res = new bytes4[](12);
            res[0] = 0x1a8631b2; // mintPyFromSy
            res[1] = 0x2d8f9d8d; // boostMarkets
            res[2] = 0x2e071dc6; // mintSyFromToken
            res[3] = 0x339748cb; // redeemPyToSy
            res[4] = 0x339a5572; // redeemSyToToken
            res[5] = 0x47f1de22; // redeemPyToToken
            res[6] = 0x5d3e105c; // swapTokenToToken
            res[7] = 0x60fc8466; // multicall
            res[8] = 0xa89eba4a; // swapTokenToTokenViaSy
            res[9] = 0xbd61951d; // simulate
            res[10] = 0xd0f42385; // mintPyFromToken
            res[11] = 0xf7e375e8; // redeemDueInterestAndRewards
        }
    }

    function facetAddress(bytes4 sig) public view returns (address) {
        if (sig < 0x6b77ac9e) {
            if (sig < 0x3dbe1c55) {
                if (sig < 0x2d8f9d8d) {
                    if (sig < 0x1a8631b2) {
                        if (sig == 0x05eb5327) return ACTION_SWAP_YT; //swapExactYtForToken
                        if (sig == 0x12599ac6) return ACTION_ADD_REMOVE_LIQ; //addLiquiditySingleToken
                    } else {
                        if (sig == 0x1a8631b2) return ACTION_MISC; //mintPyFromSy
                        if (sig == 0x2756ce06) return ACTION_ADD_REMOVE_LIQ; //addLiquidityDualTokenAndPt
                        if (sig == 0x2a50917c) return ACTION_SWAP_PT; //swapExactSyForPt
                    }
                } else {
                    if (sig < 0x3346d3a3) {
                        if (sig == 0x2d8f9d8d) return ACTION_MISC; //boostMarkets
                        if (sig == 0x2e071dc6) return ACTION_MISC; //mintSyFromToken
                    } else {
                        if (sig == 0x3346d3a3) return ACTION_SWAP_PT; //swapExactPtForSy
                        if (sig == 0x339748cb) return ACTION_MISC; //redeemPyToSy
                        if (sig == 0x339a5572) return ACTION_MISC; //redeemSyToToken
                    }
                }
            } else {
                if (sig < 0x58bda475) {
                    if (sig < 0x47f1de22) {
                        if (sig == 0x3dbe1c55) return ACTION_ADD_REMOVE_LIQ; //addLiquiditySingleTokenKeepYt
                        if (sig == 0x448b9b95) return ACTION_SWAP_YT; //swapExactYtForPt
                    } else {
                        if (sig == 0x47f1de22) return ACTION_MISC; //redeemPyToToken
                        if (sig == 0x4e390267) return ACTION_ADD_REMOVE_LIQ; //addLiquiditySinglePt
                        if (sig == 0x52ef6b2c) return address(this); //facetAddresses
                    }
                } else {
                    if (sig < 0x5d3e105c) {
                        if (sig == 0x58bda475) return ACTION_ADD_REMOVE_LIQ; //addLiquiditySingleSy
                        if (sig == 0x594a88cc) return ACTION_SWAP_PT; //swapExactPtForToken
                    } else {
                        if (sig == 0x5d3e105c) return ACTION_MISC; //swapTokenToToken
                        if (sig == 0x60da0860) return ACTION_ADD_REMOVE_LIQ; //removeLiquiditySingleToken
                        if (sig == 0x60fc8466) return ACTION_MISC; //multicall
                    }
                }
            }
        } else {
            if (sig < 0xbd61951d) {
                if (sig < 0x97ee279e) {
                    if (sig < 0x7b8b4b95) {
                        if (sig == 0x6b77ac9e) return ACTION_ADD_REMOVE_LIQ; //removeLiquiditySinglePt
                        if (sig == 0x7a0ed627) return address(this); //facets
                    } else {
                        if (sig == 0x7b8b4b95) return ACTION_SWAP_YT; //swapExactSyForYt
                        if (sig == 0x80c4d566) return ACTION_SWAP_YT; //swapExactYtForSy
                        if (sig == 0x844384aa) return ACTION_ADD_REMOVE_LIQ; //addLiquiditySingleSyKeepYt
                    }
                } else {
                    if (sig < 0xadfca15e) {
                        if (sig == 0x97ee279e) return ACTION_ADD_REMOVE_LIQ; //addLiquidityDualSyAndPt
                        if (sig == 0xa89eba4a) return ACTION_MISC; //swapTokenToTokenViaSy
                    } else {
                        if (sig == 0xadfca15e) return address(this); //facetFunctionSelectors
                        if (sig == 0xb00f09d7) return ACTION_ADD_REMOVE_LIQ; //removeLiquidityDualTokenAndPt
                        if (sig == 0xb7d75b8b) return ACTION_ADD_REMOVE_LIQ; //removeLiquidityDualSyAndPt
                    }
                }
            } else {
                if (sig < 0xd13b4fdc) {
                    if (sig < 0xc861a898) {
                        if (sig == 0xbd61951d) return ACTION_MISC; //simulate
                        if (sig == 0xc81f847a) return ACTION_SWAP_PT; //swapExactTokenForPt
                    } else {
                        if (sig == 0xc861a898) return ACTION_SWAP_YT; //swapExactPtForYt
                        if (sig == 0xcdffacc6) return address(this); //facetAddress
                        if (sig == 0xd0f42385) return ACTION_MISC; //mintPyFromToken
                    }
                } else {
                    if (sig < 0xed48907e) {
                        if (sig == 0xd13b4fdc) return ACTION_ADD_REMOVE_LIQ; //removeLiquiditySingleSy
                        if (sig == 0xeb3a7d47) return ACTION_CALLBACK; //limitRouterCallback
                    } else {
                        if (sig == 0xed48907e) return ACTION_SWAP_YT; //swapExactTokenForYt
                        if (sig == 0xf7e375e8) return ACTION_MISC; //redeemDueInterestAndRewards
                        if (sig == 0xfa483e72) return ACTION_CALLBACK; //swapCallback
                    }
                }
            }
        }
        revert Errors.RouterInvalidAction(sig);
        // NUM_FUNC: 40 AVG:4.80 WORST_CASE:6 STOP_BRANCH:3
    }

    function facetAddresses() public view returns (address[] memory) {
        address[] memory res = new address[](6);
        res[0] = address(this);
        res[1] = ACTION_ADD_REMOVE_LIQ;
        res[2] = ACTION_SWAP_YT;
        res[3] = ACTION_SWAP_PT;
        res[4] = ACTION_CALLBACK;
        res[5] = ACTION_MISC;
        return res;
    }

    function _implementation() internal view override returns (address) {
        return facetAddress(msg.sig);
    }
}

File 2 of 29 : Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)

pragma solidity ^0.8.0;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function
     * and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _beforeFallback();
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
     * is empty.
     */
    receive() external payable virtual {
        _fallback();
    }

    /**
     * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
     * call, or as part of the Solidity `fallback` or `receive` functions.
     *
     * If overridden should call `super._beforeFallback()`.
     */
    function _beforeFallback() internal virtual {}
}

File 3 of 29 : IPAllActionV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity ^0.8.0;

import "./IPActionAddRemoveLiqV3.sol";
import "./IPActionSwapPTV3.sol";
import "./IPActionSwapYTV3.sol";
import "./IPActionMiscV3.sol";
import "./IPActionCallbackV3.sol";
import "./IDiamondLoupe.sol";

interface IPAllActionV3 is
    IPActionAddRemoveLiqV3,
    IPActionSwapPTV3,
    IPActionSwapYTV3,
    IPActionMiscV3,
    IPActionCallbackV3,
    IDiamondLoupe
{}

File 4 of 29 : IDiamondLoupe.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/

// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
    /// These functions are expected to be called frequently
    /// by tools.

    struct Facet {
        address facetAddress;
        bytes4[] functionSelectors;
    }

    /// @notice Gets all facet addresses and their four byte function selectors.
    /// @return facets_ Facet
    function facets() external view returns (Facet[] memory facets_);

    /// @notice Gets all the function selectors supported by a specific facet.
    /// @param _facet The facet address.
    /// @return facetFunctionSelectors_
    function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);

    /// @notice Get all the facet addresses used by a diamond.
    /// @return facetAddresses_
    function facetAddresses() external view returns (address[] memory facetAddresses_);

    /// @notice Gets the facet that supports the given selector.
    /// @dev If facet is not found return address(0).
    /// @param _functionSelector The function selector.
    /// @return facetAddress_ The facet address.
    function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}

File 5 of 29 : IDiamondCut.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/

interface IDiamondCut {
    enum FacetCutAction {
        Add,
        Replace,
        Remove
    }
    // Add=0, Replace=1, Remove=2

    struct FacetCut {
        address facetAddress;
        FacetCutAction action;
        bytes4[] functionSelectors;
    }

    /// @notice Add/replace/remove any number of functions and optionally execute
    ///         a function with delegatecall
    /// @param _diamondCut Contains the facet addresses and function selectors
    /// @param _init The address of the contract or facet to execute _calldata
    /// @param _calldata A function call, including function selector and arguments
    ///                  _calldata is executed with delegatecall on _init
    function diamondCut(FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata) external;

    event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}

File 6 of 29 : IBlast.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

interface IBlast {
  function configureClaimableGas() external;
  function configureGovernor(address governor) external;
}

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

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

/*
 *******************************************************************************************************************
 *******************************************************************************************************************
 * NOTICE *
 * Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
 * TokenInput, TokenOutput, ApproxParams, LimitOrderData
 * It's recommended to use Pendle's Hosted SDK to generate the params
 *******************************************************************************************************************
 *******************************************************************************************************************
 */

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 8 of 29 : IPActionSwapPTV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

/*
 *******************************************************************************************************************
 *******************************************************************************************************************
 * NOTICE *
 * Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
 * TokenInput, TokenOutput, ApproxParams, LimitOrderData
 * It's recommended to use Pendle's Hosted SDK to generate the params
 *******************************************************************************************************************
 *******************************************************************************************************************
 */

interface IPActionSwapPTV3 {
    event SwapPtAndSy(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        int256 netPtToAccount,
        int256 netSyToAccount
    );

    event SwapPtAndToken(
        address indexed caller,
        address indexed market,
        address indexed token,
        address receiver,
        int256 netPtToAccount,
        int256 netTokenToAccount,
        uint256 netSyInterm
    );

    function swapExactTokenForPt(
        address receiver,
        address market,
        uint256 minPtOut,
        ApproxParams calldata guessPtOut,
        TokenInput calldata input,
        LimitOrderData calldata limit
    ) external payable returns (uint256 netPtOut, uint256 netSyFee, uint256 netSyInterm);

    function swapExactSyForPt(
        address receiver,
        address market,
        uint256 exactSyIn,
        uint256 minPtOut,
        ApproxParams calldata guessPtOut,
        LimitOrderData calldata limit
    ) external returns (uint256 netPtOut, uint256 netSyFee);

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

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

File 9 of 29 : IPActionSwapYTV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

/*
 *******************************************************************************************************************
 *******************************************************************************************************************
 * NOTICE *
 * Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
 * TokenInput, TokenOutput, ApproxParams, LimitOrderData
 * It's recommended to use Pendle's Hosted SDK to generate the params
 *******************************************************************************************************************
 *******************************************************************************************************************
 */

interface IPActionSwapYTV3 {
    event SwapYtAndSy(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        int256 netYtToAccount,
        int256 netSyToAccount
    );

    event SwapYtAndToken(
        address indexed caller,
        address indexed market,
        address indexed token,
        address receiver,
        int256 netYtToAccount,
        int256 netTokenToAccount,
        uint256 netSyInterm
    );

    event SwapPtAndYt(
        address indexed caller,
        address indexed market,
        address indexed receiver,
        int256 netPtToAccount,
        int256 netYtToAccount
    );

    function swapExactTokenForYt(
        address receiver,
        address market,
        uint256 minYtOut,
        ApproxParams calldata guessYtOut,
        TokenInput calldata input,
        LimitOrderData calldata limit
    ) external payable returns (uint256 netYtOut, uint256 netSyFee, uint256 netSyInterm);

    function swapExactSyForYt(
        address receiver,
        address market,
        uint256 exactSyIn,
        uint256 minYtOut,
        ApproxParams calldata guessYtOut,
        LimitOrderData calldata limit
    ) external returns (uint256 netYtOut, uint256 netSyFee);

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

    function swapExactYtForSy(
        address receiver,
        address market,
        uint256 exactYtIn,
        uint256 minSyOut,
        LimitOrderData calldata limit
    ) external returns (uint256 netSyOut, uint256 netSyFee);

    function swapExactPtForYt(
        address receiver,
        address market,
        uint256 exactPtIn,
        uint256 minYtOut,
        ApproxParams calldata guessTotalPtToSwap
    ) external returns (uint256 netYtOut, uint256 netSyFee);

    function swapExactYtForPt(
        address receiver,
        address market,
        uint256 exactYtIn,
        uint256 minPtOut,
        ApproxParams calldata guessTotalPtFromSwap
    ) external returns (uint256 netPtOut, uint256 netSyFee);
}

File 10 of 29 : IPActionMiscV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

/*
 *******************************************************************************************************************
 *******************************************************************************************************************
 * NOTICE *
 * Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
 * TokenInput, TokenOutput, ApproxParams, LimitOrderData
 * It's recommended to use Pendle's Hosted SDK to generate the params
 *******************************************************************************************************************
 *******************************************************************************************************************
 */

interface IPActionMiscV3 {
    struct Call3 {
        bool allowFailure;
        bytes callData;
    }

    struct Result {
        bool success;
        bytes returnData;
    }

    event MintSyFromToken(
        address indexed caller,
        address indexed tokenIn,
        address indexed SY,
        address receiver,
        uint256 netTokenIn,
        uint256 netSyOut
    );

    event RedeemSyToToken(
        address indexed caller,
        address indexed tokenOut,
        address indexed SY,
        address receiver,
        uint256 netSyIn,
        uint256 netTokenOut
    );

    event MintPyFromSy(
        address indexed caller,
        address indexed receiver,
        address indexed YT,
        uint256 netSyIn,
        uint256 netPyOut
    );

    event RedeemPyToSy(
        address indexed caller,
        address indexed receiver,
        address indexed YT,
        uint256 netPyIn,
        uint256 netSyOut
    );

    event MintPyFromToken(
        address indexed caller,
        address indexed tokenIn,
        address indexed YT,
        address receiver,
        uint256 netTokenIn,
        uint256 netPyOut,
        uint256 netSyInterm
    );

    event RedeemPyToToken(
        address indexed caller,
        address indexed tokenOut,
        address indexed YT,
        address receiver,
        uint256 netPyIn,
        uint256 netTokenOut,
        uint256 netSyInterm
    );

    function mintSyFromToken(
        address receiver,
        address SY,
        uint256 minSyOut,
        TokenInput calldata input
    ) external payable returns (uint256 netSyOut);

    function redeemSyToToken(
        address receiver,
        address SY,
        uint256 netSyIn,
        TokenOutput calldata output
    ) external returns (uint256 netTokenOut);

    function mintPyFromToken(
        address receiver,
        address YT,
        uint256 minPyOut,
        TokenInput calldata input
    ) external payable returns (uint256 netPyOut, uint256 netSyInterm);

    function redeemPyToToken(
        address receiver,
        address YT,
        uint256 netPyIn,
        TokenOutput calldata output
    ) external returns (uint256 netTokenOut, uint256 netSyInterm);

    function mintPyFromSy(
        address receiver,
        address YT,
        uint256 netSyIn,
        uint256 minPyOut
    ) external returns (uint256 netPyOut);

    function redeemPyToSy(
        address receiver,
        address YT,
        uint256 netPyIn,
        uint256 minSyOut
    ) external returns (uint256 netSyOut);

    function redeemDueInterestAndRewards(
        address user,
        address[] calldata sys,
        address[] calldata yts,
        address[] calldata markets
    ) external;

    function swapTokenToToken(
        address receiver,
        uint256 minTokenOut,
        TokenInput calldata inp
    ) external payable returns (uint256 netTokenOut);

    function swapTokenToTokenViaSy(
        address receiver,
        address SY,
        TokenInput calldata input,
        address tokenRedeemSy,
        uint256 minTokenOut
    ) external payable returns (uint256 netTokenOut, uint256 netSyInterm);

    function boostMarkets(address[] memory markets) external;

    function multicall(Call3[] calldata calls) external payable returns (Result[] memory res);

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

File 11 of 29 : IPActionCallbackV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "./IPMarketSwapCallback.sol";
import "./IPLimitRouter.sol";

interface IPActionCallbackV3 is IPMarketSwapCallback, IPLimitRouterCallback {}

File 12 of 29 : 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 13 of 29 : IPAllActionTypeV3.sol
// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity ^0.8.0;

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

/*
 *******************************************************************************************************************
 *******************************************************************************************************************
 * NOTICE *
 * Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
 * TokenInput, TokenOutput, ApproxParams, LimitOrderData
 * It's recommended to use Pendle's Hosted SDK to generate the params
 *******************************************************************************************************************
 *******************************************************************************************************************
 */

struct TokenInput {
    // TOKEN DATA
    address tokenIn;
    uint256 netTokenIn;
    address tokenMintSy;
    // AGGREGATOR DATA
    address pendleSwap;
    SwapData swapData;
}

struct TokenOutput {
    // TOKEN 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 14 of 29 : IPMarketSwapCallback.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPMarketSwapCallback {
    function swapCallback(int256 ptToAccount, int256 syToAccount, bytes calldata data) external;
}

File 15 of 29 : 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 16 of 29 : 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 17 of 29 : 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 18 of 29 : 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 19 of 29 : 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 20 of 29 : 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 21 of 29 : 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 22 of 29 : 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 23 of 29 : 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 24 of 29 : 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 25 of 29 : 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;
    }
}

File 26 of 29 : 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 27 of 29 : 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 28 of 29 : 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 29 of 29 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

Settings
{
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/solmate/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "viaIR": true,
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_ACTION_ADD_REMOVE_LIQ","type":"address"},{"internalType":"address","name":"_ACTION_SWAP_PT","type":"address"},{"internalType":"address","name":"_ACTION_SWAP_YT","type":"address"},{"internalType":"address","name":"_ACTION_MISC","type":"address"},{"internalType":"address","name":"_ACTION_CALLBACK","type":"address"},{"internalType":"address","name":"_governor","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"bytes4","name":"selector","type":"bytes4"}],"name":"RouterInvalidAction","type":"error"},{"anonymous":false,"inputs":[{"components":[{"internalType":"address","name":"facetAddress","type":"address"},{"internalType":"enum IDiamondCut.FacetCutAction","name":"action","type":"uint8"},{"internalType":"bytes4[]","name":"functionSelectors","type":"bytes4[]"}],"indexed":false,"internalType":"struct IDiamondCut.FacetCut[]","name":"_diamondCut","type":"tuple[]"},{"indexed":false,"internalType":"address","name":"_init","type":"address"},{"indexed":false,"internalType":"bytes","name":"_calldata","type":"bytes"}],"name":"DiamondCut","type":"event"},{"stateMutability":"payable","type":"fallback"},{"inputs":[],"name":"BLAST","outputs":[{"internalType":"contract IBlast","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"sig","type":"bytes4"}],"name":"facetAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"facetAddresses","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"facet","type":"address"}],"name":"facetFunctionSelectors","outputs":[{"internalType":"bytes4[]","name":"res","type":"bytes4[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"facets","outputs":[{"components":[{"internalType":"address","name":"facetAddress","type":"address"},{"internalType":"bytes4[]","name":"functionSelectors","type":"bytes4[]"}],"internalType":"struct IDiamondLoupe.Facet[]","name":"facets_","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

610120806040523462000a2c57600060c08262001ce3803803809162000026828562000ab0565b8339810103126200036c576200003c8262000ad4565b916200004b6020820162000ad4565b620000596040830162000ad4565b620000676060840162000ad4565b916200008460a06200007c6080870162000ad4565b950162000ad4565b9560805260a05260c05260e05261010052604051620000a38162000a5b565b6006815260c036602083013730620000bb8262000b01565b526080516001600160a01b0316620000d38262000b25565b5260c0516001600160a01b0316620000eb8262000b36565b5260a0516001600160a01b0316620001038262000b47565b52610100516001600160a01b03166200011c8262000b58565b5260e0516001600160a01b0316620001348262000b69565b528051620001428162000ae9565b9162000152604051938462000ab0565b818352601f19620001638362000ae9565b01845b818110620009f4575050835b828110620005085750505080516200018a8162000ae9565b916200019a604051938462000ab0565b818352601f19620001ab8362000ae9565b01845b818110620004b6575050835b828110620004535750505060405190606082016060835281518091526080830190602060808260051b86010193019185905b828210620003a45787877f8faa70878671ccd212d20771b795c50af8fd3ff6cf27f4bde57e5d4de0aeb6738860208984828401528483820391826040860152520190a173430000000000000000000000000000000000000291823b15620003a057604051634e606c4760e01b815292828460048183855af1801562000395576200037e575b829350803b156200037a57604051631d70c8d360e31b81526001600160a01b0390921660048301529091908290602490829084905af180156200036f5762000354575b6040516110e8908162000bfb82396080518181816105ca01528181610b5401528181610bf00152610fd3015260a05181818161061e01528181610bca01528181610cbc0152611031015260c0518181816105f401528181610b7a01528181610d200152611003015260e05181818161067101528181610c1601528181610c69015261108d01526101005181818161064801528181610f52015261105f0152f35b62000360829162000a31565b6200036c5780620002b4565b80fd5b6040513d84823e3d90fd5b5050fd5b9190926200038c9062000a31565b90829062000271565b6040513d85823e3d90fd5b5080fd5b858503607f19018152835180516001600160a01b031686526020810151949593949293919260038110156200043f579060409160208401520151906060604082015260206080606083019284518094520192019088905b8082106200041b57505050602080600192960192019201909291620001ec565b82516001600160e01b031916845260209384019390920191600190910190620003fb565b634e487b7160e01b89526021600452602489fd5b6001906001600160a01b036200046a828562000be5565b51511662000479828762000be5565b51528560206200048a838862000be5565b51015260206200049b828562000be5565b5101516040620004ac838862000be5565b51015201620001ba565b604051606081016001600160401b03811182821017620004f457906020929160405287815287838201526060604082015282828801015201620001ae565b634e487b7160e01b88526041600452602488fd5b6001600160a01b036200051c828462000be5565b51166200052a828662000be5565b51526001600160a01b0362000540828462000be5565b511690606030831462000981575b6080516001600160a01b031683146200086d575b60c0516001600160a01b03168314620007d2575b60a0516001600160a01b031683146200075f575b610100516001600160a01b03168314620006e3575b60e0516001936001600160a01b0390911614620005cf575b6020620005c5838862000be5565b5101520162000172565b50604051620005de8162000a93565b600c815261018036602083013780630d4318d960e11b620005ff8262000b01565b52632d8f9d8d60e01b620006138262000b25565b526317038ee360e11b620006278262000b36565b5263339748cb60e01b6200063b8262000b47565b526319cd2ab960e11b6200064f8262000b58565b526323f8ef1160e11b620006638262000b69565b5263174f841760e21b620006778262000b7a565b5263307e423360e11b6200068b8262000b8b565b5263544f5d2560e11b6200069f8262000b9d565b5263bd61951d60e01b620006b38262000baf565b5263d0f4238560e01b620006c78262000bc1565b52631efc6ebd60e31b90620006dc9062000bd3565b52620005b7565b5060405190916001600160401b0360608301908111908311176200074b579060019291606082016040526002825260403660208401378163eb3a7d4760e01b6200072d8262000b01565b52637d241f3960e11b90620007429062000b25565b5292506200059f565b634e487b7160e01b87526041600452602487fd5b506040516200076e8162000a77565b60048152608036602083013780630a94245f60e21b6200078e8262000b01565b52633346d3a360e01b620007a28262000b25565b52631652a23360e21b620007b68262000b36565b5263640fc23d60e11b90620007cb9062000b47565b526200058a565b50604051620007e18162000a5b565b6006815260c0366020830137806305eb532760e01b620008018262000b01565b5263448b9b9560e01b620008158262000b25565b52637b8b4b9560e01b620008298262000b36565b526340626ab360e11b6200083d8262000b47565b5263190c351360e31b620008518262000b58565b526376a4483f60e11b90620008669062000b69565b5262000576565b506040516200087c8162000a93565b600c81526101803660208301378063092ccd6360e11b6200089d8262000b01565b526313ab670360e11b620008b18262000b25565b52633dbe1c5560e01b620008c58262000b36565b52634e39026760e01b620008d98262000b47565b526358bda47560e01b620008ed8262000b58565b52630306d04360e51b620009018262000b69565b526335bbd64f60e11b620009158262000b7a565b52634221c25560e11b620009298262000b8b565b52634bf713cf60e11b6200093d8262000b9d565b5263b00f09d760e01b620009518262000baf565b5263b7d75b8b60e01b620009658262000bc1565b5263344ed3f760e21b906200097a9062000bd3565b5262000562565b50604051620009908162000a77565b600481526080366020830137806314bbdacb60e21b620009b08262000b01565b52637a0ed62760e01b620009c48262000b25565b526356fe50af60e11b620009d88262000b36565b526366ffd66360e11b90620009ed9062000b47565b526200054e565b604080519081016001600160401b03811182821017620004f45790602092916040528781526060838201528282880101520162000166565b600080fd5b6001600160401b03811162000a4557604052565b634e487b7160e01b600052604160045260246000fd5b60e081019081106001600160401b0382111762000a4557604052565b60a081019081106001600160401b0382111762000a4557604052565b6101a081019081106001600160401b0382111762000a4557604052565b601f909101601f19168101906001600160401b0382119082101762000a4557604052565b51906001600160a01b038216820362000a2c57565b6001600160401b03811162000a455760051b60200190565b80511562000b0f5760200190565b634e487b7160e01b600052603260045260246000fd5b80516001101562000b0f5760400190565b80516002101562000b0f5760600190565b80516003101562000b0f5760800190565b80516004101562000b0f5760a00190565b80516005101562000b0f5760c00190565b80516006101562000b0f5760e00190565b80516007101562000b0f576101000190565b80516008101562000b0f576101200190565b80516009101562000b0f576101400190565b8051600a101562000b0f576101600190565b8051600b101562000b0f576101800190565b805182101562000b0f5760209160051b01019056fe60806040526004361015610015575b3661035557005b6000803560e01c90816352ef6b2c14610068575080637a0ed6271461006357806397d757761461005e578063adfca15e146100595763cdffacc60361000e57610313565b610298565b610275565b610188565b346100cd57806003193601126100cd57610080610fa1565b90604051918291602080840190808552835180925280604086019401925b8281106100ad57505050500390f35b83516001600160a01b03168552869550938101939281019260010161009e565b80fd5b602080820190808352835180925260409283810182858560051b840101960194600080935b86851061010757505050505050505090565b909192939480969798603f198382030186528951826060818885019360018060a01b038151168652015193888382015284518094520192019085905b8082106101645750505090806001929a0195019501939695949291906100f5565b82516001600160e01b03191684528a94938401939092019160019190910190610143565b34610270576000806003193601126100cd576101a2610fa1565b8051906101b66101b183610408565b6103e2565b82815292601f196101c684610408565b01815b8181106102505750505b8281106101ec57604051806101e886826100d0565b0390f35b8061022661020c6101ff600194866104fd565b516001600160a01b031690565b61021683886104fd565b516001600160a01b039091169052565b61023b6102366101ff83866104fd565b6105af565b602061024783886104fd565b510152016101d3565b60209061025b61039d565b848152826060818301528289010152016101c9565b600080fd5b34610270576000366003190112610270576040516002604360981b018152602090f35b3461027057602080600319360112610270576004356001600160a01b0381168103610270576102c6906105af565b906040519181839283018184528251809152816040850193019160005b8281106102f257505050500390f35b83516001600160e01b031916855286955093810193928101926001016102e3565b34610270576020366003190112610270576004356001600160e01b03198116810361027057610343602091610ab5565b6040516001600160a01b039091168152f35b6000808061036d81356001600160e01b031916610ab5565b368280378136915af43d82803e15610383573d90f35b3d90fd5b634e487b7160e01b600052604160045260246000fd5b604051906040820182811067ffffffffffffffff8211176103bd57604052565b610387565b6040519060e0820182811067ffffffffffffffff8211176103bd57604052565b6040519190601f01601f1916820167ffffffffffffffff8111838210176103bd57604052565b67ffffffffffffffff81116103bd5760051b60200190565b634e487b7160e01b600052603260045260246000fd5b8051156104435760200190565b610420565b8051600110156104435760400190565b8051600210156104435760600190565b8051600310156104435760800190565b8051600410156104435760a00190565b8051600510156104435760c00190565b8051600610156104435760e00190565b805160071015610443576101000190565b805160081015610443576101200190565b805160091015610443576101400190565b8051600a1015610443576101600190565b8051600b1015610443576101800190565b80518210156104435760209160051b010190565b6040519060a0820182811067ffffffffffffffff8211176103bd57604052600482526080366020840137565b604051906101a0820182811067ffffffffffffffff8211176103bd57604052600c8252610180366020840137565b6105736103c2565b600681529060c0366020840137565b604051906060820182811067ffffffffffffffff8211176103bd5760405260028252604082602036910137565b606091906001600160a01b0390811690308214610a45575b807f0000000000000000000000000000000000000000000000000000000000000000168214610915575b807f0000000000000000000000000000000000000000000000000000000000000000168214610875575b807f0000000000000000000000000000000000000000000000000000000000000000168214610805575b807f00000000000000000000000000000000000000000000000000000000000000001682146107c5575b7f0000000000000000000000000000000000000000000000000000000000000000161461069857565b90506106a261053d565b906106bb6106af83610436565b630d4318d960e11b9052565b6106d36106c783610448565b632d8f9d8d60e01b9052565b6106eb6106df83610458565b6317038ee360e11b9052565b6107036106f783610468565b63339748cb60e01b9052565b61071b61070f83610478565b6319cd2ab960e11b9052565b61073361072783610488565b6323f8ef1160e11b9052565b61074b61073f83610498565b63174f841760e21b9052565b610763610757836104a8565b63307e423360e11b9052565b61077b61076f836104b9565b63544f5d2560e11b9052565b610793610787836104ca565b63bd61951d60e01b9052565b6107ab61079f836104db565b63d0f4238560e01b9052565b6107c36107b7836104ec565b631efc6ebd60e31b9052565b565b92506107cf610582565b926107e86107dc85610436565b63eb3a7d4760e01b9052565b6108006107f485610448565b637d241f3960e11b9052565b61066f565b925061080f610511565b9261082861081c85610436565b630a94245f60e21b9052565b61084061083485610448565b633346d3a360e01b9052565b61085861084c85610458565b631652a23360e21b9052565b61087061086485610468565b63640fc23d60e11b9052565b610645565b925061087f61056b565b9261089861088c85610436565b6305eb532760e01b9052565b6108b06108a485610448565b63448b9b9560e01b9052565b6108c86108bc85610458565b637b8b4b9560e01b9052565b6108e06108d485610468565b6340626ab360e11b9052565b6108f86108ec85610478565b63190c351360e31b9052565b61091061090485610488565b6376a4483f60e11b9052565b61061b565b925061091f61053d565b9261093861092c85610436565b63092ccd6360e11b9052565b61095061094485610448565b6313ab670360e11b9052565b61096861095c85610458565b633dbe1c5560e01b9052565b61098061097485610468565b634e39026760e01b9052565b61099861098c85610478565b6358bda47560e01b9052565b6109b06109a485610488565b630306d04360e51b9052565b6109c86109bc85610498565b6335bbd64f60e11b9052565b6109e06109d4856104a8565b634221c25560e11b9052565b6109f86109ec856104b9565b634bf713cf60e11b9052565b610a10610a04856104ca565b63b00f09d760e01b9052565b610a28610a1c856104db565b63b7d75b8b60e01b9052565b610a40610a34856104ec565b63344ed3f760e21b9052565b6105f1565b9250610a4f610511565b92610a68610a5c85610436565b6314bbdacb60e21b9052565b610a80610a7485610448565b637a0ed62760e01b9052565b610a98610a8c85610458565b6356fe50af60e11b9052565b610ab0610aa485610468565b6366ffd66360e11b9052565b6105c7565b6001600160e01b031981166335bbd64f60e11b80821015610dd15750633dbe1c5560e01b80821015610cde5750632d8f9d8d60e01b80821015610c385750630d4318d960e11b80821015610b9c57506305eb532760e01b8114610b765763092ccd6360e11b14610b5157610b4d91505b604051636ad67de160e11b81526001600160e01b031990911660048201529081906024820190565b0390fd5b507f000000000000000000000000000000000000000000000000000000000000000090565b50507f000000000000000000000000000000000000000000000000000000000000000090565b8114610c12576313ab670360e11b8114610bec57630a94245f60e21b14610bc757610b4d9150610b25565b507f000000000000000000000000000000000000000000000000000000000000000090565b50507f000000000000000000000000000000000000000000000000000000000000000090565b50507f000000000000000000000000000000000000000000000000000000000000000090565b633346d3a360e01b80831015610c8b57508114610c12576317038ee360e11b14610c6657610b4d9150610b25565b507f000000000000000000000000000000000000000000000000000000000000000090565b90508114610cb85763339748cb60e01b8114610c12576319cd2ab960e11b14610c6657610b4d9150610b25565b50507f000000000000000000000000000000000000000000000000000000000000000090565b6358bda47560e01b80831015610d7457506323f8ef1160e11b80831015610d4257508114610bec5763448b9b9560e01b14610d1d57610b4d9150610b25565b507f000000000000000000000000000000000000000000000000000000000000000090565b90508114610c1257634e39026760e01b8114610bec576314bbdacb60e21b14610d6f57610b4d9150610b25565b503090565b905063174f841760e21b80831015610da457508114610bec57631652a23360e21b14610bc757610b4d9150610b25565b90508114610c1257630306d04360e51b8114610bec5763307e423360e11b14610c6657610b4d9150610b25565b63bd61951d60e01b80831015610eb15750634bf713cf60e11b80831015610e4e5750637b8b4b9560e01b80831015610e2157508114610bec57637a0ed62760e01b14610d6f57610b4d9150610b25565b90508114610b76576340626ab360e11b8114610b7657634221c25560e11b14610b5157610b4d9150610b25565b90506356fe50af60e11b80831015610e7e57508114610bec5763544f5d2560e11b14610c6657610b4d9150610b25565b90508114610eab5763b00f09d760e01b8114610bec5763b7d75b8b60e01b14610b5157610b4d9150610b25565b50503090565b905063344ed3f760e21b80831015610f1f575063190c351360e31b80831015610ef257508114610c125763640fc23d60e11b14610bc757610b4d9150610b25565b90508114610b76576366ffd66360e11b8114610eab5763d0f4238560e01b14610c6657610b4d9150610b25565b90506376a4483f60e11b80831015610f7457508114610bec5763eb3a7d4760e01b14610f4f57610b4d9150610b25565b507f000000000000000000000000000000000000000000000000000000000000000090565b90508114610b7657631efc6ebd60e31b8114610c1257637d241f3960e11b14610f4f57610b4d9150610b25565b610fa96103c2565b600681526020810160c036823781511561044357309052610fc981610448565b6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811690915261100082610458565b817f000000000000000000000000000000000000000000000000000000000000000016905261102e82610468565b817f000000000000000000000000000000000000000000000000000000000000000016905261105c82610478565b817f000000000000000000000000000000000000000000000000000000000000000016905261108a82610488565b907f00000000000000000000000000000000000000000000000000000000000000001690529056fea2646970667358221220a810963e5296ca0206c0e012299aa41baf03eb745616dac4f4c2388e41d0a79f64736f6c63430008140033000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca929421000000000000000000000000e59d976581e4152cc39b94041c626c726d3ab0e700000000000000000000000088653cb81db25da4136448bdf561b41b77b052c4

Deployed Bytecode

0x60806040526004361015610015575b3661035557005b6000803560e01c90816352ef6b2c14610068575080637a0ed6271461006357806397d757761461005e578063adfca15e146100595763cdffacc60361000e57610313565b610298565b610275565b610188565b346100cd57806003193601126100cd57610080610fa1565b90604051918291602080840190808552835180925280604086019401925b8281106100ad57505050500390f35b83516001600160a01b03168552869550938101939281019260010161009e565b80fd5b602080820190808352835180925260409283810182858560051b840101960194600080935b86851061010757505050505050505090565b909192939480969798603f198382030186528951826060818885019360018060a01b038151168652015193888382015284518094520192019085905b8082106101645750505090806001929a0195019501939695949291906100f5565b82516001600160e01b03191684528a94938401939092019160019190910190610143565b34610270576000806003193601126100cd576101a2610fa1565b8051906101b66101b183610408565b6103e2565b82815292601f196101c684610408565b01815b8181106102505750505b8281106101ec57604051806101e886826100d0565b0390f35b8061022661020c6101ff600194866104fd565b516001600160a01b031690565b61021683886104fd565b516001600160a01b039091169052565b61023b6102366101ff83866104fd565b6105af565b602061024783886104fd565b510152016101d3565b60209061025b61039d565b848152826060818301528289010152016101c9565b600080fd5b34610270576000366003190112610270576040516002604360981b018152602090f35b3461027057602080600319360112610270576004356001600160a01b0381168103610270576102c6906105af565b906040519181839283018184528251809152816040850193019160005b8281106102f257505050500390f35b83516001600160e01b031916855286955093810193928101926001016102e3565b34610270576020366003190112610270576004356001600160e01b03198116810361027057610343602091610ab5565b6040516001600160a01b039091168152f35b6000808061036d81356001600160e01b031916610ab5565b368280378136915af43d82803e15610383573d90f35b3d90fd5b634e487b7160e01b600052604160045260246000fd5b604051906040820182811067ffffffffffffffff8211176103bd57604052565b610387565b6040519060e0820182811067ffffffffffffffff8211176103bd57604052565b6040519190601f01601f1916820167ffffffffffffffff8111838210176103bd57604052565b67ffffffffffffffff81116103bd5760051b60200190565b634e487b7160e01b600052603260045260246000fd5b8051156104435760200190565b610420565b8051600110156104435760400190565b8051600210156104435760600190565b8051600310156104435760800190565b8051600410156104435760a00190565b8051600510156104435760c00190565b8051600610156104435760e00190565b805160071015610443576101000190565b805160081015610443576101200190565b805160091015610443576101400190565b8051600a1015610443576101600190565b8051600b1015610443576101800190565b80518210156104435760209160051b010190565b6040519060a0820182811067ffffffffffffffff8211176103bd57604052600482526080366020840137565b604051906101a0820182811067ffffffffffffffff8211176103bd57604052600c8252610180366020840137565b6105736103c2565b600681529060c0366020840137565b604051906060820182811067ffffffffffffffff8211176103bd5760405260028252604082602036910137565b606091906001600160a01b0390811690308214610a45575b807f000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d168214610915575b807f0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f168214610875575b807f000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee168214610805575b807f000000000000000000000000e59d976581e4152cc39b94041c626c726d3ab0e71682146107c5575b7f0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca929421161461069857565b90506106a261053d565b906106bb6106af83610436565b630d4318d960e11b9052565b6106d36106c783610448565b632d8f9d8d60e01b9052565b6106eb6106df83610458565b6317038ee360e11b9052565b6107036106f783610468565b63339748cb60e01b9052565b61071b61070f83610478565b6319cd2ab960e11b9052565b61073361072783610488565b6323f8ef1160e11b9052565b61074b61073f83610498565b63174f841760e21b9052565b610763610757836104a8565b63307e423360e11b9052565b61077b61076f836104b9565b63544f5d2560e11b9052565b610793610787836104ca565b63bd61951d60e01b9052565b6107ab61079f836104db565b63d0f4238560e01b9052565b6107c36107b7836104ec565b631efc6ebd60e31b9052565b565b92506107cf610582565b926107e86107dc85610436565b63eb3a7d4760e01b9052565b6108006107f485610448565b637d241f3960e11b9052565b61066f565b925061080f610511565b9261082861081c85610436565b630a94245f60e21b9052565b61084061083485610448565b633346d3a360e01b9052565b61085861084c85610458565b631652a23360e21b9052565b61087061086485610468565b63640fc23d60e11b9052565b610645565b925061087f61056b565b9261089861088c85610436565b6305eb532760e01b9052565b6108b06108a485610448565b63448b9b9560e01b9052565b6108c86108bc85610458565b637b8b4b9560e01b9052565b6108e06108d485610468565b6340626ab360e11b9052565b6108f86108ec85610478565b63190c351360e31b9052565b61091061090485610488565b6376a4483f60e11b9052565b61061b565b925061091f61053d565b9261093861092c85610436565b63092ccd6360e11b9052565b61095061094485610448565b6313ab670360e11b9052565b61096861095c85610458565b633dbe1c5560e01b9052565b61098061097485610468565b634e39026760e01b9052565b61099861098c85610478565b6358bda47560e01b9052565b6109b06109a485610488565b630306d04360e51b9052565b6109c86109bc85610498565b6335bbd64f60e11b9052565b6109e06109d4856104a8565b634221c25560e11b9052565b6109f86109ec856104b9565b634bf713cf60e11b9052565b610a10610a04856104ca565b63b00f09d760e01b9052565b610a28610a1c856104db565b63b7d75b8b60e01b9052565b610a40610a34856104ec565b63344ed3f760e21b9052565b6105f1565b9250610a4f610511565b92610a68610a5c85610436565b6314bbdacb60e21b9052565b610a80610a7485610448565b637a0ed62760e01b9052565b610a98610a8c85610458565b6356fe50af60e11b9052565b610ab0610aa485610468565b6366ffd66360e11b9052565b6105c7565b6001600160e01b031981166335bbd64f60e11b80821015610dd15750633dbe1c5560e01b80821015610cde5750632d8f9d8d60e01b80821015610c385750630d4318d960e11b80821015610b9c57506305eb532760e01b8114610b765763092ccd6360e11b14610b5157610b4d91505b604051636ad67de160e11b81526001600160e01b031990911660048201529081906024820190565b0390fd5b507f000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d90565b50507f0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f90565b8114610c12576313ab670360e11b8114610bec57630a94245f60e21b14610bc757610b4d9150610b25565b507f000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee90565b50507f000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d90565b50507f0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca92942190565b633346d3a360e01b80831015610c8b57508114610c12576317038ee360e11b14610c6657610b4d9150610b25565b507f0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca92942190565b90508114610cb85763339748cb60e01b8114610c12576319cd2ab960e11b14610c6657610b4d9150610b25565b50507f000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee90565b6358bda47560e01b80831015610d7457506323f8ef1160e11b80831015610d4257508114610bec5763448b9b9560e01b14610d1d57610b4d9150610b25565b507f0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f90565b90508114610c1257634e39026760e01b8114610bec576314bbdacb60e21b14610d6f57610b4d9150610b25565b503090565b905063174f841760e21b80831015610da457508114610bec57631652a23360e21b14610bc757610b4d9150610b25565b90508114610c1257630306d04360e51b8114610bec5763307e423360e11b14610c6657610b4d9150610b25565b63bd61951d60e01b80831015610eb15750634bf713cf60e11b80831015610e4e5750637b8b4b9560e01b80831015610e2157508114610bec57637a0ed62760e01b14610d6f57610b4d9150610b25565b90508114610b76576340626ab360e11b8114610b7657634221c25560e11b14610b5157610b4d9150610b25565b90506356fe50af60e11b80831015610e7e57508114610bec5763544f5d2560e11b14610c6657610b4d9150610b25565b90508114610eab5763b00f09d760e01b8114610bec5763b7d75b8b60e01b14610b5157610b4d9150610b25565b50503090565b905063344ed3f760e21b80831015610f1f575063190c351360e31b80831015610ef257508114610c125763640fc23d60e11b14610bc757610b4d9150610b25565b90508114610b76576366ffd66360e11b8114610eab5763d0f4238560e01b14610c6657610b4d9150610b25565b90506376a4483f60e11b80831015610f7457508114610bec5763eb3a7d4760e01b14610f4f57610b4d9150610b25565b507f000000000000000000000000e59d976581e4152cc39b94041c626c726d3ab0e790565b90508114610b7657631efc6ebd60e31b8114610c1257637d241f3960e11b14610f4f57610b4d9150610b25565b610fa96103c2565b600681526020810160c036823781511561044357309052610fc981610448565b6001600160a01b037f000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d811690915261100082610458565b817f0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f16905261102e82610468565b817f000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee16905261105c82610478565b817f000000000000000000000000e59d976581e4152cc39b94041c626c726d3ab0e716905261108a82610488565b907f0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca9294211690529056fea2646970667358221220a810963e5296ca0206c0e012299aa41baf03eb745616dac4f4c2388e41d0a79f64736f6c63430008140033

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

000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca929421000000000000000000000000e59d976581e4152cc39b94041c626c726d3ab0e700000000000000000000000088653cb81db25da4136448bdf561b41b77b052c4

-----Decoded View---------------
Arg [0] : _ACTION_ADD_REMOVE_LIQ (address): 0xA884A04bf1b21039bb3250fa6b3549B8f7A4B56D
Arg [1] : _ACTION_SWAP_PT (address): 0x414A0508Ff0CAfBc4b6feb74c736d2295F7293EE
Arg [2] : _ACTION_SWAP_YT (address): 0x0d1B44cCBA201a1cFb30E8455051e137f328682f
Arg [3] : _ACTION_MISC (address): 0x6a28aBf3D78ff1fbf4562FBCa41F43c0ca929421
Arg [4] : _ACTION_CALLBACK (address): 0xe59d976581e4152Cc39B94041C626c726D3AB0E7
Arg [5] : _governor (address): 0x88653cb81db25dA4136448BDf561B41B77b052C4

-----Encoded View---------------
6 Constructor Arguments found :
Arg [0] : 000000000000000000000000a884a04bf1b21039bb3250fa6b3549b8f7a4b56d
Arg [1] : 000000000000000000000000414a0508ff0cafbc4b6feb74c736d2295f7293ee
Arg [2] : 0000000000000000000000000d1b44ccba201a1cfb30e8455051e137f328682f
Arg [3] : 0000000000000000000000006a28abf3d78ff1fbf4562fbca41f43c0ca929421
Arg [4] : 000000000000000000000000e59d976581e4152cc39b94041c626c726d3ab0e7
Arg [5] : 00000000000000000000000088653cb81db25da4136448bdf561b41b77b052c4


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
[ Download: CSV Export  ]

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.