Skip to content
Verified contractPartialGPL-3.0-or-later

PendlePTLooper

Address0x9835a4e15fd34f8d3217beffaa011fab9b8bea0b
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 1,000,000 runs
EVM version
cancun
Via IR
yes
License
GPL-3.0-or-later
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,384,255
Creation transaction
0x912087f958…9ca2244505

33 files

lib/pendle-core-v2/contracts/pt-looping/PendlePTLooper.sol

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

import {PMath} from "../core/libraries/math/PMath.sol";
import {ArrayLib} from "../core/libraries/ArrayLib.sol";
import {BoxCall, BoxData, IPLoopPositionBox} from "../interfaces/IPLoopPositionBox.sol";
import {IMoneyMarket, MarketCtx, createMarketCtx} from "../interfaces/IMoneyMarket.sol";
import {PTLooperBase} from "./PTLooperBase.sol";
import {IPPrincipalToken} from "../interfaces/IPPrincipalToken.sol";
import {IPPostPtLoopStateChecker} from "../interfaces/IPPostPtLoopStateChecker.sol";

contract PendlePTLooper is PTLooperBase {
    using PMath for uint256;

    IPPostPtLoopStateChecker public immutable POST_LOOP_STATE_CHECKER;

    constructor(address treasury, address positionBoxFactory, address postStateChecker)
        PTLooperBase(treasury, positionBoxFactory)
    {
        _disableInitializers();
        POST_LOOP_STATE_CHECKER = IPPostPtLoopStateChecker(postStateChecker);
    }

    function initialize(address _owner) external initializer {
        __EIP712_init(_EIP712Name(), _EIP712Version());
        __BoringOwnableV2_init(_owner);
    }

    function settleBox(address owner, bytes32 boxId, bool repayDebt, bool lendPt, address[] calldata tokensToOwner)
        external
        onlyExecutor
    {
        (IPLoopPositionBox box, IMoneyMarket mm, BoxData memory bd) =
            POSITION_BOX_FACTORY.deployPositionBoxAndMoneyMarket(owner, boxId);
        MarketCtx memory ctx = createMarketCtx(box, bd);

        if (repayDebt) {
            uint256 netRepaid = mm.repay(ctx, _boxBal(box, bd.spokeDebtToken));
            emit MoneyMarketRepaidThenWithdrawn(box, netRepaid, 0);
        }
        if (lendPt) {
            uint256 netLent = mm.lend(ctx, _boxBal(box, bd.spokePt));
            emit MoneyMarketLentThenBorrowed(box, netLent, 0);
        }

        for (uint256 i = 0; i < tokensToOwner.length; ++i) {
            uint256 amount = _boxBal(box, tokensToOwner[i]);
            _boxWithdraw(box, owner, tokensToOwner[i], amount);
            emit Withdrawn(owner, boxId, bytes32(0), tokensToOwner[i], amount);
        }
    }

    function increaseLoopPosition(IncreasePositionMessage memory ms, IncreasePositionRequest memory req)
        external
        onlyExecutor
    {
        Session memory s = _authorizedSession(ms.owner, req.header, _hashTyped(req));
        if (ms.flashAmount == 0) {
            _increase(ms, req, s);
        } else {
            _flashLoan(s, ms.flashAmount, abi.encodeCall(this.flashIncrease, (ms, req, s)));
        }
        // After the loan is paid back, so the checks see the final state.
        _checkLTV(s, req.postBorrowMaxLTV);
        POST_LOOP_STATE_CHECKER.check(s.marketCtx, ms.postStateCheckData);
    }

    /// @dev The iteration body. With a flash loan it runs inside the loan, and the box holds `ms.flashAmount`
    /// until Morpho pulls it back.
    function _increase(IncreasePositionMessage memory ms, IncreasePositionRequest memory req, Session memory s)
        internal
    {
        uint256 preInBalance;
        uint256 netPtToMM;
        uint256 postDebtBal;

        if (_onHub(s.bd)) {
            (preInBalance, netPtToMM) = _runHubIncrease(ms, req, s);
        } else {
            netPtToMM = _boxBal(s.box, s.bd.spokePt);
        }

        if (_onSpoke(s.bd)) {
            postDebtBal = _runSpokeIncrease(ms, req, s, netPtToMM);
        }

        postDebtBal -= ms.flashAmount; // Morpho pulls the loan back after the body

        emit PositionIncreased(ms.owner, req.header.boxId, s.requestHash, preInBalance, netPtToMM, postDebtBal);
    }

    function _runHubIncrease(IncreasePositionMessage memory ms, IncreasePositionRequest memory req, Session memory s)
        internal
        returns (uint256 preInBalance, uint256 netPtToMM)
    {
        // Any iteration can set `swapInitToken`, so the owner can deposit more `initTokenIn` during a request.
        (address tokenIn, uint256 minSwapRate) =
            ms.swapInitToken ? (req.initTokenIn, req.initMinToPtSwapRate) : (s.bd.hubDebtToken, req.minDebtToPtSwapRate);
        minSwapRate = PMath.max(minSwapRate, ms.minSwapRate);

        preInBalance = _boxBal(s.box, tokenIn);

        _boxWithdraw(s.box, TREASURY, tokenIn, ms.fee);

        uint256 netIn = preInBalance - ms.fee;

        uint256 netPtSwappedOut;
        (netPtToMM, netPtSwappedOut) = _boxSwapToken(s.box, tokenIn, netIn, s.bd.hubPt, minSwapRate, ms.swap);
        if (req.isZeroPriceImpact) {
            _boxWithdraw(s.box, ms.owner, IPPrincipalToken(s.bd.hubPt).YT(), netPtSwappedOut);
        }

        if (_isCrossChain(s.bd)) {
            _boxBridgeToken(s, ms.bridge, s.bd.hubPt, netPtToMM, s.bd.spokePt, req.header.swapBridgeSlippage, false);
        }
    }

    function _runSpokeIncrease(
        IncreasePositionMessage memory ms,
        IncreasePositionRequest memory req,
        Session memory s,
        uint256 netPtToMM
    ) internal returns (uint256 postDebtBal) {
        uint256 netLent = s.spokeMM.lend(s.marketCtx, netPtToMM);
        uint256 netBorrowed = s.spokeMM.borrow(s.marketCtx, ms.amountDebtBorrowed);
        emit MoneyMarketLentThenBorrowed(s.box, netLent, netBorrowed);

        postDebtBal = _boxBal(s.box, s.bd.spokeDebtToken);
        if (_isCrossChain(s.bd)) {
            _boxBridgeToken(
                s, ms.bridge, s.bd.spokeDebtToken, postDebtBal, s.bd.hubDebtToken, req.header.swapBridgeSlippage, false
            );
        }
    }

    function decreaseLoopPosition(DecreasePositionMessage memory ms, DecreasePositionRequest memory req)
        external
        onlyExecutor
    {
        Session memory s = _authorizedSession(ms.owner, req.header, _hashTyped(req));
        if (ms.flashAmount == 0) {
            _decrease(ms, req, s);
        } else {
            _flashLoan(s, ms.flashAmount, abi.encodeCall(this.flashDecrease, (ms, req, s)));
        }
        // After the loan is paid back, so the checks see the final state.
        _checkLTV(s, req.postWithdrawMaxLTV);
        POST_LOOP_STATE_CHECKER.check(s.marketCtx, ms.postStateCheckData);
    }

    /// @dev See `_increase`.
    function _decrease(DecreasePositionMessage memory ms, DecreasePositionRequest memory req, Session memory s)
        internal
    {
        uint256 preDebtBal;
        uint256 netPtToSwap;
        uint256 postDebtBal;

        if (_onSpoke(s.bd)) {
            (preDebtBal, netPtToSwap) = _runSpokeDecrease(ms, req, s);
        } else {
            netPtToSwap = _boxBal(s.box, s.bd.hubPt);
        }

        if (_onHub(s.bd)) {
            postDebtBal = _runHubDecrease(ms, req, s, netPtToSwap);
        }

        postDebtBal -= ms.flashAmount; // Morpho pulls the loan back after the body

        emit PositionDecreased(ms.owner, req.header.boxId, s.requestHash, preDebtBal, netPtToSwap, postDebtBal);
    }

    function _runSpokeDecrease(DecreasePositionMessage memory ms, DecreasePositionRequest memory req, Session memory s)
        internal
        returns (uint256 preDebtBal, uint256 netPtToSwap)
    {
        preDebtBal = _boxBal(s.box, s.bd.spokeDebtToken);
        uint256 netRepaid = s.spokeMM.repay(s.marketCtx, preDebtBal);
        uint256 netWithdrawn = s.spokeMM.withdraw(s.marketCtx, ms.amountPtWithdrawn);
        emit MoneyMarketRepaidThenWithdrawn(s.box, netRepaid, netWithdrawn);

        netPtToSwap = _boxBal(s.box, s.bd.spokePt);
        if (_isCrossChain(s.bd)) {
            _boxBridgeToken(s, ms.bridge, s.bd.spokePt, netPtToSwap, s.bd.hubPt, req.header.swapBridgeSlippage, false);
        }
    }

    function _runHubDecrease(
        DecreasePositionMessage memory ms,
        DecreasePositionRequest memory req,
        Session memory s,
        uint256 netPtToSwap
    ) internal returns (uint256 postDebtBal) {
        uint256 minSwapRate = PMath.max(ms.minSwapRate, req.minPtToDebtSwapRate);
        (uint256 preFeeDebtBal,) = req.redeemWithPY
            ? _boxRedeemPYToToken(s.box, s.bd.hubPt, netPtToSwap, s.bd.hubDebtToken, minSwapRate, ms.swap)
            : _boxSwapToken(s.box, s.bd.hubPt, netPtToSwap, s.bd.hubDebtToken, minSwapRate, ms.swap);

        _boxWithdraw(s.box, TREASURY, s.bd.hubDebtToken, ms.fee);
        postDebtBal = preFeeDebtBal - ms.fee;

        if (_isCrossChain(s.bd)) {
            _boxBridgeToken(
                s, ms.bridge, s.bd.hubDebtToken, postDebtBal, s.bd.spokeDebtToken, req.header.swapBridgeSlippage, false
            );
        }
    }

    function swapBridgeWithdrawAll(SwapBridgeWithdrawAllMessage memory ms, SwapBridgeWithdrawAllRequest memory req)
        external
        onlyExecutor
    {
        Session memory s = _authorizedSession(ms.owner, req.header, _hashTyped(req));

        address tokenOutHere = _onHub(s.bd) ? req.hubTokenOut : req.dstTokenOut;

        uint256 postBal;
        {
            address tokenIn = _debtTokenHere(s.bd);
            (postBal,) = _boxSwapToken(s.box, tokenIn, _boxBal(s.box, tokenIn), tokenOutHere, ms.minSwapRate, ms.swap);
        }

        require(postBal >= req.minTokenWithdrawn, "PTLooper: insufficient token out");

        uint32 destChainId = req.receiveOnSpoke ? s.bd.spokeChainId : s.bd.hubChainId;
        if (destChainId != block.chainid) {
            _boxBridgeToken(s, ms.bridge, tokenOutHere, postBal, req.dstTokenOut, req.header.swapBridgeSlippage, false);
        } else {
            _boxWithdraw(s.box, ms.owner, tokenOutHere, postBal);
            emit Withdrawn(ms.owner, req.header.boxId, s.requestHash, tokenOutHere, postBal);
        }

        POST_LOOP_STATE_CHECKER.check(s.marketCtx, ms.postStateCheckData);
    }

    // ========== Flash loan ==========

    /// @dev Called after auth. The box borrows `amount` from Morpho and, inside the loan, calls back with `call`
    /// (`flashIncrease` / `flashDecrease`). `onlyFlashCall` lets only that exact call run, once, from that box.
    function _flashLoan(Session memory s, uint256 amount, bytes memory call) internal {
        require(!_isCrossChain(s.bd), "PTLooper: cross-chain flash loan");
        _flashCallHash = keccak256(call);
        emit FlashLoaned(s.box, s.bd.spokeDebtToken, amount);
        s.box.flashLoan(s.bd.spokeDebtToken, amount, call);
    }

    modifier onlyFlashCall(IPLoopPositionBox box) {
        require(
            msg.sender == address(box) && keccak256(msg.data) == _flashCallHash, "PTLooper: unauthorized flash call"
        );
        _flashCallHash = bytes32(0);
        _;
    }

    /// @dev Runs inside the loan. The auth ran in `increaseLoopPosition`.
    function flashIncrease(IncreasePositionMessage memory ms, IncreasePositionRequest memory req, Session memory s)
        external
        onlyFlashCall(s.box)
    {
        _increase(ms, req, s);
    }

    /// @dev Runs inside the loan. The auth ran in `decreaseLoopPosition`.
    function flashDecrease(DecreasePositionMessage memory ms, DecreasePositionRequest memory req, Session memory s)
        external
        onlyFlashCall(s.box)
    {
        _decrease(ms, req, s);
    }

    /// @param tokenInBal the box's whole `tokenIn` balance before the call.
    /// @return postTokenOutBal the box's whole `tokenOut` balance after the call.
    /// @return netSwappedOut the `tokenOut` that the swap gave. 0 with no swap.
    function _boxSwapToken(
        IPLoopPositionBox box,
        address tokenIn,
        uint256 tokenInBal,
        address tokenOut,
        uint256 minSwapRate,
        BoxApprovedCall memory swap
    ) internal returns (uint256 postTokenOutBal, uint256 netSwappedOut) {
        if (tokenIn == tokenOut) return (tokenInBal, 0);

        BoxCall memory call = tokenIn == NATIVE
            ? _toBoxCall(swap, new address[](0), new uint256[](0), tokenInBal)
            : _toBoxCall(swap, ArrayLib.create(tokenIn), ArrayLib.create(tokenInBal), 0);

        (postTokenOutBal, netSwappedOut) = _boxExecSwap(box, tokenInBal, tokenOut, minSwapRate, call);

        if (netSwappedOut > 0) emit TokenSwapped(box, tokenIn, tokenInBal, tokenOut, netSwappedOut);
    }

    /// @dev PT + YT to `tokenOut`. The box approves min(PT, YT) of each; the router must spend them 1:1.
    /// @param ptBal the box's whole `pt` balance before the call.
    function _boxRedeemPYToToken(
        IPLoopPositionBox box,
        address pt,
        uint256 ptBal,
        address tokenOut,
        uint256 minSwapRate,
        BoxApprovedCall memory swap
    ) internal returns (uint256 postTokenOutBal, uint256 netSwappedOut) {
        address yt = IPPrincipalToken(pt).YT();
        uint256 ytBal = _boxBal(box, yt);
        uint256 netPyIn = PMath.min(ytBal, ptBal);

        BoxCall memory call = _toBoxCall(swap, ArrayLib.create(pt, yt), ArrayLib.create(netPyIn, netPyIn), 0);
        (postTokenOutBal, netSwappedOut) = _boxExecSwap(box, netPyIn, tokenOut, minSwapRate, call);

        // An underflow (the router sent PT or YT to the box) reverts on purpose.
        require(ytBal - _boxBal(box, yt) == ptBal - _boxBal(box, pt), "PTLooper: PY redeem mismatch");

        if (netSwappedOut > 0) emit PYRedeemed(box, pt, netPyIn, tokenOut, netSwappedOut);
    }

    /// @dev No swap, and no rate check, when `call.extRouter == address(0)`.
    function _boxExecSwap(
        IPLoopPositionBox box,
        uint256 netIn,
        address tokenOut,
        uint256 minSwapRate,
        BoxCall memory call
    ) internal returns (uint256 postTokenOutBal, uint256 netSwappedOut) {
        uint256 preTokenOutBal = _boxBal(box, tokenOut);
        if (call.extRouter == address(0)) return (preTokenOutBal, 0);

        box.approveAndCall(call, address(box));
        postTokenOutBal = _boxBal(box, tokenOut);
        netSwappedOut = postTokenOutBal - preTokenOutBal;

        require(netSwappedOut * PMath.ONE >= netIn * minSwapRate, "PTLooper: swap below minSwapRate");
    }

    function _toBoxCall(
        BoxApprovedCall memory swap,
        address[] memory tokens,
        uint256[] memory amounts,
        uint256 nativeAmount
    ) internal pure returns (BoxCall memory) {
        return BoxCall({
            tokens: tokens,
            amounts: amounts,
            nativeAmount: nativeAmount,
            approve: swap.approve,
            extRouter: swap.extRouter,
            callData: swap.callData
        });
    }

    /// @dev Stub until cross-chain lands. Only a cross-chain box gets here.
    function _boxBridgeToken(Session memory, BridgeData memory, address, uint256, address, uint256, bool)
        internal
        pure
    {
        revert("PTLooper: bridging not supported");
    }

    function _boxBal(IPLoopPositionBox box, address token) internal view returns (uint256) {
        return _balanceOf(address(box), token);
    }

    function _boxWithdraw(IPLoopPositionBox box, address to, address token, uint256 amount) internal {
        if (amount == 0) return;
        box.withdrawTo(to, token, amount);
    }

    function _onHub(BoxData memory bd) internal view returns (bool) {
        return bd.hubChainId == block.chainid;
    }

    function _onSpoke(BoxData memory bd) internal view returns (bool) {
        return bd.spokeChainId == block.chainid;
    }

    function _isCrossChain(BoxData memory bd) internal pure returns (bool) {
        return bd.hubChainId != bd.spokeChainId;
    }

    function _debtTokenHere(BoxData memory bd) internal view returns (address) {
        if (_onHub(bd)) return bd.hubDebtToken;
        if (_onSpoke(bd)) return bd.spokeDebtToken;
        revert("PTLooper: unsupported chainid");
    }

    /// @dev No debt, or no money market on this chain: the check passes with no oracle read.
    function _checkLTV(Session memory s, uint256 maxLTV) internal {
        if (address(s.spokeMM) == address(0)) return;
        uint256 debt = s.spokeMM.debtBalance(s.marketCtx);
        if (debt == 0) return;
        uint256 colat = s.spokeMM.collateralBalance(s.marketCtx);
        uint256 ptDebtRate = s.spokeMM.oraclePtDebtRate(s.marketCtx);
        require(debt <= colat.mulDown(ptDebtRate).mulDown(maxLTV), "PTLooper: maxLTV exceeded");
    }
}

