FRAX Price: $0.82 (-19.04%)

Contract

0x83f202c4ED795609EFbd5ffAA4ecC92797e3B248

Overview

FRAX Balance | FXTL Balance

0 FRAX | 715 FXTL

FRAX Value

$0.00

Token Holdings

More Info

Private Name Tags

Multichain Info

No addresses found
Age:7D
Reset Filter

Transaction Hash
Block
From
To

There are no matching entries

4 Internal Transactions and 4 Token Transfers found.

Latest 4 internal transactions

Advanced mode:
Parent Transaction Hash Block From To
45895512024-05-17 23:50:13617 days ago1715989813
0x83f202c4...797e3B248
 Contract Creation0 FRAX
45756532024-05-17 16:06:57618 days ago1715962017
0x83f202c4...797e3B248
 Contract Creation0 FRAX
45752942024-05-17 15:54:59618 days ago1715961299
0x83f202c4...797e3B248
 Contract Creation0 FRAX
45752942024-05-17 15:54:59618 days ago1715961299
0x83f202c4...797e3B248
 Contract Creation0 FRAX

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
BAMMFactory

Compiler Version
v0.8.25+commit.b61c2a91

Optimization Enabled:
Yes with 1000 runs

Other Settings:
paris EvmVersion
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import { BAMM } from "../BAMM.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SSTORE2 } from "@rari-capital/solmate/src/utils/SSTORE2.sol";
import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol";
import { Ownable, Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

import { IFraxswapFactory } from "dev-fraxswap/src/contracts/core/interfaces/IFraxswapFactory.sol";
import { IFraxswapPair } from "dev-fraxswap/src/contracts/core/interfaces/IFraxswapPair.sol";

contract BAMMFactory is Ownable2Step, Initializable {
    IFraxswapFactory public immutable iFraxswapFactory;
    address public immutable routerMultihop;
    address public immutable fraxswapOracle;
    address public immutable variableInterestRate;

    /// @dev state updated on createBamm()
    mapping(address bamm => bool exists) public isBamm;
    mapping(address pair => address bamm) public pairToBamm;
    address[] public bamms;

    /// @dev storage for contract exceeding the size limit by splitting the creation code into two
    address private contractAddress1;
    address private contractAddress2;

    address public feeTo;

    constructor(
        address _fraxswapFactory,
        address _routerMultihop,
        address _fraxswapOracle,
        address _variableInterestRate,
        address _feeTo
    ) Ownable(msg.sender) {
        iFraxswapFactory = IFraxswapFactory(_fraxswapFactory);
        routerMultihop = _routerMultihop;
        fraxswapOracle = _fraxswapOracle;
        variableInterestRate = _variableInterestRate;
        feeTo = _feeTo;
    }

    /// @notice work-around to set creation code which exceeds the contract size limit
    function setCreationCode(bytes calldata _creationCode) external onlyOwner initializer {
        bytes memory firstHalf = BytesLib.slice(_creationCode, 0, 20_500);
        contractAddress1 = SSTORE2.write(firstHalf);
        if (_creationCode.length > 20_500) {
            bytes memory secondHalf = BytesLib.slice(_creationCode, 20_500, _creationCode.length - 20_500);
            contractAddress2 = SSTORE2.write(secondHalf);
        }
    }

    /// @notice Semantic version of this contract
    /// @return _major The major version
    /// @return _minor The minor version
    /// @return _patch The patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        return (0, 4, 1);
    }

    /// @notice Create a BAMM for a given FraxswapPair
    /// @notice Incompatible for fee-on-transfer tokens
    /// @param _pair Address of the Fraxswap-created token pair
    /// @return bamm Address of the newly-created BAMM contract
    function createBamm(address _pair) public returns (address bamm) {
        // require pair to have been created from factory
        address token0 = IFraxswapPair(_pair).token0();
        address token1 = IFraxswapPair(_pair).token1();
        address getPair = iFraxswapFactory.getPair(token0, token1);
        if (_pair != getPair) revert PairNotFromFraxswapFactory();

        // revert if bamm exists for pair
        if (pairToBamm[_pair] != address(0)) revert BammAlreadyCreated();

        uint256 id = bamms.length;

        // Get init code from creation code
        bytes memory creationCode = BytesLib.concat(SSTORE2.read(contractAddress1), SSTORE2.read(contractAddress2));
        bytes memory constArgs = abi.encode(
            id,
            _pair,
            routerMultihop,
            fraxswapOracle,
            variableInterestRate,
            30 * 2 * 158_247_046
        );
        bytes memory initCode = abi.encodePacked(creationCode, abi.encode(constArgs));

        // Get Salt
        bytes32 salt = keccak256(abi.encode(id, _pair, routerMultihop, fraxswapOracle));

        /// @solidity memory-safe-assembly
        uint256 size;
        assembly {
            bamm := create2(0, add(initCode, 32), mload(initCode), salt)
            size := extcodesize(bamm)
        }
        if (bamm == address(0)) revert Create2Failed();
        if (size == 0) revert Create2Failed();

        // Update state
        isBamm[bamm] = true;
        pairToBamm[_pair] = bamm;
        bamms.push(bamm);

        emit BammCreated(_pair, bamm);
    }

    function bammsArray() external view returns (address[] memory) {
        return bamms;
    }

    function bammsLength() external view returns (uint256) {
        return bamms.length;
    }

    function setFeeTo(address _feeTo) external onlyOwner {
        feeTo = _feeTo;
    }

    event BammCreated(address pair, address bamm);

    error Create2Failed();
    error BammAlreadyCreated();
    error PairNotFromFraxswapFactory();
}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.19;

// ====================================================================
// |     ______                   _______                             |
// |    / _____________ __  __   / ____(_____  ____ _____  ________   |
// |   / /_  / ___/ __ `| |/_/  / /_  / / __ \/ __ `/ __ \/ ___/ _ \  |
// |  / __/ / /  / /_/ _>  <   / __/ / / / / / /_/ / / / / /__/  __/  |
// | /_/   /_/   \__,_/_/|_|  /_/   /_/_/ /_/\__,_/_/ /_/\___/\___/   |
// |                                                                  |
// ====================================================================
// =============================== BAMM ===============================
// ====================================================================
/*
 ** BAMM (Borrow AMM)
 ** - The BAMM wraps Uniswap/Fraxswap like LP tokens (#token0 * #token1 = K), giving out an ERC-20 wrapper token in return
 ** - Users have a personal vault where they can add / remove token0 and token1.
 ** - Users can rent the LP constituent token0s and token1s, the liquidity from which will be removed and stored in the users vault.
 ** - Rented LP constituent token0s and token1s are accounted as SQRT(#token0 * #token1)
 ** - The user can remove tokens from their personal vault as long as the SQRT(#token0 * #token1) is more than the rented value
 ** - Borrowers pay an interest rate based on the utility factor
 ** - Borrowers can only be liquidated due to interest rate payments, not due to price movements.
 ** - No price oracle needed!
 */

/*
   -----------------------------------------------------------
   -------------------- EXAMPLE SCENARIOS --------------------
   -----------------------------------------------------------

   Assume Fraxswap FRAX/FXS LP @ 0x03B59Bd1c8B9F6C265bA0c3421923B93f15036Fa.
   token0 = FXS, token1 = FRAX

   Scenario 1: User wants to rent some FXS using FRAX as collateral
   ===================================
   1) User obtains some FRAX, which will be used as collateral
   2) User calls executeActionsAndSwap() with 
      a) Positive token1Amount (add FRAX to vault)
      b) Negative token0Amount (withdraw FXS from vault)
      c) Positive rent (renting)
      d) The swapParams to swap SOME of the excess FRAX for FXS (they need to remain solvent at the end of the day)
      e) (Optional) v,r,s for a permit (token1 to this contract) for the vault add
   3) The internal call flow will be:
      i) BAMM-owned LP is unwound into BOTH FRAX and FXS, according to the supplied rent parameter. Both tokens are added to the user's vault.
      ii) User supplied FRAX is added to their vault to increase their collateral
      iii) Some of the excess FRAX from the LP unwind is swapped for FXS (according to swapParams)
      iv) FXS is sent to the user
      v) Contract will revert if the user is insolvent or the LP utility is above MAX_UTILITY_RATE


   Scenario 2: User from Scenario 1 wants to repay SOME of their rented FXS and get SOME FRAX back
   ===================================
   1) User calls executeActionsAndSwap() with 
      a) Negative token1Amount (withdraw FRAX from vault)
      b) Positive token0Amount (add FXS to vault)
      c) Negative rent (repaying)
      d) token0AmountMin to prevent sandwiches from the LP add
      e) token1AmountMin to prevent sandwiches from the LP add
      f) The swapParams to swap SOME of the FXS for FRAX. LP will be added at the current ratio so this is helpful.
      g) (Optional) v,r,s for a permit (token0 to this contract) for the vault add
   2) The internal call flow will be:
      i) Interest accrues so the user owes a little bit more FXS (and/or FRAX) now.
      ii) User-supplied FXS is added to the vault
      iii) Some of the FXS is swapped for FRAX (according to swapParams). 
      iv) FRAX and FXS are added (at current LP ratio) to make the Fraxswap LP, which becomes BAMM-owned, according to the supplied rent parameter.
      v) Accounting updated to lower rent and vaulted tokens.
      vi) FRAX is sent to the user
      vii) Contract will revert if the user is insolvent or the LP utility is above MAX_UTILITY_RATE


   Scenario 3: User from Scenario 1 wants to repay the remaining rented FXS, get their FRAX back, and close the position
   ===================================
   1) User calls executeActionsAndSwap() with 
      a) Negative token1Amount (withdraw FRAX from vault)
      b) Positive token0Amount (add FXS to vault)
      c) closePosition as true. No need to supply rent as the function will override it anyways 
      d) token0AmountMin to prevent sandwiches from the LP add
      e) token1AmountMin to prevent sandwiches from the LP add
      f) The swapParams to swap SOME of the FXS for FRAX. LP will be added at the current ratio so this is helpful.
      g) (Optional) v,r,s for a permit (token0 to this contract) for the vault add
   2) The internal call flow will be:
      i) Interest accrues so the user owes a little bit more FXS (and/or FRAX) now.
      ii) User-supplied FXS is added to the vault
      iii) Some of the FXS is swapped for FRAX (according to swapParams). 
      iv) Accounting updated to lower rent and vaulted tokens. 
      v) Any remaining FRAX or FXS needed is safeTransferFrom'd the user
      vi) FRAX and FXS are added (at current LP ratio) to make the Fraxswap LP, which becomes BAMM-owned, according to the supplied rent parameter
      vii) FRAX is sent back to the user
      viii) Contract will revert if the user is insolvent or the LP utility is above MAX_UTILITY_RATE


   Scenario 4: User wants to loan some LP and earn interest
   ===================================
   1) Approve LP to this BAMM contract
   2) Call mint(), which will give you BAMM tokens as a "receipt"
   3) Wait some time, and assume some other people borrow. Interest accrues
   4) Call redeem(), which burns your BAMM tokens and gives you your LP back, plus some extra LP as interest.
 
*/

// Frax Finance: https://github.com/FraxFinance