lib/pendle-core-v2/contracts/core/libraries/ArrayLib.sol

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

library ArrayLib {
    function sum(uint256[] memory input) internal pure returns (uint256) {
        uint256 value = 0;
        for (uint256 i = 0; i < input.length;) {
            value += input[i];
            unchecked {
                i++;
            }
        }
        return value;
    }

    /// @notice return index of the element if found, else return uint256.max
    function find(address[] memory array, address element) internal pure returns (uint256 index) {
        uint256 length = array.length;
        for (uint256 i = 0; i < length;) {
            if (array[i] == element) return i;
            unchecked {
                i++;
            }
        }
        return type(uint256).max;
    }

    function append(address[] memory inp, address element) internal pure returns (address[] memory out) {
        uint256 length = inp.length;
        out = new address[](length + 1);
        for (uint256 i = 0; i < length;) {
            out[i] = inp[i];
            unchecked {
                i++;
            }
        }
        out[length] = element;
    }

    function appendHead(address[] memory inp, address element) internal pure returns (address[] memory out) {
        uint256 length = inp.length;
        out = new address[](length + 1);
        out[0] = element;
        for (uint256 i = 1; i <= length;) {
            out[i] = inp[i - 1];
            unchecked {
                i++;
            }
        }
    }

    /**
     * @dev This function assumes a and b each contains unidentical elements
     * @param a array of addresses a
     * @param b array of addresses b
     * @return out Concatenation of a and b containing unidentical elements
     */
    function merge(address[] memory a, address[] memory b) internal pure returns (address[] memory out) {
        unchecked {
            uint256 countUnidenticalB = 0;
            bool[] memory isUnidentical = new bool[](b.length);
            for (uint256 i = 0; i < b.length; ++i) {
                if (!contains(a, b[i])) {
                    countUnidenticalB++;
                    isUnidentical[i] = true;
                }
            }

            out = new address[](a.length + countUnidenticalB);
            for (uint256 i = 0; i < a.length; ++i) {
                out[i] = a[i];
            }
            uint256 id = a.length;
            for (uint256 i = 0; i < b.length; ++i) {
                if (isUnidentical[i]) {
                    out[id++] = b[i];
                }
            }
        }
    }

    // various version of contains
    function contains(address[] memory array, address element) internal pure returns (bool) {
        uint256 length = array.length;
        for (uint256 i = 0; i < length;) {
            if (array[i] == element) return true;
            unchecked {
                i++;
            }
        }
        return false;
    }

    function contains(bytes4[] memory array, bytes4 element) internal pure returns (bool) {
        uint256 length = array.length;
        for (uint256 i = 0; i < length;) {
            if (array[i] == element) return true;
            unchecked {
                i++;
            }
        }
        return false;
    }

    function create(address a) internal pure returns (address[] memory res) {
        res = new address[](1);
        res[0] = a;
    }

    function create(address a, address b) internal pure returns (address[] memory res) {
        res = new address[](2);
        res[0] = a;
        res[1] = b;
    }

    function create(address a, address b, address c) internal pure returns (address[] memory res) {
        res = new address[](3);
        res[0] = a;
        res[1] = b;
        res[2] = c;
    }

    function create(address a, address b, address c, address d) internal pure returns (address[] memory res) {
        res = new address[](4);
        res[0] = a;
        res[1] = b;
        res[2] = c;
        res[3] = d;
    }

    function create(address a, address b, address c, address d, address e)
        internal
        pure
        returns (address[] memory res)
    {
        res = new address[](5);
        res[0] = a;
        res[1] = b;
        res[2] = c;
        res[3] = d;
        res[4] = e;
    }

    function create(uint256 a) internal pure returns (uint256[] memory res) {
        res = new uint256[](1);
        res[0] = a;
    }

    function create(uint256 a, uint256 b) internal pure returns (uint256[] memory res) {
        res = new uint256[](2);
        res[0] = a;
        res[1] = b;
    }
}

lib/pendle-core-v2/contracts/core/libraries/BoringOwnableUpgradeableV2.sol

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

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

contract BoringOwnableUpgradeableData {
    address public owner;
    address public pendingOwner;
}

abstract contract BoringOwnableUpgradeableV2 is BoringOwnableUpgradeableData, Initializable {
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

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

    /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
    /// Can only be invoked by the current `owner`.
    /// @param newOwner Address of the new owner.
    /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
    /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect
    /// otherwise.
    function transferOwnership(address newOwner, bool direct, bool renounce) public onlyOwner {
        if (direct) {
            // Checks
            require(newOwner != address(0) || renounce, "Ownable: zero address");

            // Effects
            emit OwnershipTransferred(owner, newOwner);
            owner = newOwner;
            pendingOwner = address(0);
        } else {
            // Effects
            pendingOwner = newOwner;
        }
    }

    /// @notice Needs to be called by `pendingOwner` to claim ownership.
    function claimOwnership() public {
        address _pendingOwner = pendingOwner;

        // Checks
        require(msg.sender == _pendingOwner, "Ownable: caller != pending owner");

        // Effects
        emit OwnershipTransferred(owner, _pendingOwner);
        owner = _pendingOwner;
        pendingOwner = address(0);
    }

    /// @notice Only allows the `owner` to execute the function.
    modifier onlyOwner() {
        require(msg.sender == owner, "Ownable: caller is not the owner");
        _;
    }

    uint256[48] private __gap;
}