import { IERC20Metadata as IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";

import { IFraxswapPair } from "dev-fraxswap/src/contracts/core/interfaces/IFraxswapPair.sol";
import { IFraxswapRouterMultihop } from "dev-fraxswap/src/contracts/periphery/interfaces/IFraxswapRouterMultihop.sol";
import { Math } from "dev-fraxswap/src/contracts/core/libraries/Math.sol";
import { BAMMERC20 } from "./BAMMERC20.sol";
import { VariableInterestRate } from "src/contracts/VariableInterestRate.sol";

interface IFraxswapOracle {
    function getPrice(
        IFraxswapPair pool,
        uint256 period,
        uint256 rounds,
        uint256 maxDiffPerc
    ) external view returns (uint256 result0, uint256 result1);
}

interface IBAMMFactory {
    function feeTo() external view returns (address);
}

contract BAMM is ReentrancyGuard {
    using SafeCast for *;
    using Strings for uint256;

    // ############################################
    // ############## STATE VARIABLES #############
    // ############################################

    BAMMERC20 public immutable iBammErc20;

    /// @notice Token 0 in the UniV2-like LP
    IERC20 public immutable token0;

    /// @notice Token 1 in the UniV2-like LP
    IERC20 public immutable token1;

    /// @notice Address of the UniV2-like pair
    IFraxswapPair public immutable pair;

    /// @notice The Fraxswap router
    IFraxswapRouterMultihop public immutable routerMultihop;

    /// @notice Price oracle for the Fraxswap pair
    IFraxswapOracle public immutable fraxswapOracle;

    /// @notice Address of the BAMMFactory to create this contract
    address public immutable factory;

    /// @notice Tracks the amount of rented liquidity
    /// @dev Will never be < 0
    int256 public sqrtRented;

    /// @notice Multiplier used in interest rate and rent amount calculations. Never decreases and acts like an accumulator of sorts.
    uint256 public rentedMultiplier = PRECISION; // Initialized at PRECISION, but will change

    /// @notice The last time an interest payment was made
    uint256 public timeSinceLastInterestPayment = block.timestamp;

    /// @notice The `fullUtilizationRate` returned from the variable rate oracle
    uint256 public fullUtilizationRate;

    /// @notice The variableInterestRate associated
    VariableInterestRate public variableInterestRate;

    /// @notice Vault information for a given user
    mapping(address => Vault) public userVaults;

    // #######################################
    // ############## CONSTANTS ##############
    // #######################################

    /// @notice The precision to use and conform to
    uint256 public constant PRECISION = 1e18;

    /// @notice Percent above which the position is considered insolvent and can be liquidated
    uint256 public constant SOLVENCY_THRESHOLD_LIQUIDATION = (98 * PRECISION) / 100; // 98%

    /// @notice Percent above which the position is considered can be micro liquidated
    uint256 public constant SOLVENCY_THRESHOLD_MICRO_LIQUIDATION = (975 * PRECISION) / 1000; // 97.5%

    /// @notice Percent above which the position is considered insolvent after a user action
    uint256 public constant SOLVENCY_THRESHOLD_AFTER_ACTION = (975 * PRECISION) / 1000; // 97.5%

    /// @notice Protocol's cut of the interest rate
    uint256 public constant FEE_SHARE = (10 * 10_000) / 100; // 10%

    /// @notice The fee when a liquidation occurs
    uint256 public constant LIQUIDATION_FEE = 10_000; // 1%

    /// @notice The max fee when a micro liquidation occurs
    uint256 public constant MAX_MICRO_LIQUIDATION_FEE = 100_000; // 10%

    /// @notice The maximum utility rate for an LP
    uint256 public constant MAX_UTILITY_RATE = (PRECISION * 9) / 10; // 90%

    /// @notice The minimum liquidity allowed for the pool
    uint256 public constant MINIMUM_LIQUIDITY = 1e3;

    // #####################################
    // ############## Structs ##############
    // #####################################

    /// @notice Details for a user's vault
    struct Vault {
        int256 token0; // Token 0 in the LP
        int256 token1; // Token 1 in the LP
        int256 rented; // SQRT(#token0 * #token1) that is rented
    }

    /// @notice Function parameter pack for various actions. Different parts may be empty for different actions.
    struct Action {
        int256 token0Amount; // Amount of token 0. Positive = add to vault. Negative = remove from vault
        int256 token1Amount; // Amount of token 1. Positive = add to vault. Negative = remove from vault
        int256 rent; // SQRT(#token0 * #token1). Positive if borrowing, negative if repaying
        address to; // A destination address
        uint256 token0AmountMin; // Minimum amount of token 0 expected
        uint256 token1AmountMin; // Minimum amount of token 1 expected
        bool closePosition; // Whether to close the position or not
        bool approveMax; // Whether to approve max (e.g. uint256(-1) or similar)
        uint8 v; // Part of a signature
        bytes32 r; // Part of a signature
        bytes32 s; // Part of a signature
        uint256 deadline; // Deadline of this action
    }

    // ####################################
    // ############## Events ##############
    // ####################################

    /// @notice Emitted when BAMM tokens get minted by a user directly
    /// @param sender The person sending in the LP
    /// @param recipient The recipient of the minted BAMM tokens
    /// @param lpIn The amount of LP being sent in
    /// @param bammOut The amount of BAMM tokens minted
    event BAMMMinted(address indexed sender, address indexed recipient, uint256 lpIn, uint256 bammOut);

    /// @notice Emitted when BAMM tokens get redeemed by a user directly
    /// @param sender The person sending in the BAMM tokens
    /// @param recipient The recipient of the LP tokens
    /// @param bammIn The amount of BAMM tokens being sent in
    /// @param lpOut The amount of LP sent out
    event BAMMRedeemed(address indexed sender, address indexed recipient, uint256 bammIn, uint256 lpOut);

    /// @notice Emitted when a borrower pays back a loan
    /// @param borrower The borrower
    /// @param rent The rent change
    /// @param token0ToAddToLp Token0 paid back
    /// @param token1ToAddToLp Token1 paid back
    /// @param closePosition Whether the position was closed or not
    event LoanRepaid(
        address indexed borrower,
        int256 rent,
        uint256 token0ToAddToLp,
        uint256 token1ToAddToLp,
        bool closePosition
    );

    /// @notice Emitted when a borrower takes a loan
    /// @param borrower The borrower
    /// @param rent The rent change
    /// @param token0Amount Token0 credited to borrower's vault
    /// @param token1Amount Token1 credited to borrower's vault
    event LoanTaken(address indexed borrower, int256 rent, int256 token0Amount, int256 token1Amount);

    /// @notice Emitted when tokens are transferred from or to a borrower's vault
    /// @param token Address of token transferred (either token0 or token1)
    /// @param from Sender of token
    /// @param to Recipient of token
    /// @param tokenAmount Amount of token transferred
    event MoveTokenForVault(address indexed token, address indexed from, address indexed to, int256 tokenAmount);

    /// @notice Emitted when the borrower deposits tokens to their vault
    /// @param borrower The borrower
    /// @param token0Amount Amount of token0 deposited
    /// @param token1Amount Amount of token1 deposited
    event TokensDepositedToVault(address indexed borrower, uint256 token0Amount, uint256 token1Amount);

    /// @notice Emitted when the borrower withdraws tokens from their vault
    /// @param borrower The borrower
    /// @param token0Amount Amount of token0 withdrawn
    /// @param token1Amount Amount of token1 withdrawn
    event TokensWithdrawnFromVault(address indexed borrower, uint256 token0Amount, uint256 token1Amount);

    /// @notice Emitted when a user gets liquidated
    /// @param user The user being liquidated
    /// @param liquidator The person doing the liquidating
    /// @param rented The total amount of liquidity rented
    event UserLiquidated(address indexed user, address indexed liquidator, uint256 rented);

    // #########################################
    // ############## Constructor ##############
    // #########################################

    constructor(bytes memory _encodedBammConstructorArgs) {
        (
            uint256 _id,
            address _pair,
            address _fraxswapRouter,
            address _fraxswapOracle,
            address _variableInterestRateAddress,
            uint64 startFullUtilRate
        ) = abi.decode(_encodedBammConstructorArgs, (uint256, address, address, address, address, uint64));

        // fill in state variables
        pair = IFraxswapPair(_pair);
        token0 = IERC20(pair.token0());
        token1 = IERC20(pair.token1());
        routerMultihop = IFraxswapRouterMultihop(_fraxswapRouter);
        fraxswapOracle = IFraxswapOracle(_fraxswapOracle);
        factory = msg.sender;
        variableInterestRate = VariableInterestRate(_variableInterestRateAddress);
        fullUtilizationRate = startFullUtilRate;

        // Create BAMM ERC20
        // Setup name/symbol
        string memory ticker;
        {
            string memory symbol0 = token0.symbol();
            string memory symbol1 = token1.symbol();
            ticker = string(abi.encodePacked(symbol0, "/", symbol1));
        }
        string memory name = string(abi.encodePacked("BAMM_", _id.toString(), "_", ticker, " Fraxswap V2"));
        string memory symbol = string(abi.encodePacked("BAMM_", ticker));
        iBammErc20 = new BAMMERC20(name, symbol);
    }

    /// @notice Semantic version of this contract
    /// @return _major The major version
    /// @return _minor The minor version
    /// @return _patch The patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        return (0, 5, 0);
    }

    // ############################################
    // ############## Lender actions ##############
    // ############################################

    /// @notice Mint BAMM wrapper tokens with LP tokens
    /// @param to Destination address for the wrapper tokens
    /// @param lpIn The amount of UniV2-like LP to wrap
    /// @return bammOut The amount of BAMM tokens generated
    /// @dev Make sure to approve first
    function mint(address to, uint256 lpIn) external nonReentrant returns (uint256 bammOut) {
        // Sync the LP, then add the interest
        (uint112 reserve0, uint112 reserve1, uint256 pairTotalSupply) = _addInterest();

        // Calculate the LP to BAMM conversion
        uint256 sqrtReserve = Math.sqrt(uint256(reserve0) * reserve1);
        uint256 sqrtAmount = (lpIn * sqrtReserve) / pairTotalSupply;
        uint256 balance = pair.balanceOf(address(this));

        // Take the LP from the sender and mint them BAMM wrapper tokens
        uint256 totalSupply_ = iBammErc20.totalSupply();
        if (totalSupply_ == 0) {
            // At 0 supply, mint initial liquidity and lock it
            bammOut = sqrtAmount - MINIMUM_LIQUIDITY;
            iBammErc20.mint(address(1), MINIMUM_LIQUIDITY);
        } else {
            uint256 sqrtBalance = (balance * sqrtReserve) / pairTotalSupply;
            uint256 sqrtRentedReal = (uint256(sqrtRented) * rentedMultiplier) / PRECISION;
            bammOut = (sqrtAmount * totalSupply_) / (sqrtBalance + sqrtRentedReal);
        }
        /// Revert if lpIn == 0 as sqrtAmount = 0 and in rounding down small amounts
        if (bammOut == 0) revert ZeroLiquidityMinted();

        // Transfer LP token to bamm and give `to` the BAMM wrapper tokens
        SafeERC20.safeTransferFrom({ token: IERC20(address(pair)), from: msg.sender, to: address(this), value: lpIn });
        iBammErc20.mint({ account: ((to == address(0)) ? msg.sender : to), value: bammOut });

        emit BAMMMinted({ sender: msg.sender, recipient: to, lpIn: lpIn, bammOut: bammOut });
    }

    /// @notice Redeem BAMM wrapper tokens for LP tokens
    /// @param to Destination address for the LP tokens
    /// @param bammIn The amount of BAMM tokens to redeem for UniV2-like LP
    /// @return lpOut The amount of LP tokens generated
    function redeem(address to, uint256 bammIn) external nonReentrant returns (uint256 lpOut) {
        // Sync the LP, then add the interest
        (uint112 reserve0, uint112 reserve1, uint256 pairTotalSupply) = _addInterest();

        // Calculate the BAMM to LP conversion
        uint256 sqrtToRedeem;
        uint256 sqrtReserve;
        {
            uint256 balance = pair.balanceOf(address(this));
            sqrtReserve = Math.sqrt(uint256(reserve0) * reserve1);
            uint256 sqrtBalance = (balance * sqrtReserve) / pairTotalSupply;
            uint256 sqrtRentedReal = (uint256(sqrtRented) * rentedMultiplier) / PRECISION;
            sqrtToRedeem = (bammIn * (sqrtBalance + sqrtRentedReal)) / iBammErc20.totalSupply();
        }

        // Burn the BAMM wrapper tokens from the sender and give them LP
        if (sqrtToRedeem > 0) {
            lpOut = (sqrtToRedeem * pairTotalSupply) / sqrtReserve;
            SafeERC20.safeTransfer({
                token: IERC20(address(pair)),
                to: (to == address(0) ? msg.sender : to),
                value: lpOut
            });
        }
        iBammErc20.burn({ account: msg.sender, value: bammIn });

        // Max sure the max utility is within acceptable range
        if (!_isValidUtilityRate({ reserve0: reserve0, reserve1: reserve1, pairTotalSupply: pairTotalSupply })) {
            revert InvalidUtilityRate();
        }

        emit BAMMRedeemed({ sender: msg.sender, recipient: to, bammIn: bammIn, lpOut: lpOut });
    }

    // ############################################
    // ############# Borrower actions #############
    // ############################################

    /// @notice Execute actions
    /// @param action The details of the action to be executed
    function executeActions(Action memory action) public returns (Vault memory vault) {
        IFraxswapRouterMultihop.FraxswapParams memory swapParams;
        return executeActionsAndSwap({ action: action, swapParams: swapParams });
    }

    /// @notice Calculate total supply adjustment due to protocol fees in the Fraxswap pair.
    /// @dev see: https://github.com/FraxFinance/dev-fraxswap/blob/9744c757f7e51c1deee3f5db50d3aaec495aea01/src/contracts/core/FraxswapPair.sol#L317
    /// @param reserve0 The reserves for token0 of the pair
    /// @param reserve1 The reserves for token1 of the pair
    /// @return tsAdjustment The total supply adjustment of the lp token due to fees
    function _calcMintedSupplyFromPairMintFee(
        uint256 reserve0,
        uint256 reserve1,
        uint256 totalSupply
    ) internal view returns (uint256 tsAdjustment) {
        uint256 k = Math.sqrt(uint256(reserve0) * reserve1);
        uint256 kLast = pair.kLast();
        if (kLast != 0) {
            kLast = Math.sqrt(kLast);
            if (k > kLast) {
                uint256 num = totalSupply * (k - kLast);
                uint256 denom = (k * 5) + kLast;
                tsAdjustment = num / denom;
            }
        }
    }

    function _syncVault(
        Vault memory _vault,
        int256 _rent,
        uint112 _reserve0,
        uint112 _reserve1,
        uint256 _pairTotalSupply
    ) internal returns (int256 lpTokenAmount, int256 token0Amount, int256 token1Amount) {
        // Calculate the amount of LP, token0, and token1
        int256 sqrtAmountRented = (_rent * rentedMultiplier.toInt256()) / 1e18;
        if (((sqrtAmountRented * 1e18) / rentedMultiplier.toInt256()) > _rent) sqrtAmountRented -= 1;
        lpTokenAmount =
            (sqrtAmountRented * _pairTotalSupply.toInt256()) /
            int256(Math.sqrt(uint256(_reserve0) * _reserve1));
        token0Amount = (int256(uint256(_reserve0)) * lpTokenAmount) / _pairTotalSupply.toInt256();
        token1Amount = (int256(uint256(_reserve1)) * lpTokenAmount) / _pairTotalSupply.toInt256();

        if (_rent < 0) {
            if (((token0Amount * _pairTotalSupply.toInt256()) / _reserve0.toInt256()) > lpTokenAmount) {
                token0Amount -= 1;
            }
            if (((token1Amount * _pairTotalSupply.toInt256()) / _reserve1.toInt256()) > lpTokenAmount) {
                token1Amount -= 1;
            }
        }

        // Update the rent and credit the user some token0 and token1
        _vault.rented += _rent;
        _vault.token0 += token0Amount;
        _vault.token1 += token1Amount;

        // Update the total rented liquidity
        sqrtRented += _rent;
    }

    /// @dev _rent is positive
    function _borrow(
        Vault memory _vault,
        int256 _rent,
        uint112 _reserve0,
        uint112 _reserve1,
        uint256 _pairTotalSupply
    ) internal {
        (int256 lpTokenAmount, int256 token0Amount, int256 token1Amount) = _syncVault({
            _vault: _vault,
            _rent: _rent,
            _reserve0: _reserve0,
            _reserve1: _reserve1,
            _pairTotalSupply: _pairTotalSupply
        });

        // Transfer LP to the LP contract, then optimistically burn it there to release token0 and token1 to this contract
        // The tokens will be given to the borrower later, assuming action.token0Amount and/or action.token1Amount is positive
        SafeERC20.safeTransfer({ token: IERC20(address(pair)), to: address(pair), value: uint256(lpTokenAmount) });
        pair.burn(address(this));

        emit LoanTaken({ borrower: msg.sender, rent: _rent, token0Amount: token0Amount, token1Amount: token1Amount });
    }

    /// @dev rent is negative
    function _repay(
        Vault memory _vault,
        int256 _rent,
        uint112 _reserve0,
        uint112 _reserve1,
        uint256 _pairTotalSupply,
        uint256 _token0AmountMin,
        uint256 _token1AmountMin
    ) internal returns (uint256 token0ToAddToLp, uint256 token1ToAddToLp) {
        (, int256 token0Amount, int256 token1Amount) = _syncVault({
            _vault: _vault,
            _rent: _rent,
            _reserve0: _reserve0,
            _reserve1: _reserve1,
            _pairTotalSupply: _pairTotalSupply
        });

        // token0Amount and token1Amount are negative as they subtracted balances from the vault, so we need to convert positive
        token0ToAddToLp = uint256(-token0Amount);
        token1ToAddToLp = uint256(-token1Amount);

        // Avoid sandwich attacks
        // token0Amount and token1Amount are negative as they subtract balances from the vault
        if ((token0ToAddToLp < _token0AmountMin) || (token1ToAddToLp < _token1AmountMin)) {
            revert InsufficientAmount();
        }
    }

    /// @notice Execute actions and also do a swap
    /// @param action The details of the action to be executed
    /// @param swapParams The details of the swap to be executed
    function executeActionsAndSwap(
        Action memory action,
        IFraxswapRouterMultihop.FraxswapParams memory swapParams
    ) public nonReentrant returns (Vault memory vault) {
        // Get the existing vault info for the user
        vault = userVaults[msg.sender];

        // Sync the LP, then add the interest
        (uint112 reserve0, uint112 reserve1, uint256 pairTotalSupply) = _addInterest();

        // Note if the user is closing the position
        if (action.closePosition) action.rent = -vault.rented;

        // Rent LP constituent tokens (if specified). Positive rent means borrowing
        if (action.rent > 0) {
            _borrow({
                _vault: vault,
                _rent: action.rent,
                _reserve0: reserve0,
                _reserve1: reserve1,
                _pairTotalSupply: pairTotalSupply
            });
        }

        // If specified in the action, add tokens to the vault (vault is modified by reference)
        // Positive token0Amount and/or token1Amount means add from vault
        if (action.token0Amount > 0 || action.token1Amount > 0) _addTokensToVault({ _vault: vault, _action: action });

        // Execute the swap if there are swapParams
        if (swapParams.amountIn != 0) {
            // Do the swap
            _executeSwap(vault, swapParams);

            // Swap might have changed the reserves of the pair.
            if (action.rent != 0) {
                (reserve0, reserve1, pairTotalSupply) = _addInterest();
            }
        }

        // Return rented LP constituent tokens (if specified) to this contract.
        // Negative rent means repaying but not closing.
        uint256 token0ToAddToLp;
        uint256 token1ToAddToLp;
        if (action.rent < 0) {
            (token0ToAddToLp, token1ToAddToLp) = _repay({
                _vault: vault,
                _rent: action.rent,
                _reserve0: reserve0,
                _reserve1: reserve1,
                _pairTotalSupply: pairTotalSupply,
                _token0AmountMin: action.token0AmountMin,
                _token1AmountMin: action.token1AmountMin
            });
        }

        // Close the position (if specified)
        if (action.closePosition) {
            // You might have some leftover tokens you can withdraw later if you over-collateralized
            action.token0Amount = -vault.token0;
            action.token1Amount = -vault.token1;
            _addTokensToVault({ _vault: vault, _action: action });
        }

        // Return rented LP constituent tokens (continued from above)
        // This portion recovers the LP and gives it to this BAMM contract
        if (token0ToAddToLp > 0) {
            // Send token0 and token1 directly to the LP address
            SafeERC20.safeTransfer({ token: token0, to: address(pair), value: token0ToAddToLp });
            SafeERC20.safeTransfer({ token: token1, to: address(pair), value: token1ToAddToLp });

            // Mint repayed LP last, so we know we have enough tokens in the contract
            pair.mint(address(this));

            emit LoanRepaid({
                borrower: msg.sender,
                rent: -action.rent,
                token0ToAddToLp: token0ToAddToLp,
                token1ToAddToLp: token1ToAddToLp,
                closePosition: action.closePosition
            });
        }

        // Remove token0 from the vault and give to the user (if specified)
        // Negative token0Amount means remove from vault
        if (action.token0Amount < 0) {
            if (action.to == address(this)) revert CannotWithdrawToSelf();
            _moveTokenForVault({
                _vault: vault,
                _token: token0,
                _to: (action.to == address(0) ? msg.sender : action.to),
                _tokenAmount: action.token0Amount
            });
        }

        // Remove token1 from the vault and give to the user (if specified)
        // Negative token1Amount means remove from vault
        if (action.token1Amount < 0) {
            if (action.to == address(this)) revert CannotWithdrawToSelf();
            _moveTokenForVault({
                _vault: vault,
                _token: token1,
                _to: (action.to == address(0) ? msg.sender : action.to),
                _tokenAmount: action.token1Amount
            });
        }

        // Write the final vault state to storage after all the above operations are completed
        userVaults[msg.sender] = vault;

        // Make sure the user is still solvent
        if (!_solvent(vault, SOLVENCY_THRESHOLD_AFTER_ACTION)) {
            revert NotSolvent();
        }

        // Check max utility after a rent
        // TODO: should we check max utility after a swap as well?
        if (action.rent > 0) {
            if (!_isValidUtilityRate({ reserve0: reserve0, reserve1: reserve1, pairTotalSupply: pairTotalSupply })) {
                revert InvalidUtilityRate();
            }
        }
    }

    function _moveTokenForVault(Vault memory _vault, IERC20 _token, address _to, int256 _tokenAmount) internal {
        // NOTE: _tokenAmount is negative when withdrawing from vault and positive when depositing to vault
        if (_token == token0) {
            _vault.token0 += _tokenAmount;
        } else {
            // _token == token1
            /// @dev _token will always be either token0 or token1
            _vault.token1 += _tokenAmount;
        }

        if (_to == address(this)) {
            // deposit
            SafeERC20.safeTransferFrom({
                token: _token,
                from: msg.sender,
                to: address(this), // for clarity
                value: uint256(_tokenAmount)
            });
        } else {
            // withdrawal (_tokenAmount is currently negative)
            SafeERC20.safeTransfer({ token: _token, to: _to, value: uint256(-_tokenAmount) });
        }

        emit MoveTokenForVault({ token: address(_token), from: msg.sender, to: _to, tokenAmount: _tokenAmount });
    }

    // ############################################
    // ############ Liquidator actions ############
    // ############################################

    struct LiquidationMath {
        uint112 reserve0;
        uint112 reserve1;
        uint256 pairTotalSupply;
        uint256 partialLiquidationOut;
        uint256 token0ToLiquidity;
        uint256 token1ToLiquidity;
        uint256 token0Fee;
        uint256 token1Fee;
    }

    function getMaxSell(
        uint256 tokenIn,
        uint256 tokenOut,
        uint256 reserveIn,
        uint256 reserveOut
    ) public returns (uint256 maxSell) {
        // Solve x for: (reserveOut-y)/(reserveIn+x) = (tokenOut+y)/(tokenIn-x), (reserveOut-y)*(reserveIn+x)=reserveIn*reserveOut
        uint256 prod = Math.sqrt(reserveOut * reserveIn) * Math.sqrt((reserveOut + tokenOut) * (reserveIn + tokenIn));
        uint256 minus = reserveIn * tokenOut + reserveOut * reserveIn;
        if (prod > minus) maxSell = (prod - minus) / (reserveOut + tokenOut);
    }

    /// @notice Micro liquidate a user by doing a small swap and adding the liquidity back to the pool
    /// @param user The user to be micro-liquidated
    /// @return token0Fee The number of token0 received as liquidion fee
    /// @return token1Fee The number of token1 received as liquidion fee
    function microLiquidate(address user) external nonReentrant returns (uint256 token0Fee, uint256 token1Fee) {
        // Sync the LP, then add the interest
        (uint112 reserve0, uint112 reserve1, ) = _addInterest();
        // Compare the spot price from the reserves to the oracle price. Revert if they are off by too much.
        ammPriceCheck(reserve0, reserve1);

        // Get the existing vault info for the user
        Vault memory vault = userVaults[user];

        // Make sure the user is NOT solvent for micro liquidations
        uint256 _ltv = ltv(vault);
        if (_ltv < SOLVENCY_THRESHOLD_MICRO_LIQUIDATION) revert("User solvent");

        // Sell amount is a percentage of the excess in the vault. This percentage starts at 1% of the max amount and goes up with the ltv, creating an auction.
        uint256 sellToken0;
        uint256 sellToken1;
        if (uint256(vault.token0) > (uint256(vault.token1) * reserve0) / reserve1) {
            // Excess token0
            uint256 maxSell = getMaxSell(
                uint256(vault.token0),
                uint256(vault.token1),
                uint256(reserve0),
                uint256(reserve1)
            );
            uint256 minSell = maxSell / 100; // 1%
            uint256 kinkSell = maxSell / 20; // 5%
            uint256 kinkLTV = (SOLVENCY_THRESHOLD_LIQUIDATION + SOLVENCY_THRESHOLD_MICRO_LIQUIDATION * 3) / 4;
            if (_ltv < kinkLTV)
                sellToken0 =
                    minSell +
                    ((kinkSell - minSell) * (_ltv - SOLVENCY_THRESHOLD_MICRO_LIQUIDATION)) /
                    (kinkLTV - SOLVENCY_THRESHOLD_MICRO_LIQUIDATION);
            else if (_ltv < SOLVENCY_THRESHOLD_LIQUIDATION)
                sellToken0 =
                    kinkSell +
                    ((maxSell - kinkSell) * (_ltv - kinkLTV)) /
                    (SOLVENCY_THRESHOLD_LIQUIDATION - kinkLTV);
            else sellToken0 = maxSell;
        } else {
            // Excess token1
            uint256 maxSell = getMaxSell(
                uint256(vault.token1),
                uint256(vault.token0),
                uint256(reserve1),
                uint256(reserve0)
            );
            uint256 minSell = maxSell / 100; // 1%
            uint256 kinkSell = maxSell / 20; // 5%
            uint256 kinkLTV = (SOLVENCY_THRESHOLD_LIQUIDATION + SOLVENCY_THRESHOLD_MICRO_LIQUIDATION * 3) / 4;
            if (_ltv < kinkLTV)
                sellToken1 =
                    minSell +
                    ((kinkSell - minSell) * (_ltv - SOLVENCY_THRESHOLD_MICRO_LIQUIDATION)) /
                    (kinkLTV - SOLVENCY_THRESHOLD_MICRO_LIQUIDATION);
            else if (_ltv < SOLVENCY_THRESHOLD_LIQUIDATION)
                sellToken1 =
                    kinkSell +
                    ((maxSell - kinkSell) * (_ltv - kinkLTV)) /
                    (SOLVENCY_THRESHOLD_LIQUIDATION - kinkLTV);
            else sellToken1 = maxSell;
        }

        if (sellToken0 > 0 || sellToken1 > 0) {
            // The liquidationFee starts at 0% and goes up with the LTV, creating an auction
            uint256 liquidationFee = _ltv > SOLVENCY_THRESHOLD_LIQUIDATION
                ? MAX_MICRO_LIQUIDATION_FEE
                : (MAX_MICRO_LIQUIDATION_FEE * (_ltv - SOLVENCY_THRESHOLD_MICRO_LIQUIDATION)) /
                    (SOLVENCY_THRESHOLD_LIQUIDATION - SOLVENCY_THRESHOLD_MICRO_LIQUIDATION);

            // Execute the micro liquidation
            (token0Fee, token1Fee) = _liquidate(user, sellToken0, sellToken1, liquidationFee, true);
        }
    }

    /// @notice Liquidate an underwater user by adding the liquidity back to the pool
    /// @param user The user to be liquidated
    /// @param sellToken0 The number of token0 to sell for the vault to be balanced
    /// @param sellToken1 The number of token1 to sell for the vault to be balanced
    /// @return token0Fee The number of token0 received as liquidion fee
    /// @return token1Fee The number of token1 received as liquidion fee
    function liquidate(
        address user,
        uint256 sellToken0,
        uint256 sellToken1
    ) external nonReentrant returns (uint256 token0Fee, uint256 token1Fee) {
        (token0Fee, token1Fee) = _liquidate(user, sellToken0, sellToken1, LIQUIDATION_FEE, false);
    }

    /// @notice Liquidate an underwater user by adding the liquidity back to the pool
    /// @param user The user to be liquidated
    /// @param sellToken0 The number of token0 to sell for the vault to be balanced
    /// @param sellToken1 The number of token1 to sell for the vault to be balanced
    /// @return token0Fee The number of token0 received as liquidion fee
    /// @return token1Fee The number of token1 received as liquidion fee
    function _liquidate(
        address user,
        uint256 sellToken0,
        uint256 sellToken1,
        uint256 liquidationFee,
        bool isMicroLiquidation
    ) internal returns (uint256 token0Fee, uint256 token1Fee) {
        LiquidationMath memory liquidationMath;

        // Sync the LP, then add the interest
        (liquidationMath.reserve0, liquidationMath.reserve1, ) = _addInterest();

        // Compare the spot price from the reserves to the oracle price. Revert if they are off by too much.
        ammPriceCheck(liquidationMath.reserve0, liquidationMath.reserve1);

        // Make sure the user is NOT solvent
        if (!isMicroLiquidation && solvent(user)) revert("User solvent");

        // Get the existing vault info for the user
        Vault memory vault = userVaults[user];

        // Execute the sells as proposed by the liquidator
        // uint256 partialLiquidationOut;
        if (sellToken0 > 0) {
            // Cap the amount sold to 1/10th of the vault and 1/10 of the total liquidity.
            if (sellToken0 > uint256(vault.token0) / 10 || sellToken0 > liquidationMath.reserve0 / 10) {
                sellToken0 = uint256(vault.token0) / 10;
                if (sellToken0 > liquidationMath.reserve0 / 10) sellToken0 = liquidationMath.reserve0 / 10;
                liquidationMath.partialLiquidationOut = 1;
            }
            uint256 token1Out = getAmountOut(
                liquidationMath.reserve0,
                liquidationMath.reserve1,
                sellToken0,
                pair.fee()
            );
            if (token1Out > 0) {
                if (liquidationMath.partialLiquidationOut == 1 || isMicroLiquidation)
                    liquidationMath.partialLiquidationOut = token1Out;
                SafeERC20.safeTransfer(token0, address(pair), sellToken0);
                pair.swap(0, token1Out, address(this), "");
                vault.token0 -= int256(sellToken0);
                vault.token1 += int256(token1Out);
            }
        } else if (sellToken1 > 0) {
            // Cap the amount sold to 1/10th of the vault and 1/10 of the total liquidity.
            if (sellToken1 > uint256(vault.token1) / 10 || sellToken1 > liquidationMath.reserve1 / 10) {
                sellToken1 = uint256(vault.token1) / 10;
                if (sellToken1 > liquidationMath.reserve1 / 10) sellToken1 = liquidationMath.reserve1 / 10;
                liquidationMath.partialLiquidationOut = 1;
            }
            uint256 token0Out = getAmountOut(
                liquidationMath.reserve1,
                liquidationMath.reserve0,
                sellToken1,
                pair.fee()
            );
            if (token0Out > 0) {
                if (liquidationMath.partialLiquidationOut == 1 || isMicroLiquidation)
                    liquidationMath.partialLiquidationOut = token0Out;
                SafeERC20.safeTransfer(token1, address(pair), sellToken1);
                pair.swap(token0Out, 0, address(this), "");
                vault.token0 += int256(token0Out);
                vault.token1 -= int256(sellToken1);
            }
        }

        // Reserves have changed due to the swap, refresh.
        // uint256 pairTotalSupply;
        (liquidationMath.reserve0, liquidationMath.reserve1, liquidationMath.pairTotalSupply) = _addInterest();

        // Calculate the max amount of tokens to add as liquidity
        if (!isMicroLiquidation && liquidationMath.partialLiquidationOut == 0) {
            if (uint256(vault.token0) > (uint256(vault.token1) * liquidationMath.reserve0) / liquidationMath.reserve1) {
                // Excess token0
                liquidationMath.token0ToLiquidity =
                    (uint256(vault.token1) * liquidationMath.reserve0) /
                    liquidationMath.reserve1;
                liquidationMath.token1ToLiquidity = uint256(vault.token1);
            } else {
                // Excess token1
                liquidationMath.token0ToLiquidity = uint256(vault.token0);
                liquidationMath.token1ToLiquidity =
                    (uint256(vault.token0) * liquidationMath.reserve1) /
                    liquidationMath.reserve0;
            }
            // Check to see if the proposed swap has resulted an equal ratio in the vault as in the AMM pair.
            require(
                vault.token0 - int256(liquidationMath.token0ToLiquidity) < 10 ||
                    (vault.token0 - int256(liquidationMath.token0ToLiquidity)) * 10_000 < vault.token0,
                "Swap not close enough token0"
            );
            require(
                vault.token1 - int256(liquidationMath.token1ToLiquidity) < 10 ||
                    (vault.token1 - int256(liquidationMath.token1ToLiquidity)) * 10_000 < vault.token1,
                "Swap not close enough token1"
            );
        } else {
            // Partial liquidation
            if (sellToken0 > 0) {
                liquidationMath.token0ToLiquidity =
                    (liquidationMath.partialLiquidationOut * liquidationMath.reserve0) /
                    liquidationMath.reserve1;
                liquidationMath.token1ToLiquidity = liquidationMath.partialLiquidationOut;
                // Check to make sure we still have too much token0
                require(
                    (uint256(vault.token0) * liquidationMath.reserve1) / liquidationMath.reserve0 >
                        uint256(vault.token1),
                    "Partial liquidation failed"
                );
            } else {
                liquidationMath.token0ToLiquidity = liquidationMath.partialLiquidationOut;
                liquidationMath.token1ToLiquidity =
                    (liquidationMath.partialLiquidationOut * liquidationMath.reserve1) /
                    liquidationMath.reserve0;
                // Check to make sure we still have too much token1
                require(
                    (uint256(vault.token1) * liquidationMath.reserve0) / liquidationMath.reserve1 >
                        uint256(vault.token0),
                    "Partial liquidation failed"
                );
            }
        }

        {
            // Give the liquidation fee to the liquidator as a percentage of the total vaults value
            token0Fee = (liquidationMath.token0ToLiquidity * liquidationFee) / 1_000_000;
            liquidationMath.token0ToLiquidity -= token0Fee;
            SafeERC20.safeTransfer(IERC20(address(token0)), msg.sender, token0Fee);
            vault.token0 -= int256(token0Fee);

            token1Fee = (liquidationMath.token1ToLiquidity * liquidationFee) / 1_000_000;
            liquidationMath.token1ToLiquidity -= token1Fee;
            SafeERC20.safeTransfer(IERC20(address(token1)), msg.sender, token1Fee);
            vault.token1 -= int256(token1Fee);
        }

        {
            // Add liquidity
            uint256 sqrtAmountRented = (uint256(vault.rented) * rentedMultiplier) / 1e18;
            uint256 lpTokenToLiquidity = Math.min(
                (liquidationMath.token0ToLiquidity * liquidationMath.pairTotalSupply) / liquidationMath.reserve0,
                (liquidationMath.token1ToLiquidity * liquidationMath.pairTotalSupply) / liquidationMath.reserve1
            );
            uint256 sqrtToLiquidity = _lpTokenToSqrtAmount(
                lpTokenToLiquidity,
                liquidationMath.pairTotalSupply,
                liquidationMath.reserve0,
                liquidationMath.reserve1
            );
            int256 returnedAmount = vault.rented;
            if (sqrtToLiquidity > sqrtAmountRented) {
                // Pay down fully
                (, int256 token0Amount, int256 token1Amount) = _syncVault(
                    vault,
                    -vault.rented,
                    liquidationMath.reserve0,
                    liquidationMath.reserve1,
                    liquidationMath.pairTotalSupply
                );
                liquidationMath.token0ToLiquidity = uint256(-token0Amount);
                liquidationMath.token1ToLiquidity = uint256(-token1Amount);
            } else if (liquidationMath.partialLiquidationOut > 0) {
                // Partial liquidation
                vault.token0 -= int256(liquidationMath.token0ToLiquidity);
                vault.token1 -= int256(liquidationMath.token1ToLiquidity);
                returnedAmount = int256((sqrtToLiquidity * 1e18) / rentedMultiplier);
                vault.rented -= returnedAmount;
                sqrtRented -= returnedAmount;
            } else {
                // Bad debt
                liquidationMath.token0ToLiquidity = uint256(vault.token0);
                liquidationMath.token1ToLiquidity = uint256(vault.token1);
                vault.token0 = 0;
                vault.token1 = 0;
                vault.rented -= returnedAmount;
                sqrtRented -= returnedAmount;
            }
            SafeERC20.safeTransfer(IERC20(address(token0)), address(pair), liquidationMath.token0ToLiquidity);
            SafeERC20.safeTransfer(IERC20(address(token1)), address(pair), liquidationMath.token1ToLiquidity);
            pair.mint(address(this));

            emit UserLiquidated(user, msg.sender, uint256(returnedAmount));
        }

        // Update the user's vault
        if (!_isValidVault(vault)) revert InvalidVault();
        userVaults[user] = vault;
    }

    function getAmountOut(
        uint256 reserveIn,
        uint256 reserveOut,
        uint256 amountIn,
        uint256 fee
    ) internal pure returns (uint256) {
        require(amountIn > 0 && reserveIn > 0 && reserveOut > 0); // INSUFFICIENT_INPUT_AMOUNT, INSUFFICIENT_LIQUIDITY
        uint256 amountInWithFee = amountIn * fee;
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = (reserveIn * 10_000) + amountInWithFee;
        return numerator / denominator;
    }

    // ############################################
    // ############# External utility #############
    // ############################################

    /// @notice Accrue interest payments
    /// @return reserve0 The LP's reserve0
    /// @return reserve1 The LP's reserve1
    /// @return totalSupply The LP's totalSupply()
    /// @return _rentedMultiplier rentedMultiplier after interest calculation
    function addInterest()
        external
        nonReentrant
        returns (uint256 reserve0, uint256 reserve1, uint256 totalSupply, uint256 _rentedMultiplier)
    {
        (reserve0, reserve1, totalSupply) = _addInterest();
        _rentedMultiplier = rentedMultiplier;
    }

    /// @notice Is a user solvent?
    /// @param user The user to check
    /// @return bool If the user is solvent
    function solvent(address user) public view returns (bool) {
        Vault memory vault = userVaults[user];
        return _solvent(vault, SOLVENCY_THRESHOLD_LIQUIDATION);
    }

    /// @notice Get the interest rate at the specified _utilization
    /// @param _deltaTime The time in seconds between now and the previous interest accrual
    /// @param _utilization The internal Bamm Utilization represented in 1e18 w/ a max of 0.9e18
    /// @return newRatePerSec The interest rate per second
    function _getVariableInterestRate(
        uint256 _deltaTime,
        uint256 _utilization
    ) internal returns (uint256 newRatePerSec) {
        uint256 utilScaled = (_utilization * 1e5) / 0.9e18;
        (newRatePerSec, fullUtilizationRate) = variableInterestRate.getNewRate(
            _deltaTime,
            utilScaled,
            uint64(fullUtilizationRate)
        );
    }

    /// @notice public view function to view the calculated interest rate at a given utilization
    /// @param _utilization The internal Bamm Utilization represented in 1e18 w/ a max of 0.9e18
    /// @return newRatePerSec The interest rate per second
    function previewInterestRate(uint256 _utilization) public view returns (uint256 newRatePerSec) {
        uint256 utilScaled = (_utilization * 1e5) / 0.9e18;
        uint256 period = block.timestamp - timeSinceLastInterestPayment;
        (newRatePerSec, ) = variableInterestRate.getNewRate(period, utilScaled, uint64(fullUtilizationRate));
    }

    // ############################################
    // ################# Internal #################
    // ############################################

    /// @notice Transfers LP constituent tokens from the user to this contract, and marks it as part of their vault.
    /// @param _vault The _vault you are modifying
    /// @param _action The _action
    /// @dev _vault is passed by reference, so it modified in the caller
    function _addTokensToVault(Vault memory _vault, Action memory _action) internal {
        // // Make sure only one token is being added
        // require(!(_action.token0Amount > 0 && _action.token1Amount > 0), 'Can only add one token');

        // Approve via permit
        if (_action.v != 0 && (_action.token0Amount > 0 || _action.token1Amount > 0)) {
            // Determine the token of the permit
            IERC20 token = _action.token0Amount > 0 ? token0 : token1;

            // Do the permit
            uint256 amount = _action.approveMax
                ? type(uint256).max
                : uint256(_action.token0Amount > 0 ? _action.token0Amount : _action.token1Amount);
            IERC20Permit(address(token)).permit({
                owner: msg.sender,
                spender: address(this),
                value: amount,
                deadline: _action.deadline,
                v: _action.v,
                r: _action.r,
                s: _action.s
            });
        }

        // Add token0 to the vault
        if (_action.token0Amount > 0) {
            _moveTokenForVault({
                _vault: _vault,
                _token: token0,
                _to: address(this),
                _tokenAmount: _action.token0Amount
            });
        }

        // Add token1 to the vault
        if (_action.token1Amount > 0) {
            _moveTokenForVault({
                _vault: _vault,
                _token: token1,
                _to: address(this),
                _tokenAmount: _action.token1Amount
            });
        }
    }

    /// @notice Swaps tokens in the users vault
    /// @param vault The vault you are modifying
    /// @param swapParams Info about the swap. Is modified
    /// @dev vault and swapParams are passed by reference, so they modified in the caller
    function _executeSwap(Vault memory vault, IFraxswapRouterMultihop.FraxswapParams memory swapParams) internal {
        // Make sure the order of the swap is one of two directions
        if (
            !(swapParams.tokenIn == address(token0) && swapParams.tokenOut == address(token1)) &&
            !(swapParams.tokenIn == address(token1) && swapParams.tokenOut == address(token0))
        ) {
            revert IncorrectSwapTokens();
        }

        // Approve the input token to the router
        SafeERC20.safeIncreaseAllowance({
            token: IERC20(swapParams.tokenIn),
            spender: address(routerMultihop),
            value: swapParams.amountIn
        });

        // Set the recipient to this address
        swapParams.recipient = address(this);

        // Router checks the minAmountOut
        /// @dev: ensure swapParams are correct - fat-fingered route data may result in lost funds
        /// @dev: we trust the output of the routerMultihop, token transfered in and out are checked in the router
        uint256 amountOut = routerMultihop.swap(swapParams);
        if (swapParams.tokenIn == address(token0)) {
            vault.token0 -= swapParams.amountIn.toInt256();
            vault.token1 += amountOut.toInt256();
        } else {
            vault.token1 -= swapParams.amountIn.toInt256();
            vault.token0 += amountOut.toInt256();
        }
    }

    /// @notice Sync the LP and accrue interest
    /// @return reserve0 The LP's reserve0
    /// @return reserve1 The LP's reserve1
    /// @return pairTotalSupply The LP's totalSupply()
    function _addInterest() internal returns (uint112 reserve0, uint112 reserve1, uint256 pairTotalSupply) {
        // We need to call sync for Fraxswap pairs first to execute TWAMMs
        pair.sync();

        // Get the total supply and the updated reserves
        (reserve0, reserve1, ) = pair.getReserves();
        pairTotalSupply = pair.totalSupply();
        pairTotalSupply += _calcMintedSupplyFromPairMintFee(reserve0, reserve1, pairTotalSupply);

        // Calculate and accumulate interest if time has passed
        uint256 period = block.timestamp - timeSinceLastInterestPayment;
        if (period > 0) {
            // If there are outstanding rents, proceed
            if (sqrtRented > 0) {
                // Do the interest calculations
                uint256 balance = pair.balanceOf(address(this));
                uint256 sqrtBalance = Math.sqrt(
                    ((balance * reserve0) / pairTotalSupply) * ((balance * reserve1) / pairTotalSupply)
                );
                uint256 sqrtRentedReal = (uint256(sqrtRented) * rentedMultiplier) / PRECISION;
                uint256 utilityRate = (uint256(sqrtRentedReal) * PRECISION) / (sqrtBalance + sqrtRentedReal);

                uint256 interestRate = _getVariableInterestRate(period, utilityRate);
                uint256 sqrtInterest = (interestRate * period * uint256(sqrtRented)) / (PRECISION);

                // Update the rentedMultiplier
                // The original lender will get more LP back as their "earnings" when they redeem their BAMM tokens
                rentedMultiplier = (rentedMultiplier * (sqrtInterest + uint256(sqrtRented))) / uint256(sqrtRented);

                // Give the fee recipient their cut of the fee, directly as BAMM tokens
                {
                    address feeTo = IBAMMFactory(factory).feeTo();
                    if (feeTo != address(0)) {
                        // accrue fee
                        uint256 fee = (sqrtInterest * FEE_SHARE) / 10_000;
                        uint256 feeMintAmount = (fee * iBammErc20.totalSupply()) /
                            (sqrtBalance + ((uint256(sqrtRented) * rentedMultiplier) / PRECISION));
                        iBammErc20.mint(feeTo, feeMintAmount);
                    }
                }
            }

            // Update the timeSinceLastInterestPayment
            timeSinceLastInterestPayment = block.timestamp;
        }
    }

    function _isValidVault(Vault memory vault) internal pure returns (bool) {
        if (vault.rented < 0 || vault.token0 < 0 || vault.token1 < 0) {
            // A vault should never end with negative balances
            return false;
        } else if (vault.rented > 0 && (vault.token0 == 0 || vault.token1 == 0)) {
            // If a vault has outstanding rent, both token0 and token1 must not be 0
            return false;
        }
        return true;
    }

    function ltv(address user) external view returns (uint256) {
        Vault memory vault = userVaults[user];
        return ltv(vault);
    }

    function ltv(Vault memory vault) public view returns (uint256) {
        return (uint256(vault.rented) * rentedMultiplier) / Math.sqrt(uint256(vault.token0 * vault.token1));
    }

    /// @notice Is the vault solvent?
    /// @param vault The vault to check
    /// @return bool If the vault is solvent
    function _solvent(Vault memory vault, uint256 solvencyThreshold) internal view returns (bool) {
        return _isValidVault(vault) && (vault.rented == 0 || ltv(vault) < solvencyThreshold);
    }

    /// @dev approximate: does not sync to execute TWAMM orders - max utility may differ from this value
    /// @dev does not require staticcall
    function currentUtilityRate() public view returns (uint256) {
        (uint112 reserve0, uint112 reserve1, ) = pair.getReserves();
        uint256 pairTotalSupply = pair.totalSupply();

        return _currentUtilityRate({ reserve0: reserve0, reserve1: reserve1, pairTotalSupply: pairTotalSupply });
    }

    /// @param reserve0 The LP's reserve0
    /// @param reserve1 The LP's reserve1
    /// @param pairTotalSupply The LP's totalSupply
    function _currentUtilityRate(
        uint112 reserve0,
        uint112 reserve1,
        uint256 pairTotalSupply
    ) internal view returns (uint256) {
        if (sqrtRented == 0) {
            return 0;
        }

        uint256 balance = pair.balanceOf(address(this));
        uint256 sqrtBalance = Math.sqrt(
            ((balance * reserve0) / pairTotalSupply) * ((balance * reserve1) / pairTotalSupply)
        );
        uint256 sqrtRentedReal = (uint256(sqrtRented) * rentedMultiplier) / PRECISION;
        uint256 utilityRate = (uint256(sqrtRentedReal) * PRECISION) / (sqrtBalance + sqrtRentedReal);
        return utilityRate;
    }

    /// @dev Returns true if 0 <= {all outstanding rent} < MAX_UTILITY_RATE
    function _isValidUtilityRate(
        uint112 reserve0,
        uint112 reserve1,
        uint256 pairTotalSupply
    ) internal view returns (bool) {
        if (sqrtRented < 0) {
            return false;
        }
        if (
            _currentUtilityRate({ reserve0: reserve0, reserve1: reserve1, pairTotalSupply: pairTotalSupply }) >
            MAX_UTILITY_RATE
        ) {
            return false;
        }
        return true;
    }

    /// @notice Compare the spot price from the reserves to the oracle price. Revert if they are off by too much.
    /// @param reserve0 The LP's reserve0
    /// @param reserve1 The LP's reserve1
    function ammPriceCheck(uint112 reserve0, uint112 reserve1) internal view {
        // 30 minutes and max 1024 blocks
        (uint256 result0, uint256 result1) = fraxswapOracle.getPrice({
            pool: pair,
            period: 60 * 30,
            rounds: 10,
            maxDiffPerc: 10_000
        });
        result0 = 1e68 / result0;
        uint256 spotPrice = (uint256(reserve0) * 1e34) / reserve1;

        // Check the price differences and revert if they are too much
        uint256 diff = (spotPrice > result0 ? spotPrice - result0 : result0 - spotPrice);
        if ((diff * 10_000) / result0 > 500) {
            revert OraclePriceDeviated();
        }
        diff = (spotPrice > result1 ? spotPrice - result1 : result1 - spotPrice);
        if ((diff * 10_000) / result1 > 500) {
            revert OraclePriceDeviated();
        }
    }

    function _lpTokenToSqrtAmount(
        uint256 lpTokens,
        uint256 pairTotalSupply,
        uint256 reserve0,
        uint256 reserve1
    ) internal pure returns (uint256 sqrtAmount) {
        uint256 K = reserve0 * reserve1;
        if (K < 2 ** 140) sqrtAmount = Math.sqrt((((K * lpTokens) / pairTotalSupply) * lpTokens) / pairTotalSupply);
        else sqrtAmount = (Math.sqrt(K) * lpTokens) / pairTotalSupply;
    }

    // errors
    /// @notice Emitted when attempting to withdraw a vault tokens to the BAMM

    error CannotWithdrawToSelf();
    error InsufficientAmount();
    error ZeroLiquidityMinted();
    error NotSolvent();
    error Solvent();
    error IncorrectSwapTokens();
    error InvalidVault();
    error InvalidUtilityRate();
    error OraclePriceDeviated();
}