lib/pendle-core-v2/contracts/core/libraries/TokenHelper.sol

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

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

abstract contract TokenHelper {
    using SafeERC20 for IERC20;

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

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

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

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

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

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

    function _selfBalance(address token) internal view returns (uint256) {
        return _balanceOf(address(this), token);
    }

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

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

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

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

lib/pendle-core-v2/contracts/core/libraries/math/PMath.sol

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    function Uint152(uint256 x) internal pure returns (uint152) {
        require(x <= type(uint152).max);
        return uint152(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);
    }
}

lib/pendle-core-v2/contracts/interfaces/IMoneyMarket.sol

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

import {IPLoopPositionBox, BoxData} from "./IPLoopPositionBox.sol";

/// @notice What every money market call acts on. Built from `BoxData` with `createMarketCtx`.
struct MarketCtx {
    IPLoopPositionBox box;
    bytes32 mmPayload;
    address collateral;
    address debtAsset;
}

function createMarketCtx(IPLoopPositionBox box, BoxData memory bd) pure returns (MarketCtx memory) {
    return MarketCtx({box: box, mmPayload: bd.mmPayload, collateral: bd.spokePt, debtAsset: bd.spokeDebtToken});
}

interface IMoneyMarket {
    function initialize(MarketCtx memory ctx) external;

    function lend(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);

    function withdraw(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);

    function borrow(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);

    function repay(MarketCtx memory ctx, uint256 amount) external returns (uint256 actualAmount);

    function collateralBalance(MarketCtx memory ctx) external returns (uint256 balance);

    function debtBalance(MarketCtx memory ctx) external returns (uint256 balance);

    /// @notice Oracle price of 1 PT wei in debt token wei, in WAD.
    function oraclePtDebtRate(MarketCtx memory ctx) external view returns (uint256 rate);
}

lib/pendle-core-v2/contracts/interfaces/IPLoopPositionBox.sol

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

/// @dev `tokens` are ERC20 only; native value goes in `nativeAmount`. The other fields mirror `BoxApprovedCall`.
struct BoxCall {
    address[] tokens;
    uint256[] amounts;
    uint256 nativeAmount;
    address approve;
    address extRouter;
    bytes callData;
}

struct BoxData {
    uint32 hubChainId;
    uint32 spokeChainId;

    address hubPt;
    address hubDebtToken;
    address spokePt;
    address spokeDebtToken;

    /// @dev Beacon of the spoke money market adapter.
    address spokeMMBeacon;
    /// @dev Adapter-specific market id. See each `*MMPayloadLib`.
    bytes32 mmPayload;
}

interface IPLoopPositionBox {
    function MANAGER() external view returns (address);
    function OWNER() external view returns (address);
    function BOX_ID() external view returns (bytes32);
    function SPOKE_MONEY_MARKET() external view returns (address);

    function initialize(
        address owner,
        bytes32 boxId,
        address spokeMoneyMarket,
        address ptToApprove,
        address debtTokenToApprove
    ) external;

    function withdrawTo(address to, address token, uint256 amount) external;

    function approveAndCall(BoxCall memory call, address nativeRefund) external payable returns (bytes memory);

    function MORPHO() external view returns (address);

    /// @notice Manager only. Flash-borrows `assets` of `token` from Morpho and calls the manager with `data`
    ///         inside the loan. Morpho pulls the loan back after.
    function flashLoan(address token, uint256 assets, bytes calldata data) external;

    /// @notice Morpho Blue flash-loan callback. Relays `data` to the manager.
    function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
}

lib/pendle-core-v2/contracts/interfaces/IPLoopPositionBoxFactory.sol

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

import {IMoneyMarket} from "./IMoneyMarket.sol";
import {BoxData, IPLoopPositionBox} from "./IPLoopPositionBox.sol";

interface IPLoopPositionBoxFactory {
    event BoxDataRegistered(bytes32 indexed boxId, BoxData boxData);

    function boxData(bytes32 boxId) external view returns (BoxData memory);

    function computePositionBox(address owner, bytes32 boxId)
        external
        view
        returns (address box, bytes32 salt, bool deployed);

    /// @notice `computedAddr` is zero off the spoke chain.
    function computeMoneyMarket(address owner, bytes32 boxId)
        external
        view
        returns (address computedAddr, bytes32 salt, bool deployed);

    /// @notice Deploys whichever is missing. `mm` is zero off the spoke chain.
    function deployPositionBoxAndMoneyMarket(address owner, bytes32 boxId)
        external
        returns (IPLoopPositionBox box, IMoneyMarket mm, BoxData memory boxData);

    function BEACON_PROXY_CODE_CONTRACT() external view returns (address);

    function POSITION_BOX_BEACON() external view returns (address);

    function POSITION_BOX_CODE_HASH() external view returns (bytes32);

    // ========== Admin functions ==========

    function registerBoxData(BoxData calldata boxData) external returns (bytes32 boxId);
}

lib/pendle-core-v2/contracts/interfaces/IPPTLooper.sol

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

import {IPLoopPositionBox} from "./IPLoopPositionBox.sol";
import {IPLoopPositionBoxFactory} from "./IPLoopPositionBoxFactory.sol";
import {IPPostPtLoopStateChecker} from "../interfaces/IPPostPtLoopStateChecker.sol";

/// @notice The owner approves a request (EIP-712, in the looper's domain). The executor builds a message for
///         each iteration, and the checker signs the whole `execute`. The box is `(ms.owner, req.header.boxId)`.
interface IPPTLooperEIP712Types {
    /// @notice What the checker signs for `execute`. `calls` is hashed as an EIP-712 `bytes[]`.
    struct Execution {
        /// @notice The calls that `execute` runs in order, as delegatecalls into the looper.
        bytes[] calls;
        /// @notice The last timestamp at which `execute` can run.
        uint256 deadline;
    }