//                          .,,.
//               ,;;<!;;;,'``<!!!!;,
//            =c,`<!!!!!!!!!>;``<!!!!>,
//         ,zcc;$$c`'!!!!!!!!!,;`<!!!!!>
//         .  $$$;F?b`!'!!!!!!!,    ;!!!!>
//      ;!; `",,,`"b " ;!!!!!!!!    .!!!!!!;
//     ;!>>;;  r'  :<!!!!!!!''''```,,,,,,,,,,,,.
//     ;!>;!>; ""):!```.,,,nmMMb`'!!!!!!!!!!!!!!!!!!!!!'''`,,,,;;;
//    <!!;;;;;''.,,ndMr'4MMMMMMMMb,``'''''''''''''',,;;<!!!!!!!!'
//   !!!'''''. "TMMMMMPJ,)MMMMMMMMMMMMMMMMMnmnmdM !!!!!!!!!!!!'
//   `.,nMbmnm $e."MMM J$ MMMMMMMMMMMMMMMMMMMMMP  `!!!!!!!''
//   .MMMMMMMM>$$$b 4 c$$>4MMMMMMM?MMMMM"MMM4M",M
//    4MMMMMMM>$$$P   "?$>,MMMMMP,dMMM",;M",",nMM
//    'MMMMMMM $$Ez$$$$$$>JMMM",MMMP .' .c nMMMMM
//     4Mf4MMP $$$$$$$$P"uP",uP"",zdc,'$$F;MMMfP
//      "M'MM d$$",="=,cccccc$$$$$$$$$$$P MMM"
//      \/\"f.$$$cb  ,b$$$$$$$" -."?$$$$ dP)"
//      `$c, $$$$$$$$$$",,,,"$$   "J$$$'J" ,c
//       `"$ $$$$$$P)3$ccd$,,$$$$$$$$$'',z$$F
//           `$$$$$$$`?$$$$$$"$$$$$$$P,c$P"
//             "?$$$$;=,""',c$$$$$$$"
//                `"??bc,,z$$$$PF""
//     .,,,,,,,,.    4c,,,,,
//  4$$$$$$$$$$$??$bd$$$$$P";!' ccd$$PF"  c,
//  4$$$$$$$$$P.d$$$$$?$P"<!! z$$$P",c$$$$$$$b.
//  `$$c,""??".$$$$$?4P';!!! J$$P'z$$$$$$$$$$P"
//   `?$$$$L z$$$$$$ C ,<!! $$$"J$$$?$$$PF"""
//    `?$$$".$$$$$$$F ;!!! zP" J$$$$-;;;
//     ,$$%z$$$$$$$";!!!' d$L`z?$?$" <!';
//  ..'$$"-",nr"$" !!!!! $$$$;3L?c"? `<>`;
//   "C": \'MMM ";!!!!!'<$$$$$        !! <;
//     <`.dMMT4bn`.!';! ???$$F        !!! <>
//    !!>;`T",;- !! emudMMb.??        <!!! <>
//   !<!!!!,,`''!!! `TMMMP",!!!>      !!!!!.`!
//    !!!!!!!!!>.`'!`:MMM.<!!!!       !!!!!!>`!;
//   !!!!!!`<!!!!!;,,`TT" <!!!,      ;!'.`'!!! <>
//  '!''<! ,.`!!!``!!!!'`!!! '!      !! <!:`'!!.`!;
//  '      ?",`! dc''`,r;`,-  `     ;!!!`!!!;`!!:`!>
//    cbccc$$$$c$$$bd$$bcd          `!!! <;'!;`!! !!>
//   <$$$$$$$$$$$$$?)$$P"            `!!! <! ! !!>`!!
//   d$$$$$$P$$?????""                `!!> !> ,!!',!!
// .$$$$$$   cccc$$$                   `!!>`!!!!! !!!
//  "$C" ",d$$$$$$$$                    `!!:`!!!! !!!
//      ` `,c$$$$""                       <!!;,,,<!!!
//                                         `!!!!!'`
//                                           `