    /// @notice A request runs iterations until it is terminated or expires. A box can have more than one
    ///         live request. `offchainMetadataHash` is `keccak256(offchainMetadata)`; the contract does not read it.
    struct RequestHeader {
        bytes32 boxId;
        uint256 expiry;
        uint256 swapBridgeSlippage;
        bytes32 offchainMetadataHash;
    }

    struct BoxApprovedCall {
        address extRouter;
        address approve;
        bytes callData;
    }

    /// @notice Cross-chain only. `maxAmount`: the max amount to bridge. `nativeFee`: the native fee of the call.
    struct BridgeData {
        BoxApprovedCall call;
        uint256 maxAmount;
        uint256 nativeFee;
    }

    struct IncreasePositionRequest {
        RequestHeader header;
        /// @notice The token that an iteration with `swapInitToken` swaps.
        address initTokenIn;
        /// @notice Min `netOut / netIn` (WAD) of an `initTokenIn` to PT swap. 0: no check.
        uint256 initMinToPtSwapRate;
        /// @notice Min `netOut / netIn` (WAD) of a debt token to PT swap. 0: no check.
        uint256 minDebtToPtSwapRate;
        /// @notice Max `debt / (collateral * oracle rate)` (WAD) after the iteration.
        uint256 postBorrowMaxLTV;
        /// @notice true: the swap mints PT + YT 1:1, and the YT goes to the owner.
        bool isZeroPriceImpact;
    }

    struct IncreasePositionMessage {
        address owner;
        // Hub only.
        /// @notice true: swap `req.initTokenIn` to PT. false: swap the debt token to PT. The fee is in the
        ///         token that is swapped.
        bool swapInitToken;
        /// @notice `extRouter == address(0)`: no swap.
        BoxApprovedCall swap;
        /// @notice Min `netOut / netIn` (WAD) of the swap; the higher of this and the request's rate applies.
        uint256 minSwapRate;
        uint256 fee;

        // Cross-chain only: the hub bridges PT to the spoke; the spoke bridges debt back to the hub.
        BridgeData bridge;
        // Spoke only: lend, then borrow.
        uint256 amountDebtBorrowed;
        /// @notice Same-chain only. Debt token that the box flash-borrows from Morpho and pays back out of the
        ///         borrowed debt. 0: no flash loan.
        uint256 flashAmount;

        bytes postStateCheckData;
    }

    struct DecreasePositionRequest {
        RequestHeader header;
        /// @notice Min `netOut / netIn` (WAD) of a PT to debt token swap. 0: no check.
        uint256 minPtToDebtSwapRate;
        /// @notice Max `debt / (collateral * oracle rate)` (WAD) after the iteration.
        uint256 postWithdrawMaxLTV;
        /// @notice Hub only. true: the router redeems min(PT, YT) of the box 1:1 to the debt token. The rest
        ///         of the PT stays in the box. The owner sends the YT to the box first.
        bool redeemWithPY;
    }

    struct DecreasePositionMessage {
        address owner;
        // Hub only: swap PT to the debt token.
        /// @notice `extRouter == address(0)`: no swap. See `DecreasePositionRequest.redeemWithPY`.
        BoxApprovedCall swap;
        /// @notice Min `netOut / netIn` (WAD) of the swap; the higher of this and the request's rate applies.
        uint256 minSwapRate;
        // Cross-chain only: the hub bridges debt to the spoke; the spoke bridges PT back to the hub.
        BridgeData bridge;
        // Spoke only: repay, then withdraw.
        uint256 amountPtWithdrawn;
        /// @notice Hub only. In the debt token, out of the swap's output.
        uint256 fee;
        /// @notice Same-chain only. Debt token that the box flash-borrows from Morpho and pays back out of the
        ///         swap's output. 0: no flash loan.
        uint256 flashAmount;

        bytes postStateCheckData;
    }

    /// @notice Swaps the box's whole debt token balance on this chain to the token out, then sends it to the
    ///         owner, or bridges it when the destination is the other chain.
    struct SwapBridgeWithdrawAllRequest {
        RequestHeader header;
        /// @notice true: the destination is the spoke. false: the hub.
        bool receiveOnSpoke;
        /// @notice The token out on the hub, when the iteration runs on the hub.
        address hubTokenOut;
        /// @notice The token out on the destination chain.
        address dstTokenOut;
        /// @notice Min box balance of the token out after the swap.
        uint256 minTokenWithdrawn;
    }

    struct SwapBridgeWithdrawAllMessage {
        address owner;
        BoxApprovedCall swap;
        /// @notice Min `netOut / netIn` (WAD) of the swap. 0: no check.
        uint256 minSwapRate;
        BridgeData bridge;

        bytes postStateCheckData;
    }
}

interface IPPTLooper is IPPTLooperEIP712Types {
    /// @notice `DEFAULT`: cannot run. `APPROVED` (`approveRequest`): can run. `TERMINATED` (`terminateRequest`,
    ///         from any status): cannot run again. An iteration does not change the status.
    enum RequestStatus {
        DEFAULT,
        APPROVED,
        TERMINATED
    }

    event RequestApproved(address indexed owner, bytes32 requestHash);

    event RequestTerminated(address indexed owner, bytes32 requestHash);

    event SetExecutor(address executor);

    event SetChecker(address checker);

    event TokenSwapped(
        IPLoopPositionBox indexed box,
        address indexed tokenIn,
        uint256 netIn,
        address indexed tokenOut,
        uint256 netSwappedOut
    );

    event PYRedeemed(
        IPLoopPositionBox indexed box,
        address indexed pt,
        uint256 netPyIn,
        address indexed tokenOut,
        uint256 netSwappedOut
    );

    event TokenBridged(IPLoopPositionBox indexed box, address indexed token, uint256 amount);

    /// @notice The `box` flash-borrowed `amount` of `token` for this iteration, repaid at the end.
    ///         `preDebtBalance` and `preInBalance` (when swapping the debt token) count the loan,
    ///         and so do the swap input and money market amounts. `postDebtBalance` does not include it.
    event FlashLoaned(IPLoopPositionBox indexed box, address indexed token, uint256 amount);

    /// @notice The money market adapter emits no events.
    event MoneyMarketLentThenBorrowed(IPLoopPositionBox indexed box, uint256 ptLent, uint256 debtBorrowed);

    /// @notice The money market adapter emits no events.
    event MoneyMarketRepaidThenWithdrawn(IPLoopPositionBox indexed box, uint256 debtRepaid, uint256 ptWithdrawn);

    event PositionIncreased(
        address indexed owner,
        bytes32 indexed boxId,
        bytes32 requestHash,
        /// @notice Hub only. The box's pre-fee balance of the token swapped (`initTokenIn` or the debt token).
        uint256 preInBalance,
        uint256 netPtToMM,
        /// @notice Spoke only.
        uint256 postDebtBalance
    );

    event PositionDecreased(
        address indexed owner,
        bytes32 indexed boxId,
        bytes32 requestHash,
        /// @notice Spoke only.
        uint256 preDebtBalance,
        uint256 netPtToSwap,
        /// @notice Hub only. After the fee.
        uint256 postDebtBalance
    );

    event Withdrawn(
        address indexed owner, bytes32 indexed boxId, bytes32 requestHash, address tokenOut, uint256 netOut
    );

    // ========== Getters ==========

    function POSITION_BOX_FACTORY() external view returns (IPLoopPositionBoxFactory);