// ------------------------------------------------
// https://asciiart.website/index.php?art=cartoons/flintstones

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
library SSTORE2 {
    uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called.

    /*//////////////////////////////////////////////////////////////
                               WRITE LOGIC
    //////////////////////////////////////////////////////////////*/

    function write(bytes memory data) internal returns (address pointer) {
        // Prefix the bytecode with a STOP opcode to ensure it cannot be called.
        bytes memory runtimeCode = abi.encodePacked(hex"00", data);

        bytes memory creationCode = abi.encodePacked(
            //---------------------------------------------------------------------------------------------------------------//
            // Opcode  | Opcode + Arguments  | Description  | Stack View                                                     //
            //---------------------------------------------------------------------------------------------------------------//
            // 0x60    |  0x600B             | PUSH1 11     | codeOffset                                                     //
            // 0x59    |  0x59               | MSIZE        | 0 codeOffset                                                   //
            // 0x81    |  0x81               | DUP2         | codeOffset 0 codeOffset                                        //
            // 0x38    |  0x38               | CODESIZE     | codeSize codeOffset 0 codeOffset                               //
            // 0x03    |  0x03               | SUB          | (codeSize - codeOffset) 0 codeOffset                           //
            // 0x80    |  0x80               | DUP          | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset   //
            // 0x92    |  0x92               | SWAP3        | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset)   //
            // 0x59    |  0x59               | MSIZE        | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
            // 0x39    |  0x39               | CODECOPY     | 0 (codeSize - codeOffset)                                      //
            // 0xf3    |  0xf3               | RETURN       |                                                                //
            //---------------------------------------------------------------------------------------------------------------//
            hex"60_0B_59_81_38_03_80_92_59_39_F3", // Returns all code in the contract except for the first 11 (0B in hex) bytes.
            runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit.
        );

        assembly {
            // Deploy a new contract with the generated creation code.
            // We start 32 bytes into the code to avoid copying the byte length.
            pointer := create(0, add(creationCode, 32), mload(creationCode))
        }

        require(pointer != address(0), "DEPLOYMENT_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                               READ LOGIC
    //////////////////////////////////////////////////////////////*/

    function read(address pointer) internal view returns (bytes memory) {
        return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);
    }

    function read(address pointer, uint256 start) internal view returns (bytes memory) {
        start += DATA_OFFSET;

        return readBytecode(pointer, start, pointer.code.length - start);
    }

    function read(
        address pointer,
        uint256 start,
        uint256 end
    ) internal view returns (bytes memory) {
        start += DATA_OFFSET;
        end += DATA_OFFSET;

        require(pointer.code.length >= end, "OUT_OF_BOUNDS");

        return readBytecode(pointer, start, end - start);
    }

    /*//////////////////////////////////////////////////////////////
                          INTERNAL HELPER LOGIC
    //////////////////////////////////////////////////////////////*/

    function readBytecode(
        address pointer,
        uint256 start,
        uint256 size
    ) private view returns (bytes memory data) {
        assembly {
            // Get a pointer to some free memory.
            data := mload(0x40)

            // Update the free memory pointer to prevent overriding our data.
            // We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)).
            // Adding 31 to size and running the result through the logic above ensures
            // the memory pointer remains word-aligned, following the Solidity convention.
            mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))

            // Store the size of the data in the first 32 byte chunk of free memory.
            mstore(data, size)

            // Copy the code into memory right after the 32 bytes we used to store the size.
            extcodecopy(pointer, add(data, 32), start, size)
        }
    }
}

// SPDX-License-Identifier: Unlicense
/*
 * @title Solidity Bytes Arrays Utils
 * @author Gonçalo Sá <[email protected]>
 *
 * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
 *      The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
 */
pragma solidity >=0.8.0 <0.9.0;


library BytesLib {
    function concat(
        bytes memory _preBytes,
        bytes memory _postBytes
    )
        internal
        pure
        returns (bytes memory)
    {
        bytes memory tempBytes;

        assembly {
            // Get a location of some free memory and store it in tempBytes as
            // Solidity does for memory variables.
            tempBytes := mload(0x40)

            // Store the length of the first bytes array at the beginning of
            // the memory for tempBytes.
            let length := mload(_preBytes)
            mstore(tempBytes, length)

            // Maintain a memory counter for the current write location in the
            // temp bytes array by adding the 32 bytes for the array length to
            // the starting location.
            let mc := add(tempBytes, 0x20)
            // Stop copying when the memory counter reaches the length of the
            // first bytes array.
            let end := add(mc, length)

            for {
                // Initialize a copy counter to the start of the _preBytes data,
                // 32 bytes into its memory.
                let cc := add(_preBytes, 0x20)
            } lt(mc, end) {
                // Increase both counters by 32 bytes each iteration.
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                // Write the _preBytes data into the tempBytes memory 32 bytes
                // at a time.
                mstore(mc, mload(cc))
            }

            // Add the length of _postBytes to the current length of tempBytes
            // and store it as the new length in the first 32 bytes of the
            // tempBytes memory.
            length := mload(_postBytes)
            mstore(tempBytes, add(length, mload(tempBytes)))

            // Move the memory counter back from a multiple of 0x20 to the
            // actual end of the _preBytes data.
            mc := end
            // Stop copying when the memory counter reaches the new combined
            // length of the arrays.
            end := add(mc, length)

            for {
                let cc := add(_postBytes, 0x20)
            } lt(mc, end) {
                mc := add(mc, 0x20)
                cc := add(cc, 0x20)
            } {
                mstore(mc, mload(cc))
            }

            // Update the free-memory pointer by padding our last write location
            // to 32 bytes: add 31 bytes to the end of tempBytes to move to the
            // next 32 byte block, then round down to the nearest multiple of
            // 32. If the sum of the length of the two arrays is zero then add
            // one before rounding down to leave a blank 32 bytes (the length block with 0).
            mstore(0x40, and(
              add(add(end, iszero(add(length, mload(_preBytes)))), 31),
              not(31) // Round down to the nearest 32 bytes.
            ))
        }

        return tempBytes;
    }

    function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
        assembly {
            // Read the first 32 bytes of _preBytes storage, which is the length
            // of the array. (We don't need to use the offset into the slot
            // because arrays use the entire slot.)
            let fslot := sload(_preBytes.slot)
            // Arrays of 31 bytes or less have an even value in their slot,
            // while longer arrays have an odd value. The actual length is
            // the slot divided by two for odd values, and the lowest order
            // byte divided by two for even values.
            // If the slot is even, bitwise and the slot with 255 and divide by
            // two to get the length. If the slot is odd, bitwise and the slot
            // with -1 and divide by two.
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)
            let newlength := add(slength, mlength)
            // slength can contain both the length and contents of the array
            // if length < 32 bytes so let's prepare for that
            // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
            switch add(lt(slength, 32), lt(newlength, 32))
            case 2 {
                // Since the new array still fits in the slot, we just need to
                // update the contents of the slot.
                // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
                sstore(
                    _preBytes.slot,
                    // all the modifications to the slot are inside this
                    // next block
                    add(
                        // we can just add to the slot contents because the
                        // bytes we want to change are the LSBs
                        fslot,
                        add(
                            mul(
                                div(
                                    // load the bytes from memory
                                    mload(add(_postBytes, 0x20)),
                                    // zero all bytes to the right
                                    exp(0x100, sub(32, mlength))
                                ),
                                // and now shift left the number of bytes to
                                // leave space for the length in the slot
                                exp(0x100, sub(32, newlength))
                            ),
                            // increase length by the double of the memory
                            // bytes length
                            mul(mlength, 2)
                        )
                    )
                )
            }
            case 1 {
                // The stored value fits in the slot, but the combined value
                // will exceed it.
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // The contents of the _postBytes array start 32 bytes into
                // the structure. Our first read should obtain the `submod`
                // bytes that can fit into the unused space in the last word
                // of the stored array. To get this, we read 32 bytes starting
                // from `submod`, so the data we read overlaps with the array
                // contents by `submod` bytes. Masking the lowest-order
                // `submod` bytes allows us to add that value directly to the
                // stored value.

                let submod := sub(32, slength)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(
                    sc,
                    add(
                        and(
                            fslot,
                            0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
                        ),
                        and(mload(mc), mask)
                    )
                )

                for {
                    mc := add(mc, 0x20)
                    sc := add(sc, 1)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } {
                    sstore(sc, mload(mc))
                }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
            default {
                // get the keccak hash to get the contents of the array
                mstore(0x0, _preBytes.slot)
                // Start copying to the last used word of the stored array.
                let sc := add(keccak256(0x0, 0x20), div(slength, 32))

                // save new length
                sstore(_preBytes.slot, add(mul(newlength, 2), 1))

                // Copy over the first `submod` bytes of the new data as in
                // case 1 above.
                let slengthmod := mod(slength, 32)
                let mlengthmod := mod(mlength, 32)
                let submod := sub(32, slengthmod)
                let mc := add(_postBytes, submod)
                let end := add(_postBytes, mlength)
                let mask := sub(exp(0x100, submod), 1)

                sstore(sc, add(sload(sc), and(mload(mc), mask)))

                for {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } lt(mc, end) {
                    sc := add(sc, 1)
                    mc := add(mc, 0x20)
                } {
                    sstore(sc, mload(mc))
                }

                mask := exp(0x100, sub(mc, end))

                sstore(sc, mul(div(mload(mc), mask), mask))
            }
        }
    }

    function slice(
        bytes memory _bytes,
        uint256 _start,
        uint256 _length
    )
        internal
        pure
        returns (bytes memory)
    {
        require(_length + 31 >= _length, "slice_overflow");
        require(_bytes.length >= _start + _length, "slice_outOfBounds");

        bytes memory tempBytes;

        assembly {
            switch iszero(_length)
            case 0 {
                // Get a location of some free memory and store it in tempBytes as
                // Solidity does for memory variables.
                tempBytes := mload(0x40)

                // The first word of the slice result is potentially a partial
                // word read from the original array. To read it, we calculate
                // the length of that partial word and start copying that many
                // bytes into the array. The first word we copy will start with
                // data we don't care about, but the last `lengthmod` bytes will
                // land at the beginning of the contents of the new array. When
                // we're done copying, we overwrite the full first word with
                // the actual length of the slice.
                let lengthmod := and(_length, 31)

                // The multiplication in the next line is necessary
                // because when slicing multiples of 32 bytes (lengthmod == 0)
                // the following copy loop was copying the origin's length
                // and then ending prematurely not copying everything it should.
                let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
                let end := add(mc, _length)

                for {
                    // The multiplication in the next line has the same exact purpose
                    // as the one above.
                    let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
                } lt(mc, end) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    mstore(mc, mload(cc))
                }

                mstore(tempBytes, _length)

                //update free-memory pointer
                //allocating the array padded to 32 bytes like the compiler does now
                mstore(0x40, and(add(mc, 31), not(31)))
            }
            //if we want a zero-length slice let's just return a zero-length array
            default {
                tempBytes := mload(0x40)
                //zero out the 32 bytes slice we are about to return
                //we need to do it because Solidity does not garbage collect
                mstore(tempBytes, 0)

                mstore(0x40, add(tempBytes, 0x20))
            }
        }

        return tempBytes;
    }

    function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
        require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
        address tempAddress;

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

        return tempAddress;
    }

    function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
        require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
        uint8 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x1), _start))
        }

        return tempUint;
    }

    function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {
        require(_bytes.length >= _start + 2, "toUint16_outOfBounds");
        uint16 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x2), _start))
        }

        return tempUint;
    }

    function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {
        require(_bytes.length >= _start + 4, "toUint32_outOfBounds");
        uint32 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x4), _start))
        }

        return tempUint;
    }

    function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {
        require(_bytes.length >= _start + 8, "toUint64_outOfBounds");
        uint64 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x8), _start))
        }

        return tempUint;
    }

    function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {
        require(_bytes.length >= _start + 12, "toUint96_outOfBounds");
        uint96 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0xc), _start))
        }

        return tempUint;
    }

    function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {
        require(_bytes.length >= _start + 16, "toUint128_outOfBounds");
        uint128 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x10), _start))
        }

        return tempUint;
    }

    function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
        require(_bytes.length >= _start + 32, "toUint256_outOfBounds");
        uint256 tempUint;

        assembly {
            tempUint := mload(add(add(_bytes, 0x20), _start))
        }

        return tempUint;
    }

    function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
        require(_bytes.length >= _start + 32, "toBytes32_outOfBounds");
        bytes32 tempBytes32;

        assembly {
            tempBytes32 := mload(add(add(_bytes, 0x20), _start))
        }

        return tempBytes32;
    }

    function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
        bool success = true;

        assembly {
            let length := mload(_preBytes)

            // if lengths don't match the arrays are not equal
            switch eq(length, mload(_postBytes))
            case 1 {
                // cb is a circuit breaker in the for loop since there's
                //  no said feature for inline assembly loops
                // cb = 1 - don't breaker
                // cb = 0 - break
                let cb := 1

                let mc := add(_preBytes, 0x20)
                let end := add(mc, length)

                for {
                    let cc := add(_postBytes, 0x20)
                // the next line is the loop condition:
                // while(uint256(mc < end) + cb == 2)
                } eq(add(lt(mc, end), cb), 2) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    // if any of these checks fails then arrays are not equal
                    if iszero(eq(mload(mc), mload(cc))) {
                        // unsuccess:
                        success := 0
                        cb := 0
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }

    function equal_nonAligned(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
        bool success = true;

        assembly {
            let length := mload(_preBytes)

            // if lengths don't match the arrays are not equal
            switch eq(length, mload(_postBytes))
            case 1 {
                // cb is a circuit breaker in the for loop since there's
                //  no said feature for inline assembly loops
                // cb = 1 - don't breaker
                // cb = 0 - break
                let cb := 1

                let endMinusWord := add(_preBytes, length)
                let mc := add(_preBytes, 0x20)
                let cc := add(_postBytes, 0x20)

                for {
                // the next line is the loop condition:
                // while(uint256(mc < endWord) + cb == 2)
                } eq(add(lt(mc, endMinusWord), cb), 2) {
                    mc := add(mc, 0x20)
                    cc := add(cc, 0x20)
                } {
                    // if any of these checks fails then arrays are not equal
                    if iszero(eq(mload(mc), mload(cc))) {
                        // unsuccess:
                        success := 0
                        cb := 0
                    }
                }

                // Only if still successful
                // For <1 word tail bytes
                if gt(success, 0) {
                    // Get the remainder of length/32
                    // length % 32 = AND(length, 32 - 1)
                    let numTailBytes := and(length, 0x1f)
                    let mcRem := mload(mc)
                    let ccRem := mload(cc)
                    for {
                        let i := 0
                    // the next line is the loop condition:
                    // while(uint256(i < numTailBytes) + cb == 2)
                    } eq(add(lt(i, numTailBytes), cb), 2) {
                        i := add(i, 1)
                    } {
                        if iszero(eq(byte(i, mcRem), byte(i, ccRem))) {
                            // unsuccess:
                            success := 0
                            cb := 0
                        }
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }

    function equalStorage(
        bytes storage _preBytes,
        bytes memory _postBytes
    )
        internal
        view
        returns (bool)
    {
        bool success = true;

        assembly {
            // we know _preBytes_offset is 0
            let fslot := sload(_preBytes.slot)
            // Decode the length of the stored array like in concatStorage().
            let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
            let mlength := mload(_postBytes)

            // if lengths don't match the arrays are not equal
            switch eq(slength, mlength)
            case 1 {
                // slength can contain both the length and contents of the array
                // if length < 32 bytes so let's prepare for that
                // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
                if iszero(iszero(slength)) {
                    switch lt(slength, 32)
                    case 1 {
                        // blank the last byte which is the length
                        fslot := mul(div(fslot, 0x100), 0x100)

                        if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
                            // unsuccess:
                            success := 0
                        }
                    }
                    default {
                        // cb is a circuit breaker in the for loop since there's
                        //  no said feature for inline assembly loops
                        // cb = 1 - don't breaker
                        // cb = 0 - break
                        let cb := 1

                        // get the keccak hash to get the contents of the array
                        mstore(0x0, _preBytes.slot)
                        let sc := keccak256(0x0, 0x20)

                        let mc := add(_postBytes, 0x20)
                        let end := add(mc, mlength)

                        // the next line is the loop condition:
                        // while(uint256(mc < end) + cb == 2)
                        for {} eq(add(lt(mc, end), cb), 2) {
                            sc := add(sc, 1)
                            mc := add(mc, 0x20)
                        } {
                            if iszero(eq(sload(sc), mload(mc))) {
                                // unsuccess:
                                success := 0
                                cb := 0
                            }
                        }
                    }
                }
            }
            default {
                // unsuccess:
                success := 0
            }
        }

        return success;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

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

pragma solidity ^0.8.20;

/**
 * @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 Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._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 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._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() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @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 {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

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

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

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

pragma solidity ^0.8.0;

import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";

interface IFraxswapFactory is IUniswapV2Factory {
    function createPair(address tokenA, address tokenB, uint256 fee) external returns (address pair);
    function globalPause() external view returns (bool);
    function toggleGlobalPause() external;
}

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

import { IUniswapV2Pair } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";

/// @dev Fraxswap LP Pair Interface
interface IFraxswapPair is IUniswapV2Pair {
    // TWAMM
    struct TWAPObservation {
        uint256 timestamp;
        uint256 price0CumulativeLast;
        uint256 price1CumulativeLast;
    }

    function TWAPObservationHistory(uint256 index) external view returns (TWAPObservation memory);

    event LongTermSwap0To1(address indexed addr, uint256 orderId, uint256 amount0In, uint256 numberOfTimeIntervals);
    event LongTermSwap1To0(address indexed addr, uint256 orderId, uint256 amount1In, uint256 numberOfTimeIntervals);
    event CancelLongTermOrder(
        address indexed addr,
        uint256 orderId,
        address sellToken,
        uint256 unsoldAmount,
        address buyToken,
        uint256 purchasedAmount
    );
    event WithdrawProceedsFromLongTermOrder(
        address indexed addr,
        uint256 orderId,
        address indexed proceedToken,
        uint256 proceeds,
        bool orderExpired
    );

    function fee() external view returns (uint256);

    function longTermSwapFrom0To1(uint256 amount0In, uint256 numberOfTimeIntervals) external returns (uint256 orderId);
    function longTermSwapFrom1To0(uint256 amount1In, uint256 numberOfTimeIntervals) external returns (uint256 orderId);
    function cancelLongTermSwap(uint256 orderId) external;
    function withdrawProceedsFromLongTermSwap(
        uint256 orderId
    ) external returns (bool is_expired, address rewardTkn, uint256 totalReward);
    function executeVirtualOrders(uint256 blockTimestamp) external;

    function getAmountOut(uint256 amountIn, address tokenIn) external view returns (uint256);
    function getAmountIn(uint256 amountOut, address tokenOut) external view returns (uint256);

    function orderTimeInterval() external returns (uint256);
    function getTWAPHistoryLength() external view returns (uint256);
    function getTwammReserves()
        external
        view
        returns (
            uint112 _reserve0,
            uint112 _reserve1,
            uint32 _blockTimestampLast,
            uint112 _twammReserve0,
            uint112 _twammReserve1,
            uint256 _fee
        );
    function getReserveAfterTwamm(
        uint256 blockTimestamp
    )
        external
        view
        returns (
            uint112 _reserve0,
            uint112 _reserve1,
            uint256 lastVirtualOrderTimestamp,
            uint112 _twammReserve0,
            uint112 _twammReserve1
        );
    function getNextOrderID() external view returns (uint256);
    function getOrderIDsForUser(address user) external view returns (uint256[] memory);
    function getOrderIDsForUserLength(address user) external view returns (uint256);
    function twammUpToDate() external view returns (bool);
    function getTwammState()
        external
        view
        returns (
            uint256 token0Rate,
            uint256 token1Rate,
            uint256 lastVirtualOrderTimestamp,
            uint256 orderTimeInterval_rtn,
            uint256 rewardFactorPool0,
            uint256 rewardFactorPool1
        );
    function getTwammSalesRateEnding(
        uint256 _blockTimestamp
    ) external view returns (uint256 orderPool0SalesRateEnding, uint256 orderPool1SalesRateEnding);
    function getTwammRewardFactor(
        uint256 _blockTimestamp
    ) external view returns (uint256 rewardFactorPool0AtTimestamp, uint256 rewardFactorPool1AtTimestamp);
    function getTwammOrder(
        uint256 orderId
    )
        external
        view
        returns (
            uint256 id,
            uint256 creationTimestamp,
            uint256 expirationTimestamp,
            uint256 saleRate,
            address owner,
            address sellTokenAddr,
            address buyTokenAddr
        );
    function getTwammOrderProceedsView(
        uint256 orderId,
        uint256 blockTimestamp
    ) external view returns (bool orderExpired, uint256 totalReward);
    function getTwammOrderProceeds(uint256 orderId) external returns (bool orderExpired, uint256 totalReward);

    function togglePauseNewSwaps() external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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

pragma solidity ^0.8.20;

/**
 * @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.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
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].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

File 13 of 37 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }
}

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../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 An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @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.encodeCall(token.approve, (spender, value));

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

    /**
     * @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);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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(token).code.length > 0;
    }
}

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

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

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @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), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(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) {
        uint256 localValue = value;
        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] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        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 bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

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

interface IFraxswapRouterMultihop {
    /// @notice Input to the swap function
    /// @dev contains the top level info for the swap
    /// @param tokenIn input token address
    /// @param amountIn input token amount
    /// @param tokenOut output token address
    /// @param amountOutMinimum output token minimum amount (reverts if lower)
    /// @param recipient recipient of the output token
    /// @param deadline deadline for this swap transaction (reverts if exceeded)
    /// @param v v value for permit signature if supported
    /// @param r r value for permit signature if supported
    /// @param s s value for permit signature if supported
    /// @param route byte encoded
    struct FraxswapParams {
        address tokenIn;
        uint256 amountIn;
        address tokenOut;
        uint256 amountOutMinimum;
        address recipient;
        uint256 deadline;
        bool approveMax;
        uint8 v;
        bytes32 r;
        bytes32 s;
        bytes route;
    }

    /// @notice A hop along the swap route
    /// @dev a series of swaps (steps) containing the same input token and output token
    /// @param tokenOut output token address
    /// @param amountOut output token amount
    /// @param percentOfHop amount of output tokens from the previous hop going into this hop
    /// @param steps list of swaps from the same input token to the same output token
    /// @param nextHops next hops from this one, the next hops' input token is the tokenOut
    struct FraxswapRoute {
        address tokenOut;
        uint256 amountOut;
        uint256 percentOfHop;
        bytes[] steps;
        bytes[] nextHops;
    }

    /// @notice A swap step in a specific route. routes can have multiple swap steps
    /// @dev a single swap to a token from the token of the previous hop in the route
    /// @param swapType type of the swap performed (Uniswap V2, Fraxswap,Curve, etc)
    /// @param directFundNextPool 0 = funds go via router, 1 = fund are sent directly to pool
    /// @param directFundThisPool 0 = funds go via router, 1 = fund are sent directly to pool
    /// @param tokenOut the target token of the step. output token address
    /// @param pool address of the pool to use in the step
    /// @param extraParam1 extra data used in the step
    /// @param extraParam2 extra data used in the step
    /// @param percentOfHop percentage of all of the steps in this route (hop)
    struct FraxswapStepData {
        uint8 swapType;
        uint8 directFundNextPool;
        uint8 directFundThisPool;
        address tokenOut;
        address pool;
        uint256 extraParam1;
        uint256 extraParam2;
        uint256 percentOfHop;
    }

    /// @notice struct for Uniswap V3 callback
    /// @param tokenIn address of input token
    /// @param directFundThisPool this pool already been funded
    struct SwapCallbackData {
        address tokenIn;
        bool directFundThisPool;
    }

    /// @notice Routing event emitted every swap
    /// @param tokenIn address of the original input token
    /// @param tokenOut address of the final output token
    /// @param amountIn input amount for original input token
    /// @param amountOut output amount for the final output token
    event Routed(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);

    function encodeRoute(
        address tokenOut,
        uint256 percentOfHop,
        bytes[] memory steps,
        bytes[] memory nextHops
    ) external pure returns (bytes memory out);
    function encodeStep(
        uint8 swapType,
        uint8 directFundNextPool,
        uint8 directFundThisPool,
        address tokenOut,
        address pool,
        uint256 extraParam1,
        uint256 extraParam2,
        uint256 percentOfHop
    ) external pure returns (bytes memory out);
    function swap(FraxswapParams memory params) external payable returns (uint256 amountOut);
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes memory _data) external;
}

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

// a library for performing various math operations

library Math {
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        z = x < y ? x : y;
    }

    // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
    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;
        }
    }
}

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.19;

import { ERC20Permit, ERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

/// @dev supports OZ 5.0 interface
contract BAMMERC20 is ERC20Permit, Ownable {
    constructor(
        string memory name_,
        string memory symbol_
    ) ERC20(name_, symbol_) ERC20Permit(name_) Ownable(msg.sender) {}

    function mint(address account, uint256 value) external onlyOwner {
        _mint(account, value);
    }

    function burn(address account, uint256 value) external onlyOwner {
        _burn(account, value);
    }
}

// SPDX-License-Identifier: ISC
pragma solidity ^0.8.19;

// ====================================================================
// |     ______                   _______                             |
// |    / _____________ __  __   / ____(_____  ____ _____  ________   |
// |   / /_  / ___/ __ `| |/_/  / /_  / / __ \/ __ `/ __ \/ ___/ _ \  |
// |  / __/ / /  / /_/ _>  <   / __/ / / / / / /_/ / / / / /__/  __/  |
// | /_/   /_/   \__,_/_/|_|  /_/   /_/_/ /_/\__,_/_/ /_/\___/\___/   |
// |                                                                  |
// ====================================================================
// ====================== VariableInterestRate ========================
// ====================================================================

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { IRateCalculatorV2 } from "./interfaces/IRateCalculatorV2.sol";

/// @title A formula for calculating interest rates as a function of utilization and time
/// @author Frax Finance (https://github.com/FraxFinance)
/// @notice A Contract for calculating interest rates as a function of utilization and time
contract VariableInterestRate is IRateCalculatorV2 {
    using Strings for uint256;

    /// @notice The name suffix for the interest rate calculator
    string public suffix;

    // Utilization Settings
    /// @notice The minimum utilization wherein no adjustment to full utilization and vertex rates occurs
    uint256 public immutable MIN_TARGET_UTIL;
    /// @notice The maximum utilization wherein no adjustment to full utilization and vertex rates occurs
    uint256 public immutable MAX_TARGET_UTIL;
    /// @notice The utilization at which the slope increases
    uint256 public immutable VERTEX_UTILIZATION;
    /// @notice precision of utilization calculations
    uint256 public constant UTIL_PREC = 1e5; // 5 decimals

    // Interest Rate Settings (all rates are per second), 365.24 days per year
    /// @notice The minimum interest rate (per second) when utilization is 100%
    uint256 public immutable MIN_FULL_UTIL_RATE; // 18 decimals
    /// @notice The maximum interest rate (per second) when utilization is 100%
    uint256 public immutable MAX_FULL_UTIL_RATE; // 18 decimals
    /// @notice The interest rate (per second) when utilization is 0%
    uint256 public immutable ZERO_UTIL_RATE; // 18 decimals
    /// @notice The interest rate half life in seconds, determines rate of adjustments to rate curve
    uint256 public immutable RATE_HALF_LIFE; // 1 decimals
    /// @notice The percent of the delta between max and min
    uint256 public immutable VERTEX_RATE_PERCENT; // 18 decimals
    /// @notice The precision of interest rate calculations
    uint256 public constant RATE_PREC = 1e18; // 18 decimals

    error MaxUtilizationTooLow();
    error MaxFullUtilizationTooLow();
    error DivideByZero();
    error VertexUtilizationTooHigh();
    error UtilizationRateTooHigh();

    /// @param _suffix The suffix of the contract name
    /// @param _vertexUtilization The utilization at which the slope increases
    /// @param _vertexRatePercentOfDelta The percent of the delta between max and min, defines vertex rate
    /// @param _minUtil The minimum utilization wherein no adjustment to full utilization and vertex rates occurs
    /// @param _maxUtil The maximum utilization wherein no adjustment to full utilization and vertex rates occurs
    /// @param _zeroUtilizationRate The interest rate (per second) when utilization is 0%
    /// @param _minFullUtilizationRate The minimum interest rate at 100% utilization
    /// @param _maxFullUtilizationRate The maximum interest rate at 100% utilization
    /// @param _rateHalfLife The half life parameter for interest rate adjustments
    constructor(
        string memory _suffix,
        uint256 _vertexUtilization,
        uint256 _vertexRatePercentOfDelta,
        uint256 _minUtil,
        uint256 _maxUtil,
        uint256 _zeroUtilizationRate,
        uint256 _minFullUtilizationRate,
        uint256 _maxFullUtilizationRate,
        uint256 _rateHalfLife
    ) {
        if (_maxUtil <= _minUtil) {
            revert MaxUtilizationTooLow();
        }
        if (_maxFullUtilizationRate <= _minFullUtilizationRate) {
            revert MaxFullUtilizationTooLow();
        }

        if (_vertexUtilization > UTIL_PREC) {
            revert VertexUtilizationTooHigh();
        }

        if (
            _minUtil == 0 ||
            _rateHalfLife == 0 ||
            _vertexUtilization == 0 ||
            _vertexUtilization == UTIL_PREC ||
            _maxUtil == UTIL_PREC
        ) {
            revert DivideByZero();
        }

        if (_maxUtil > RATE_PREC || _maxFullUtilizationRate > RATE_PREC) {
            revert UtilizationRateTooHigh();
        }

        suffix = _suffix;
        MIN_TARGET_UTIL = _minUtil;
        MAX_TARGET_UTIL = _maxUtil;
        VERTEX_UTILIZATION = _vertexUtilization;
        ZERO_UTIL_RATE = _zeroUtilizationRate;
        MIN_FULL_UTIL_RATE = _minFullUtilizationRate;
        MAX_FULL_UTIL_RATE = _maxFullUtilizationRate;
        RATE_HALF_LIFE = _rateHalfLife;
        VERTEX_RATE_PERCENT = _vertexRatePercentOfDelta;
    }

    /// @notice The ```name``` function returns the name of the rate contract
    /// @return memory name of contract
    function name() external view returns (string memory) {
        return string(abi.encodePacked("Variable Rate V2 ", suffix));
    }

    /// @notice The ```version``` function returns the semantic version of the rate contract
    /// @dev Follows semantic versioning
    /// @return _major Major version
    /// @return _minor Minor version
    /// @return _patch Patch version
    function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
        _major = 2;
        _minor = 0;
        _patch = 0;
    }

    /// @notice The ```getFullUtilizationInterest``` function calculate the new maximum interest rate, i.e. rate when utilization is 100%
    /// @dev Given in interest per second
    /// @param _deltaTime The elapsed time since last update given in seconds
    /// @param _utilization The utilization %, given with 5 decimals of precision
    /// @param _fullUtilizationInterest The interest value when utilization is 100%, given with 18 decimals of precision
    /// @return _newFullUtilizationInterest The new maximum interest rate
    function getFullUtilizationInterest(
        uint256 _deltaTime,
        uint256 _utilization,
        uint64 _fullUtilizationInterest
    ) internal view returns (uint64 _newFullUtilizationInterest) {
        if (_utilization < MIN_TARGET_UTIL) {
            // 18 decimals
            uint256 _deltaUtilization = ((MIN_TARGET_UTIL - _utilization) * 1e18) / MIN_TARGET_UTIL;
            // 36 decimals
            uint256 _decayGrowth = (RATE_HALF_LIFE * 1e36) + (_deltaUtilization * _deltaUtilization * _deltaTime);
            // 18 decimals
            _newFullUtilizationInterest = uint64((_fullUtilizationInterest * (RATE_HALF_LIFE * 1e36)) / _decayGrowth);
        } else if (_utilization > MAX_TARGET_UTIL) {
            // 18 decimals
            uint256 _deltaUtilization = ((_utilization - MAX_TARGET_UTIL) * 1e18) / (UTIL_PREC - MAX_TARGET_UTIL);
            // 36 decimals
            uint256 _decayGrowth = (RATE_HALF_LIFE * 1e36) + (_deltaUtilization * _deltaUtilization * _deltaTime);
            // 18 decimals
            _newFullUtilizationInterest = uint64((_fullUtilizationInterest * _decayGrowth) / (RATE_HALF_LIFE * 1e36));
        } else {
            _newFullUtilizationInterest = _fullUtilizationInterest;
        }
        if (_newFullUtilizationInterest > MAX_FULL_UTIL_RATE) {
            _newFullUtilizationInterest = uint64(MAX_FULL_UTIL_RATE);
        } else if (_newFullUtilizationInterest < MIN_FULL_UTIL_RATE) {
            _newFullUtilizationInterest = uint64(MIN_FULL_UTIL_RATE);
        }
    }

    /// @notice The ```getNewRate``` function calculates interest rates using two linear functions f(utilization)
    /// @param _deltaTime The elapsed time since last update, given in seconds
    /// @param _utilization The utilization %, given with 5 decimals of precision
    /// @param _oldFullUtilizationInterest The interest value when utilization is 100%, given with 18 decimals of precision
    /// @return _newRatePerSec The new interest rate, 18 decimals of precision
    /// @return _newFullUtilizationInterest The new max interest rate, 18 decimals of precision
    function getNewRate(
        uint256 _deltaTime,
        uint256 _utilization,
        uint64 _oldFullUtilizationInterest
    ) external view returns (uint64 _newRatePerSec, uint64 _newFullUtilizationInterest) {
        _newFullUtilizationInterest = getFullUtilizationInterest(_deltaTime, _utilization, _oldFullUtilizationInterest);

        // _vertexInterest is calculated as the percentage of the delta between min and max interest
        uint256 _vertexInterest = (((_newFullUtilizationInterest - ZERO_UTIL_RATE) * VERTEX_RATE_PERCENT) / RATE_PREC) +
            ZERO_UTIL_RATE;
        if (_utilization < VERTEX_UTILIZATION) {
            // For readability, the following formula is equivalent to:
            // uint256 _slope = ((_vertexInterest - ZERO_UTIL_RATE) * UTIL_PREC) / VERTEX_UTILIZATION;
            // _newRatePerSec = uint64(ZERO_UTIL_RATE + ((_utilization * _slope) / UTIL_PREC));

            // 18 decimals
            _newRatePerSec = uint64(
                ZERO_UTIL_RATE + (_utilization * (_vertexInterest - ZERO_UTIL_RATE)) / VERTEX_UTILIZATION
            );
        } else {
            // For readability, the following formula is equivalent to:
            // uint256 _slope = (((_newFullUtilizationInterest - _vertexInterest) * UTIL_PREC) / (UTIL_PREC - VERTEX_UTILIZATION));
            // _newRatePerSec = uint64(_vertexInterest + (((_utilization - VERTEX_UTILIZATION) * _slope) / UTIL_PREC));

            // 18 decimals
            _newRatePerSec = uint64(
                _vertexInterest +
                    ((_utilization - VERTEX_UTILIZATION) * (_newFullUtilizationInterest - _vertexInterest)) /
                    (UTIL_PREC - VERTEX_UTILIZATION)
            );
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

pragma solidity >=0.5.0;

interface IUniswapV2Pair {
    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    function name() external pure returns (string memory);
    function symbol() external pure returns (string memory);
    function decimals() external pure returns (uint8);
    function totalSupply() external view returns (uint);
    function balanceOf(address owner) external view returns (uint);
    function allowance(address owner, address spender) external view returns (uint);

    function approve(address spender, uint value) external returns (bool);
    function transfer(address to, uint value) external returns (bool);
    function transferFrom(address from, address to, uint value) external returns (bool);

    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function PERMIT_TYPEHASH() external pure returns (bytes32);
    function nonces(address owner) external view returns (uint);

    function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;

    event Mint(address indexed sender, uint amount0, uint amount1);
    event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
    event Swap(
        address indexed sender,
        uint amount0In,
        uint amount1In,
        uint amount0Out,
        uint amount1Out,
        address indexed to
    );
    event Sync(uint112 reserve0, uint112 reserve1);

    function MINIMUM_LIQUIDITY() external pure returns (uint);
    function factory() external view returns (address);
    function token0() external view returns (address);
    function token1() external view returns (address);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() external view returns (uint);
    function kLast() external view returns (uint);

    function mint(address to) external returns (uint liquidity);
    function burn(address to) external returns (uint amount0, uint amount1);
    function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address) external;
}

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedInnerCall();

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) 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 FailedInnerCall();
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @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 towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (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 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                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.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 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.

            uint256 twos = denominator & (0 - denominator);
            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 (unsignedRoundsUp(rounding) && 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
     * towards zero.
     *
     * 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.20;

import {IERC20Permit} from "./IERC20Permit.sol";
import {ERC20} from "../ERC20.sol";
import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
import {EIP712} from "../../../utils/cryptography/EIP712.sol";
import {Nonces} from "../../../utils/Nonces.sol";

/**
 * @dev Implementation 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.
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
    bytes32 private constant PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Permit deadline has expired.
     */
    error ERC2612ExpiredSignature(uint256 deadline);

    /**
     * @dev Mismatched signature.
     */
    error ERC2612InvalidSigner(address signer, address owner);

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @inheritdoc IERC20Permit
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        if (block.timestamp > deadline) {
            revert ERC2612ExpiredSignature(deadline);
        }

        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        if (signer != owner) {
            revert ERC2612InvalidSigner(signer, owner);
        }

        _approve(owner, spender, value);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
        return super.nonces(owner);
    }

    /**
     * @inheritdoc IERC20Permit
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
        return _domainSeparatorV4();
    }
}

// SPDX-License-Identifier: ISC
pragma solidity ^0.8.19;

interface IRateCalculatorV2 {
    function name() external view returns (string memory);

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

    function getNewRate(
        uint256 _deltaTime,
        uint256 _utilization,
        uint64 _maxInterest
    ) external view returns (uint64 _newRatePerSec, uint64 _newMaxInterest);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     * ```
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

pragma solidity ^0.8.20;

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

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile 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 {MessageHashUtils-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]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        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, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile 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 {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        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]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            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.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // 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, s);
        }

        // 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, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @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, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

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

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its 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 order to
 * produce the hash of their typed data 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.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @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].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, 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 MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract Nonces {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return _nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

File 36 of 37 : IERC5267.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}

Settings
{
  "remappings": [
    "frax-std/=node_modules/frax-standard-solidity/src/",
    "@prb/test/=node_modules/@prb/test/",
    "forge-std/=node_modules/forge-std/src/",
    "ds-test/=node_modules/ds-test/src/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@rari-capital/=node_modules/@rari-capital/",
    "@uniswap/=node_modules/@uniswap/",
    "dev-fraxswap/=node_modules/dev-fraxswap/",
    "frax-standard-solidity/=node_modules/frax-standard-solidity/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "solmate/=node_modules/solmate/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": false
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "paris",
  "viaIR": false,
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_fraxswapFactory","type":"address"},{"internalType":"address","name":"_routerMultihop","type":"address"},{"internalType":"address","name":"_fraxswapOracle","type":"address"},{"internalType":"address","name":"_variableInterestRate","type":"address"},{"internalType":"address","name":"_feeTo","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"BammAlreadyCreated","type":"error"},{"inputs":[],"name":"Create2Failed","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PairNotFromFraxswapFactory","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"pair","type":"address"},{"indexed":false,"internalType":"address","name":"bamm","type":"address"}],"name":"BammCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"bamms","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bammsArray","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"bammsLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_pair","type":"address"}],"name":"createBamm","outputs":[{"internalType":"address","name":"bamm","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeTo","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fraxswapOracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"iFraxswapFactory","outputs":[{"internalType":"contract IFraxswapFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"bamm","type":"address"}],"name":"isBamm","outputs":[{"internalType":"bool","name":"exists","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"pair","type":"address"}],"name":"pairToBamm","outputs":[{"internalType":"address","name":"bamm","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"routerMultihop","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_creationCode","type":"bytes"}],"name":"setCreationCode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeTo","type":"address"}],"name":"setFeeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"variableInterestRate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"_major","type":"uint256"},{"internalType":"uint256","name":"_minor","type":"uint256"},{"internalType":"uint256","name":"_patch","type":"uint256"}],"stateMutability":"pure","type":"function"}]

61010060405234801561001157600080fd5b506040516113fe3803806113fe83398101604081905261003091610121565b338061005657604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b61005f81610099565b506001600160a01b0394851660805292841660a05290831660c052821660e052600780546001600160a01b03191691909216179055610186565b600180546001600160a01b03191690556100b2816100b5565b50565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80516001600160a01b038116811461011c57600080fd5b919050565b600080600080600060a0868803121561013957600080fd5b61014286610105565b945061015060208701610105565b935061015e60408701610105565b925061016c60608701610105565b915061017a60808701610105565b90509295509295909350565b60805160a05160c05160e0516112156101e96000396000818161028e01526109350152600081816101f00152818161090d0152610a0301526000818161025f015281816108e501526109db0152600081816101c9015261078601526112156000f3fe608060405234801561001057600080fd5b50600436106101515760003560e01c8063715018a6116100cd5780639a0bc2a911610081578063ef3bd76611610066578063ef3bd7661461031e578063f2fde38b14610331578063f46901ed1461034457600080fd5b80639a0bc2a9146102fc578063e30c39781461030d57600080fd5b806379ba5097116100b257806379ba5097146102b057806389439acf146102b85780638da5cb5b146102eb57600080fd5b8063715018a61461028157806378f3a8941461028957600080fd5b8063395db9ec116101245780635cd8d064116101095780635cd8d064146102325780636f4b49c11461024557806370dcf1631461025a57600080fd5b8063395db9ec146101eb57806354fd4d501461021257600080fd5b8063017e7e581461015657806306c75b6a1461018657806307be75f71461019b5780630feef4b1146101c4575b600080fd5b600754610169906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b610199610194366004610fa1565b610357565b005b6101696101a9366004611028565b6003602052600090815260409020546001600160a01b031681565b6101697f000000000000000000000000000000000000000000000000000000000000000081565b6101697f000000000000000000000000000000000000000000000000000000000000000081565b60408051600081526004602082015260019181019190915260600161017d565b61016961024036600461104c565b61058c565b61024d6105b6565b60405161017d9190611065565b6101697f000000000000000000000000000000000000000000000000000000000000000081565b610199610618565b6101697f000000000000000000000000000000000000000000000000000000000000000081565b61019961062c565b6102db6102c6366004611028565b60026020526000908152604090205460ff1681565b604051901515815260200161017d565b6000546001600160a01b0316610169565b60045460405190815260200161017d565b6001546001600160a01b0316610169565b61016961032c366004611028565b610675565b61019961033f366004611028565b610bd0565b610199610352366004611028565b610c41565b61035f610c6b565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000810460ff16159067ffffffffffffffff166000811580156103aa5750825b905060008267ffffffffffffffff1660011480156103c75750303b155b9050811580156103d5575080155b1561040c576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561044057845468ff00000000000000001916680100000000000000001785555b600061048588888080601f016020809104026020016040519081016040528093929190818152602001838380828437600092018290525092506150149150610c989050565b905061049081610dc0565b600580546001600160a01b0319166001600160a01b039290921691909117905561501487111561053757600061050a89898080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250615014925061050591508290508c6110e1565b610c98565b905061051581610dc0565b600680546001600160a01b0319166001600160a01b0392909216919091179055505b50831561058357845468ff000000000000000019168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b6004818154811061059c57600080fd5b6000918252602090912001546001600160a01b0316905081565b6060600480548060200260200160405190810160405280929190818152602001828054801561060e57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116105f0575b5050505050905090565b610620610c6b565b61062a6000610e71565b565b60015433906001600160a01b031681146106695760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b61067281610e71565b50565b600080826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106da91906110f4565b90506000836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801561071c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074091906110f4565b6040517fe6a439050000000000000000000000000000000000000000000000000000000081526001600160a01b03848116600483015280831660248301529192506000917f0000000000000000000000000000000000000000000000000000000000000000169063e6a4390590604401602060405180830381865afa1580156107cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107f191906110f4565b9050806001600160a01b0316856001600160a01b03161461083e576040517f2392efd300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038581166000908152600360205260409020541615610890576040517fda6b1bf300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6004546005546000906108c9906108af906001600160a01b0316610e8a565b6006546108c4906001600160a01b0316610e8a565b610eb1565b60408051602081018590526001600160a01b038a8116828401527f0000000000000000000000000000000000000000000000000000000000000000811660608301527f0000000000000000000000000000000000000000000000000000000000000000811660808301527f00000000000000000000000000000000000000000000000000000000000000001660a0820152640235ef7f6860c0808301919091528251808303909101815260e0820190925291925090600090839061099290849061010001611135565b60408051601f19818403018152908290526109b09291602001611168565b60408051808303601f19018152828252602083018790526001600160a01b038c8116928401929092527f0000000000000000000000000000000000000000000000000000000000000000821660608401527f00000000000000000000000000000000000000000000000000000000000000009091166080830152915060009060a0016040516020818303038152906040528051906020012090506000818351602085016000f5995050883b6001600160a01b038a16610a8257604051630252d9f760e11b815260040160405180910390fd5b80600003610aa357604051630252d9f760e11b815260040160405180910390fd5b6001600260008c6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff02191690831515021790555089600360008d6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060048a9080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055507ffedf6a4642d7997210a9fb40020d72f90c1d9c535a3ae87bade5764edc6f08308b8b604051610bba9291906001600160a01b0392831681529116602082015260400190565b60405180910390a1505050505050505050919050565b610bd8610c6b565b600180546001600160a01b0383166001600160a01b03199091168117909155610c096000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b610c49610c6b565b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b0316331461062a5760405163118cdaa760e01b8152336004820152602401610660565b606081610ca681601f611197565b1015610cf45760405162461bcd60e51b815260206004820152600e60248201527f736c6963655f6f766572666c6f770000000000000000000000000000000000006044820152606401610660565b610cfe8284611197565b84511015610d4e5760405162461bcd60e51b815260206004820152601160248201527f736c6963655f6f75744f66426f756e64730000000000000000000000000000006044820152606401610660565b606082158015610d6d5760405191506000825260208201604052610db7565b6040519150601f8416801560200281840101858101878315602002848b0101015b81831015610da6578051835260209283019201610d8e565b5050858452601f01601f1916604052505b50949350505050565b60008082604051602001610dd491906111aa565b6040516020818303038152906040529050600081604051602001610df891906111d0565b60405160208183030381529060405290508051602082016000f092506001600160a01b038316610e6a5760405162461bcd60e51b815260206004820152601160248201527f4445504c4f594d454e545f4641494c45440000000000000000000000000000006044820152606401610660565b5050919050565b600180546001600160a01b031916905561067281610f2e565b6060610eab826001610ea6816001600160a01b0384163b6110e1565b610f7e565b92915050565b6060806040519050835180825260208201818101602087015b81831015610ee2578051835260209283019201610eca565b50855184518101855292509050808201602086015b81831015610f0f578051835260209283019201610ef7565b508651929092011591909101601f01601f191660405250905092915050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60408051603f8301601f19168101909152818152818360208301863c9392505050565b60008060208385031215610fb457600080fd5b823567ffffffffffffffff80821115610fcc57600080fd5b818501915085601f830112610fe057600080fd5b813581811115610fef57600080fd5b86602082850101111561100157600080fd5b60209290920196919550909350505050565b6001600160a01b038116811461067257600080fd5b60006020828403121561103a57600080fd5b813561104581611013565b9392505050565b60006020828403121561105e57600080fd5b5035919050565b6020808252825182820181905260009190848201906040850190845b818110156110a65783516001600160a01b031683529284019291840191600101611081565b50909695505050505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b81810381811115610eab57610eab6110b2565b60006020828403121561110657600080fd5b815161104581611013565b60005b8381101561112c578181015183820152602001611114565b50506000910152565b6020815260008251806020840152611154816040850160208701611111565b601f01601f19169190910160400192915050565b6000835161117a818460208801611111565b83519083019061118e818360208801611111565b01949350505050565b80820180821115610eab57610eab6110b2565b60008152600082516111c3816001850160208701611111565b9190910160010192915050565b7f600b5981380380925939f300000000000000000000000000000000000000000081526000825161120881600b850160208701611111565b91909101600b019291505056000000000000000000000000e30521fe7f3beb6ad556887b50739d6c7ca667e600000000000000000000000046d2487cdbea04411c49e6c55ace805bfa8f5de500000000000000000000000003047fa366900b4cbf5e8f9feece97553f20370e0000000000000000000000003fba5850c7bc570ad21deb96094f2105e9f4dc94000000000000000000000000b0e1650a9760e0f383174af042091fc544b8356f

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106101515760003560e01c8063715018a6116100cd5780639a0bc2a911610081578063ef3bd76611610066578063ef3bd7661461031e578063f2fde38b14610331578063f46901ed1461034457600080fd5b80639a0bc2a9146102fc578063e30c39781461030d57600080fd5b806379ba5097116100b257806379ba5097146102b057806389439acf146102b85780638da5cb5b146102eb57600080fd5b8063715018a61461028157806378f3a8941461028957600080fd5b8063395db9ec116101245780635cd8d064116101095780635cd8d064146102325780636f4b49c11461024557806370dcf1631461025a57600080fd5b8063395db9ec146101eb57806354fd4d501461021257600080fd5b8063017e7e581461015657806306c75b6a1461018657806307be75f71461019b5780630feef4b1146101c4575b600080fd5b600754610169906001600160a01b031681565b6040516001600160a01b0390911681526020015b60405180910390f35b610199610194366004610fa1565b610357565b005b6101696101a9366004611028565b6003602052600090815260409020546001600160a01b031681565b6101697f000000000000000000000000e30521fe7f3beb6ad556887b50739d6c7ca667e681565b6101697f00000000000000000000000003047fa366900b4cbf5e8f9feece97553f20370e81565b60408051600081526004602082015260019181019190915260600161017d565b61016961024036600461104c565b61058c565b61024d6105b6565b60405161017d9190611065565b6101697f00000000000000000000000046d2487cdbea04411c49e6c55ace805bfa8f5de581565b610199610618565b6101697f0000000000000000000000003fba5850c7bc570ad21deb96094f2105e9f4dc9481565b61019961062c565b6102db6102c6366004611028565b60026020526000908152604090205460ff1681565b604051901515815260200161017d565b6000546001600160a01b0316610169565b60045460405190815260200161017d565b6001546001600160a01b0316610169565b61016961032c366004611028565b610675565b61019961033f366004611028565b610bd0565b610199610352366004611028565b610c41565b61035f610c6b565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00805468010000000000000000810460ff16159067ffffffffffffffff166000811580156103aa5750825b905060008267ffffffffffffffff1660011480156103c75750303b155b9050811580156103d5575080155b1561040c576040517ff92ee8a900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b845467ffffffffffffffff19166001178555831561044057845468ff00000000000000001916680100000000000000001785555b600061048588888080601f016020809104026020016040519081016040528093929190818152602001838380828437600092018290525092506150149150610c989050565b905061049081610dc0565b600580546001600160a01b0319166001600160a01b039290921691909117905561501487111561053757600061050a89898080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250615014925061050591508290508c6110e1565b610c98565b905061051581610dc0565b600680546001600160a01b0319166001600160a01b0392909216919091179055505b50831561058357845468ff000000000000000019168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050565b6004818154811061059c57600080fd5b6000918252602090912001546001600160a01b0316905081565b6060600480548060200260200160405190810160405280929190818152602001828054801561060e57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116105f0575b5050505050905090565b610620610c6b565b61062a6000610e71565b565b60015433906001600160a01b031681146106695760405163118cdaa760e01b81526001600160a01b03821660048201526024015b60405180910390fd5b61067281610e71565b50565b600080826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106da91906110f4565b90506000836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801561071c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074091906110f4565b6040517fe6a439050000000000000000000000000000000000000000000000000000000081526001600160a01b03848116600483015280831660248301529192506000917f000000000000000000000000e30521fe7f3beb6ad556887b50739d6c7ca667e6169063e6a4390590604401602060405180830381865afa1580156107cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107f191906110f4565b9050806001600160a01b0316856001600160a01b03161461083e576040517f2392efd300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038581166000908152600360205260409020541615610890576040517fda6b1bf300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6004546005546000906108c9906108af906001600160a01b0316610e8a565b6006546108c4906001600160a01b0316610e8a565b610eb1565b60408051602081018590526001600160a01b038a8116828401527f00000000000000000000000046d2487cdbea04411c49e6c55ace805bfa8f5de5811660608301527f00000000000000000000000003047fa366900b4cbf5e8f9feece97553f20370e811660808301527f0000000000000000000000003fba5850c7bc570ad21deb96094f2105e9f4dc941660a0820152640235ef7f6860c0808301919091528251808303909101815260e0820190925291925090600090839061099290849061010001611135565b60408051601f19818403018152908290526109b09291602001611168565b60408051808303601f19018152828252602083018790526001600160a01b038c8116928401929092527f00000000000000000000000046d2487cdbea04411c49e6c55ace805bfa8f5de5821660608401527f00000000000000000000000003047fa366900b4cbf5e8f9feece97553f20370e9091166080830152915060009060a0016040516020818303038152906040528051906020012090506000818351602085016000f5995050883b6001600160a01b038a16610a8257604051630252d9f760e11b815260040160405180910390fd5b80600003610aa357604051630252d9f760e11b815260040160405180910390fd5b6001600260008c6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a81548160ff02191690831515021790555089600360008d6001600160a01b03166001600160a01b0316815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060048a9080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055507ffedf6a4642d7997210a9fb40020d72f90c1d9c535a3ae87bade5764edc6f08308b8b604051610bba9291906001600160a01b0392831681529116602082015260400190565b60405180910390a1505050505050505050919050565b610bd8610c6b565b600180546001600160a01b0383166001600160a01b03199091168117909155610c096000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b610c49610c6b565b600780546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b0316331461062a5760405163118cdaa760e01b8152336004820152602401610660565b606081610ca681601f611197565b1015610cf45760405162461bcd60e51b815260206004820152600e60248201527f736c6963655f6f766572666c6f770000000000000000000000000000000000006044820152606401610660565b610cfe8284611197565b84511015610d4e5760405162461bcd60e51b815260206004820152601160248201527f736c6963655f6f75744f66426f756e64730000000000000000000000000000006044820152606401610660565b606082158015610d6d5760405191506000825260208201604052610db7565b6040519150601f8416801560200281840101858101878315602002848b0101015b81831015610da6578051835260209283019201610d8e565b5050858452601f01601f1916604052505b50949350505050565b60008082604051602001610dd491906111aa565b6040516020818303038152906040529050600081604051602001610df891906111d0565b60405160208183030381529060405290508051602082016000f092506001600160a01b038316610e6a5760405162461bcd60e51b815260206004820152601160248201527f4445504c4f594d454e545f4641494c45440000000000000000000000000000006044820152606401610660565b5050919050565b600180546001600160a01b031916905561067281610f2e565b6060610eab826001610ea6816001600160a01b0384163b6110e1565b610f7e565b92915050565b6060806040519050835180825260208201818101602087015b81831015610ee2578051835260209283019201610eca565b50855184518101855292509050808201602086015b81831015610f0f578051835260209283019201610ef7565b508651929092011591909101601f01601f191660405250905092915050565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60408051603f8301601f19168101909152818152818360208301863c9392505050565b60008060208385031215610fb457600080fd5b823567ffffffffffffffff80821115610fcc57600080fd5b818501915085601f830112610fe057600080fd5b813581811115610fef57600080fd5b86602082850101111561100157600080fd5b60209290920196919550909350505050565b6001600160a01b038116811461067257600080fd5b60006020828403121561103a57600080fd5b813561104581611013565b9392505050565b60006020828403121561105e57600080fd5b5035919050565b6020808252825182820181905260009190848201906040850190845b818110156110a65783516001600160a01b031683529284019291840191600101611081565b50909695505050505050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b81810381811115610eab57610eab6110b2565b60006020828403121561110657600080fd5b815161104581611013565b60005b8381101561112c578181015183820152602001611114565b50506000910152565b6020815260008251806020840152611154816040850160208701611111565b601f01601f19169190910160400192915050565b6000835161117a818460208801611111565b83519083019061118e818360208801611111565b01949350505050565b80820180821115610eab57610eab6110b2565b60008152600082516111c3816001850160208701611111565b9190910160010192915050565b7f600b5981380380925939f300000000000000000000000000000000000000000081526000825161120881600b850160208701611111565b91909101600b019291505056

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

000000000000000000000000e30521fe7f3beb6ad556887b50739d6c7ca667e600000000000000000000000046d2487cdbea04411c49e6c55ace805bfa8f5de500000000000000000000000003047fa366900b4cbf5e8f9feece97553f20370e0000000000000000000000003fba5850c7bc570ad21deb96094f2105e9f4dc94000000000000000000000000b0e1650a9760e0f383174af042091fc544b8356f

-----Decoded View---------------
Arg [0] : _fraxswapFactory (address): 0xE30521fe7f3bEB6Ad556887b50739d6C7CA667E6
Arg [1] : _routerMultihop (address): 0x46D2487CdbeA04411C49e6c55aCE805bfA8f5dE5
Arg [2] : _fraxswapOracle (address): 0x03047fA366900b4cBf5E8F9FEEce97553f20370e
Arg [3] : _variableInterestRate (address): 0x3Fba5850c7BC570ad21deb96094F2105E9f4Dc94
Arg [4] : _feeTo (address): 0xb0E1650A9760e0f383174af042091fc544b8356f

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 000000000000000000000000e30521fe7f3beb6ad556887b50739d6c7ca667e6
Arg [1] : 00000000000000000000000046d2487cdbea04411c49e6c55ace805bfa8f5de5
Arg [2] : 00000000000000000000000003047fa366900b4cbf5e8f9feece97553f20370e
Arg [3] : 0000000000000000000000003fba5850c7bc570ad21deb96094f2105e9f4dc94
Arg [4] : 000000000000000000000000b0e1650a9760e0f383174af042091fc544b8356f


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.