    function POST_LOOP_STATE_CHECKER() external view returns (IPPostPtLoopStateChecker);

    function executor() external view returns (address);

    function checker() external view returns (address);

    function requestStatus(address owner, bytes32 requestHash) external view returns (RequestStatus);

    // ========== Actions ==========

    // Each action runs one iteration, executor only, inside `execute`. The request must be approved and not expired.

    function increaseLoopPosition(IncreasePositionMessage memory ms, IncreasePositionRequest memory req) external;

    function decreaseLoopPosition(DecreasePositionMessage memory ms, DecreasePositionRequest memory req) external;

    function swapBridgeWithdrawAll(SwapBridgeWithdrawAllMessage memory ms, SwapBridgeWithdrawAllRequest memory req)
        external;

    /// @notice Approves a `DEFAULT` request. `requestHash` is the request's EIP-712 digest. The owner calls it,
    ///         or the executor calls it inside `execute` with the owner's signature of `requestHash`.
    function approveRequest(address owner, bytes32 requestHash, bytes memory ownerSig) external;

    /// @notice The request cannot run again. The owner calls it, or the executor inside `execute`.
    function terminateRequest(address owner, bytes32 requestHash) external;

    /// @notice Executor only, inside `execute`. Needs no request: funds go only to the owner or into the
    ///         owner's position. In order: `repayDebt` repays as much debt as the box's
    ///         debt token balance covers, `lendPt` lends its whole PT balance, then each token in `tokensToOwner`
    ///         goes to the owner in full.
    ///         `repayDebt` and `lendPt` need the spoke chain.
    function settleBox(address owner, bytes32 boxId, bool repayDebt, bool lendPt, address[] calldata tokensToOwner)
        external;

    /// @notice The executor's only entry point. Runs `execution.calls` in order as delegatecalls into this
    ///         contract; any failure reverts all. With `tx.origin == 0` (an `eth_call` with no `from`) it is a
    ///         simulation: no checker signature or deadline.
    /// @param execution the calls and the deadline.
    /// @param checkerSig the checker's EIP-712 signature over `execution`.
    /// @return results the return data of each call.
    function execute(Execution memory execution, bytes calldata checkerSig) external returns (bytes[] memory results);

    // ========== Admin functions ==========

    function setExecutor(address executor) external;

    function setChecker(address checker) external;
}

lib/pendle-core-v2/contracts/interfaces/IPPostPtLoopStateChecker.sol

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

import {MarketCtx} from "./IMoneyMarket.sol";

interface IPPostPtLoopStateChecker {
    function check(MarketCtx memory ctx, bytes calldata data) external;
}

lib/pendle-core-v2/contracts/interfaces/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);

    function VERSION() external pure returns (uint256);

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

lib/pendle-core-v2/contracts/interfaces/IWETH.sol

// SPDX-License-Identifier: GPL-3.0-or-later
/*
 * MIT License
 * ===========
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 */
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

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

    function deposit() external payable;

    function withdraw(uint256 wad) external;
}

lib/pendle-core-v2/contracts/pt-looping/PTLooperBase.sol

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

import {BoringOwnableUpgradeableV2} from "../core/libraries/BoringOwnableUpgradeableV2.sol";
import {TokenHelper} from "../core/libraries/TokenHelper.sol";
import {IMoneyMarket, MarketCtx, createMarketCtx} from "../interfaces/IMoneyMarket.sol";
import {BoxData, IPLoopPositionBox} from "../interfaces/IPLoopPositionBox.sol";
import {IPLoopPositionBoxFactory} from "../interfaces/IPLoopPositionBoxFactory.sol";
import {IPPTLooper} from "../interfaces/IPPTLooper.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import {PTLooperEIP712TypesEncodeDataLib} from "./PTLooperEIP712TypesEncodeDataLib.sol";

abstract contract PTLooperBase is IPPTLooper, EIP712Upgradeable, BoringOwnableUpgradeableV2, TokenHelper {
    using PTLooperEIP712TypesEncodeDataLib for *;

    address public immutable TREASURY;
    IPLoopPositionBoxFactory public immutable POSITION_BOX_FACTORY;

    /// @dev The implementation. `execute` delegatecalls it directly, skipping the proxy.
    address private immutable _SELF = address(this);

    /// @dev True while `execute` runs the calls.
    bool private transient _executing;

    /// @dev Hash of the one `flashIncrease` / `flashDecrease` call that the box may make inside a flash loan.
    bytes32 internal transient _flashCallHash;

    address public executor;
    address public checker;

    /// @dev Unused. Kept for the proxy storage layout.
    mapping(address owner => mapping(bytes32 requestHash => uint256 nonce)) private __deprecatedProposerNonce;
    /// @dev Unused. Kept for the proxy storage layout. The value type is a placeholder.
    mapping(address owner => mapping(bytes32 boxId => bytes32)) private __deprecatedUserRequest;
    mapping(address owner => mapping(bytes32 requestHash => RequestStatus)) public requestStatus;

    constructor(address treasury_, address positionBoxFactory_) {
        TREASURY = treasury_;
        POSITION_BOX_FACTORY = IPLoopPositionBoxFactory(positionBoxFactory_);
    }

    // ========== Execute ==========
    //
    // Each call is a delegatecall into the implementation, so `msg.sender` stays the executor.
    // `onlyExecutor` passes only in `execute`; a router or box callback reverts, as its `msg.sender` is not
    // the executor.

    /// @dev A transaction never has a zero `tx.origin`, so the checks are skipped only in a simulation.
    function execute(Execution memory execution, bytes calldata checkerSig) external returns (bytes[] memory results) {
        if (tx.origin != address(0)) {
            require(msg.sender == executor, "PTLooper: unauthorized");
            require(executor.code.length == 0, "PTLooper: non-EOA executor");
            require(checker.code.length == 0, "PTLooper: non-EOA checker");
            require(execution.deadline >= block.timestamp, "PTLooper: execution expired"); // forge-lint: disable-line(block-timestamp)
            require(
                SignatureChecker.isValidSignatureNow(checker, _hashExecution(execution), checkerSig),
                "PTLooper: invalid signature"
            );
        }

        bytes[] memory calls = execution.calls;
        results = new bytes[](calls.length);

        _executing = true;
        for (uint256 i = 0; i < calls.length; ++i) {
            results[i] = Address.functionDelegateCall(_SELF, calls[i]);
        }
        _executing = false;
    }

    /// @dev A simulation (`tx.origin == 0`) passes with any caller.
    function _checkExecutor() internal view {
        require(_executing && (msg.sender == executor || tx.origin == address(0)), "PTLooper: unauthorized");
    }

    modifier onlyExecutor() {
        _checkExecutor();
        _;
    }

    modifier onlyExecutorOrBoxOwner(address boxOwner) {
        if (msg.sender != boxOwner) _checkExecutor();
        _;
    }

    function setExecutor(address executor_) external onlyOwner {
        executor = executor_;
        emit SetExecutor(executor_);
    }

    function setChecker(address checker_) external onlyOwner {
        checker = checker_;
        emit SetChecker(checker_);
    }

    /// @dev Constants, so `_hashTypedDataV4` does not read the name and version from storage.
    function _EIP712Name() internal pure override returns (string memory) {
        return "Pendle PT Looper";
    }

    function _EIP712Version() internal pure override returns (string memory) {
        return "1";
    }

    function _hashExecution(Execution memory execution) internal view returns (bytes32) {
        return _hashTypedDataV4(execution.encodeData());
    }

    function _hashTyped(IncreasePositionRequest memory req) internal view returns (bytes32) {
        return _hashTypedDataV4(req.encodeData());
    }

    function _hashTyped(DecreasePositionRequest memory req) internal view returns (bytes32) {
        return _hashTypedDataV4(req.encodeData());
    }

    function _hashTyped(SwapBridgeWithdrawAllRequest memory req) internal view returns (bytes32) {
        return _hashTypedDataV4(req.encodeData());
    }

    /// @dev The context of an iteration. `spokeMM` is zero off the box's spoke chain. `requestHash` is for events.
    struct Session {
        IPLoopPositionBox box;
        IMoneyMarket spokeMM;
        BoxData bd;
        MarketCtx marketCtx;
        bytes32 requestHash;
    }

    function approveRequest(address owner, bytes32 requestHash, bytes memory ownerSig)
        external
        onlyExecutorOrBoxOwner(owner)
    {
        require(
            msg.sender == owner || SignatureChecker.isValidSignatureNow(owner, requestHash, ownerSig),
            "PTLooper: invalid owner signature"
        );
        require(requestStatus[owner][requestHash] == RequestStatus.DEFAULT, "PTLooper: invalid request status");
        requestStatus[owner][requestHash] = RequestStatus.APPROVED;
        emit RequestApproved(owner, requestHash);
    }

    /// @dev Lets the owner stop a request without the executor. The executor uses it, e.g., after a one-shot request.
    function terminateRequest(address owner, bytes32 requestHash) external onlyExecutorOrBoxOwner(owner) {
        requestStatus[owner][requestHash] = RequestStatus.TERMINATED;
        emit RequestTerminated(owner, requestHash);
    }

    /// @dev Checks the request is approved and not expired. The caller checks the executor.
    function _authorizedSession(address owner, RequestHeader memory header, bytes32 requestHash)
        internal
        returns (Session memory s)
    {
        require(header.expiry > block.timestamp, "PTLooper: request expired"); // forge-lint: disable-line(block-timestamp)
        require(requestStatus[owner][requestHash] == RequestStatus.APPROVED, "PTLooper: invalid request status");

        return _session(owner, header.boxId, requestHash);
    }

    /// @dev No auth; the caller does it.
    function _session(address owner, bytes32 boxId, bytes32 requestHash) private returns (Session memory s) {
        (s.box, s.spokeMM, s.bd) = POSITION_BOX_FACTORY.deployPositionBoxAndMoneyMarket(owner, boxId);
        s.marketCtx = createMarketCtx(s.box, s.bd);
        s.requestHash = requestHash;
    }
}

lib/pendle-core-v2/contracts/pt-looping/PTLooperEIP712TypesEncodeDataLib.sol

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

/* GENERATED FILE. DO NOT EDIT DIRECTLY.
FOUNDRY_PROFILE=v2-script forge script script/GenEIP712.sol -- './contracts/interfaces/IPPTLooper.sol' 'IPPTLooperEIP712Types' '[]' './contracts/pt-looping/PTLooperEIP712TypesEncodeDataLib.sol'
*/

import {IPPTLooperEIP712Types} from "./../interfaces/IPPTLooper.sol";

/// @notice Generate EIP712 `encodeData` function for types in IPPTLooperEIP712Types based on specification:
/// https://eips.ethereum.org/EIPS/eip-712#definition-of-encodedata
/// @dev tempReplaceMem for typeHash is ALWAYS written after the other replacements, because of out-of-region memory write.
// forgefmt: disable-next-item
library PTLooperEIP712TypesEncodeDataLib {
    // IPPTLooper.sol > IPPTLooperEIP712Types > Execution
    function encodeData(IPPTLooperEIP712Types.Execution memory data) internal pure
        tempReplaceMem(_mPos(data), 0, encodeData(data.calls))
        /* TypeHash calculation: keccak256(
            "Execution(bytes[] calls,uint256 deadline)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x2731bab67703f25265d364e0e113c4017ffa557ce8afa5889af81fb8de0dff83)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 96) }
    }
    
    function _mPos(IPPTLooperEIP712Types.Execution memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > RequestHeader
    function encodeData(IPPTLooperEIP712Types.RequestHeader memory data) internal pure
        /* TypeHash calculation: keccak256(
            "RequestHeader(bytes32 boxId,uint256 expiry,uint256 swapBridgeSlippage,bytes32 offchainMetadataHash)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x821bd07beb0c9815c324abec6fdf02735804d21c9aa9d963dea50c2a5d099e59)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 160) }
    }
    
    function _mPos(IPPTLooperEIP712Types.RequestHeader memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > BoxApprovedCall
    function encodeData(IPPTLooperEIP712Types.BoxApprovedCall memory data) internal pure
        tempReplaceMem(_mPos(data), 64, encodeData(data.callData))
        /* TypeHash calculation: keccak256(
            "BoxApprovedCall(address extRouter,address approve,bytes callData)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0xd3355b017a4df5ab14bfe30be8fc74cf288d6cbdd53b7fb9a45cb406e14cb425)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 128) }
    }
    
    function _mPos(IPPTLooperEIP712Types.BoxApprovedCall memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > BridgeData
    function encodeData(IPPTLooperEIP712Types.BridgeData memory data) internal pure
        tempReplaceMem(_mPos(data), 0, encodeData(data.call))
        /* TypeHash calculation: keccak256(
            "BridgeData(BoxApprovedCall call,uint256 maxAmount,uint256 nativeFee)" 
            "BoxApprovedCall(address extRouter,address approve,bytes callData)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x2e509eca09b391e74bb50ce10f43a13d6dfd1390e626fcfc40c60b1d7369a4b0)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 128) }
    }
    
    function _mPos(IPPTLooperEIP712Types.BridgeData memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > IncreasePositionRequest
    function encodeData(IPPTLooperEIP712Types.IncreasePositionRequest memory data) internal pure
        tempReplaceMem(_mPos(data), 0, encodeData(data.header))
        /* TypeHash calculation: keccak256(
            "IncreasePositionRequest(RequestHeader header,address initTokenIn,uint256 initMinToPtSwapRate,uint256 minDebtToPtSwapRate,uint256 postBorrowMaxLTV,bool isZeroPriceImpact)" 
            "RequestHeader(bytes32 boxId,uint256 expiry,uint256 swapBridgeSlippage,bytes32 offchainMetadataHash)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x8fe1153584d333f5ea73b33aa49631061934154d52d99b5a71eb6fb7b1083e4a)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 224) }
    }
    
    function _mPos(IPPTLooperEIP712Types.IncreasePositionRequest memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > IncreasePositionMessage
    function encodeData(IPPTLooperEIP712Types.IncreasePositionMessage memory data) internal pure
        tempReplaceMem(_mPos(data), 64, encodeData(data.swap))
        tempReplaceMem(_mPos(data), 160, encodeData(data.bridge))
        tempReplaceMem(_mPos(data), 256, encodeData(data.postStateCheckData))
        /* TypeHash calculation: keccak256(
            "IncreasePositionMessage(address owner,bool swapInitToken,BoxApprovedCall swap,uint256 minSwapRate,uint256 fee,BridgeData bridge,uint256 amountDebtBorrowed,uint256 flashAmount,bytes postStateCheckData)" 
            "BoxApprovedCall(address extRouter,address approve,bytes callData)" 
            "BridgeData(BoxApprovedCall call,uint256 maxAmount,uint256 nativeFee)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x9f254442c96b08d2176fd44748fb9ed910a3d39aaf389b88d8a10506e22b9965)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 320) }
    }
    
    function _mPos(IPPTLooperEIP712Types.IncreasePositionMessage memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > DecreasePositionRequest
    function encodeData(IPPTLooperEIP712Types.DecreasePositionRequest memory data) internal pure
        tempReplaceMem(_mPos(data), 0, encodeData(data.header))
        /* TypeHash calculation: keccak256(
            "DecreasePositionRequest(RequestHeader header,uint256 minPtToDebtSwapRate,uint256 postWithdrawMaxLTV,bool redeemWithPY)" 
            "RequestHeader(bytes32 boxId,uint256 expiry,uint256 swapBridgeSlippage,bytes32 offchainMetadataHash)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x61b256fba1c5d9e3e04d71b4bc3604b30d83b34c5f626ef62479b8caac40282c)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 160) }
    }
    
    function _mPos(IPPTLooperEIP712Types.DecreasePositionRequest memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > DecreasePositionMessage
    function encodeData(IPPTLooperEIP712Types.DecreasePositionMessage memory data) internal pure
        tempReplaceMem(_mPos(data), 32, encodeData(data.swap))
        tempReplaceMem(_mPos(data), 96, encodeData(data.bridge))
        tempReplaceMem(_mPos(data), 224, encodeData(data.postStateCheckData))
        /* TypeHash calculation: keccak256(
            "DecreasePositionMessage(address owner,BoxApprovedCall swap,uint256 minSwapRate,BridgeData bridge,uint256 amountPtWithdrawn,uint256 fee,uint256 flashAmount,bytes postStateCheckData)" 
            "BoxApprovedCall(address extRouter,address approve,bytes callData)" 
            "BridgeData(BoxApprovedCall call,uint256 maxAmount,uint256 nativeFee)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0xe1084c1d7fa444be31f398b89301944c5ba04a1f5296534519de59ab6738eea5)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 288) }
    }
    
    function _mPos(IPPTLooperEIP712Types.DecreasePositionMessage memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > SwapBridgeWithdrawAllRequest
    function encodeData(IPPTLooperEIP712Types.SwapBridgeWithdrawAllRequest memory data) internal pure
        tempReplaceMem(_mPos(data), 0, encodeData(data.header))
        /* TypeHash calculation: keccak256(
            "SwapBridgeWithdrawAllRequest(RequestHeader header,bool receiveOnSpoke,address hubTokenOut,address dstTokenOut,uint256 minTokenWithdrawn)" 
            "RequestHeader(bytes32 boxId,uint256 expiry,uint256 swapBridgeSlippage,bytes32 offchainMetadataHash)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x97fe4994ae4134ffa7d8bebba2ff21ca5ab9b59939502108614e0634e320cabf)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 192) }
    }
    
    function _mPos(IPPTLooperEIP712Types.SwapBridgeWithdrawAllRequest memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    // IPPTLooper.sol > IPPTLooperEIP712Types > SwapBridgeWithdrawAllMessage
    function encodeData(IPPTLooperEIP712Types.SwapBridgeWithdrawAllMessage memory data) internal pure
        tempReplaceMem(_mPos(data), 32, encodeData(data.swap))
        tempReplaceMem(_mPos(data), 96, encodeData(data.bridge))
        tempReplaceMem(_mPos(data), 128, encodeData(data.postStateCheckData))
        /* TypeHash calculation: keccak256(
            "SwapBridgeWithdrawAllMessage(address owner,BoxApprovedCall swap,uint256 minSwapRate,BridgeData bridge,bytes postStateCheckData)" 
            "BoxApprovedCall(address extRouter,address approve,bytes callData)" 
            "BridgeData(BoxApprovedCall call,uint256 maxAmount,uint256 nativeFee)" 
        ); */
        tempReplaceMem(_mPos(data), -32, 0x7cc1b15ccedaf263db15ec8f89f9160e8f4ba28e2c396709482a83c6fa6f16af)
        returns (bytes32 res)
    {
        assembly { res := keccak256(sub(data, 32), 192) }
    }
    
    function _mPos(IPPTLooperEIP712Types.SwapBridgeWithdrawAllMessage memory data) private pure returns (bytes32 res) {
        assembly { res := data }
    }
    
    function encodeData(bytes memory data) internal pure returns (bytes32 res) {
        assembly { res := keccak256(add(data, 32), mload(data)) }
    }
    
    function encodeData(bytes[] memory data) internal pure returns (bytes32 res) {
        uint256 n = data.length;
        bytes32[] memory encodedData = new bytes32[](n);
        for (uint256 i = 0; i < n; ++i) encodedData[i] = encodeData(data[i]);
        assembly { res := keccak256(add(encodedData, 32), shl(5, n)) }
    }
    
    // ========== Helper functions ==========
    
    modifier tempReplaceMem(bytes32 mPos, int256 ofs, bytes32 val) {
        bytes32 temp;
        assembly { temp := mload(add(mPos, ofs)) mstore(add(mPos, ofs), val) }
        _;
        assembly { mstore(add(mPos, ofs), temp) }
    }
}

node_modules/@openzeppelin/contracts-upgradeable/interfaces/IERC5267Upgradeable.sol

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

pragma solidity ^0.8.0;

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

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

node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.2;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

node_modules/@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol

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

pragma solidity ^0.8.0;

import "../StringsUpgradeable.sol";

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

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

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

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

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

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

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

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

        return (signer, RecoverError.NoError);
    }

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

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

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

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

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

node_modules/@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol

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

pragma solidity ^0.8.8;

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

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

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

    string private _name;
    string private _version;

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

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

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

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

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

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

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

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

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

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

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

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

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

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

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts-upgradeable/utils/math/SignedMathUpgradeable.sol

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

pragma solidity ^0.8.0;

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

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

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

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

node_modules/@openzeppelin/contracts/interfaces/IERC1271.sol

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

pragma solidity ^0.8.0;

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

node_modules/@openzeppelin/contracts/token/ERC20/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);
}

node_modules/@openzeppelin/contracts/token/ERC20/extensions/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);
}

node_modules/@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

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

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

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

node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

node_modules/@openzeppelin/contracts/utils/Strings.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.0;

import "../Strings.sol";

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

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

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

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

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

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

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

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

        return (signer, RecoverError.NoError);
    }

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

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

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

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

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

node_modules/@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol

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

pragma solidity ^0.8.0;

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

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

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

node_modules/@openzeppelin/contracts/utils/math/Math.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

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

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

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

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

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

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

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

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

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

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

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

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

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

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/utils/math/SignedMath.sol

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

pragma solidity ^0.8.0;

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

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

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

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@pendle/core-v2/=lib/pendle-core-v2/",
    "@pendle/sy/=lib/pendle-sy/",
    "forge-std/=lib/forge-std/",
    "vendor/=vendor/",
    "vendor-locked/=vendor-locked/",
    "node_modules/@chainlink/contracts/:@openzeppelin/contracts/=node_modules/@chainlink/contracts/node_modules/@openzeppelin/contracts/",
    "@chainlink/=node_modules/@chainlink/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@pendle/=node_modules/@pendle/",
    "hardhat/=node_modules/hardhat/",
    "pendle-core-v2/=lib/pendle-core-v2/",
    "pendle-sy/=lib/pendle-sy/contracts/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.