Skip to content
Verified contractExactMIT

SmartProvider

Address0x2e0761dcf8a3772f876234578f2d8f049946bd0e
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

7 more contracts

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 20 runs
EVM version
osaka
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,830,231
Creation transaction
0x023c181d8c…1472c71c91

40 files

src/provider/SmartProvider.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

import { MarketParamsLib } from "../moolah/libraries/MarketParamsLib.sol";
import { SharesMathLib } from "../moolah/libraries/SharesMathLib.sol";
import { IMoolahVault } from "../moolah-vault/interfaces/IMoolahVault.sol";
import { Id, IMoolah, MarketParams, Market } from "../moolah/interfaces/IMoolah.sol";
import { ErrorsLib } from "../moolah/libraries/ErrorsLib.sol";
import { UtilsLib } from "../moolah/libraries/UtilsLib.sol";

import { ISmartProvider } from "./interfaces/IProvider.sol";
import { IStableSwap, IStableSwapPoolInfo, StableSwapType } from "../dex/interfaces/IStableSwap.sol";
import { IStableSwapLPCollateral } from "../dex/interfaces/IStableSwapLPCollateral.sol";
import { IOracle, TokenConfig } from "../moolah/interfaces/IOracle.sol";
import { ISlisBNBxMinter } from "../utils/interfaces/ISlisBNBx.sol";

/**
 * @title SmartProvider
 * @author Lista DAO
 * @notice SmartProvider is a contract that allows users to supply collaterals to Lista Lending while simultaneously earning swap fees.
 */
contract SmartProvider is
  ReentrancyGuardUpgradeable,
  UUPSUpgradeable,
  AccessControlEnumerableUpgradeable,
  IOracle,
  ISmartProvider
{
  using SafeERC20 for IERC20;
  using MarketParamsLib for MarketParams;
  using SharesMathLib for uint256;

  /* IMMUTABLES */
  IMoolah public immutable MOOLAH;
  /// @dev stableswap LP Collateral token
  address public immutable TOKEN;

  /// @dev stableswap pool
  address public dex;

  /// @dev stableswap pool info contract
  address public dexInfo;

  /// @dev stableswap LP token
  address public dexLP;

  /// @dev resilient oracle address
  address public resilientOracle;

  /// @dev user account > market id > amount of token deposited
  mapping(address => mapping(Id => uint256)) public userMarketDeposit;

  /// @dev user account > total amount of token deposited
  mapping(address => uint256) public userTotalDeposit;

  /// @dev slisBNBxMinter address
  address public slisBNBxMinter;

  address public constant BNB_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
  bytes32 public constant MANAGER = keccak256("MANAGER");

  /* ------------------ Events ------------------ */
  event SupplyCollateral(
    address indexed onBehalf,
    address indexed collateralToken,
    uint256 collateralAmount,
    uint256 amount0,
    uint256 amount1
  );

  event WithdrawCollateral(
    address indexed collateralToken,
    address indexed onBehalf,
    uint256 collateralAmount,
    uint256 token0Amount,
    uint256 token1Amount,
    address receiver
  );

  event RedeemLpCollateral(address indexed liquidator, uint256 lpAmount, uint256 token0Amount, uint256 token1Amount);
  event SlisBNBxMinterChanged(address newSlisBNBxMinter);
  event RebalanceFailed(string message);

  modifier onlyMoolah() {
    require(msg.sender == address(MOOLAH), "not moolah");
    _;
  }

  /* CONSTRUCTOR */

  /// @custom:oz-upgrades-unsafe-allow constructor
  /// @param moolah The address of the Moolah contract.
  /// @param dexLPCollateral The address of the stableswap LP collateral token.
  constructor(address moolah, address dexLPCollateral) {
    require(moolah != address(0), ErrorsLib.ZERO_ADDRESS);
    require(dexLPCollateral != address(0), ErrorsLib.ZERO_ADDRESS);

    MOOLAH = IMoolah(moolah);
    TOKEN = dexLPCollateral;

    _disableInitializers();
  }

  /// @param _admin The admin of the contract.
  /// @param _dex The address of the stableswap pool.
  /// @param _dexInfo The address of the stableswap pool info contract.
  /// @param _resilientOracle The address of the resilient oracle.
  function initialize(address _admin, address _dex, address _dexInfo, address _resilientOracle) public initializer {
    require(_admin != address(0), ErrorsLib.ZERO_ADDRESS);
    require(_dex != address(0), ErrorsLib.ZERO_ADDRESS);
    require(_dexInfo != address(0), ErrorsLib.ZERO_ADDRESS);
    require(_resilientOracle != address(0), ErrorsLib.ZERO_ADDRESS);

    dex = _dex;
    dexInfo = _dexInfo;
    dexLP = IStableSwap(dex).token();
    require(dexLP != address(0), "invalid dex LP token");

    resilientOracle = _resilientOracle;
    _peek(token(0));
    _peek(token(1));

    __AccessControl_init();

    _grantRole(DEFAULT_ADMIN_ROLE, _admin);
  }

  /**
   * @dev Supplies existing stableswap LP tokens as collateral in Moolah.
   * @param marketParams The market parameters.
   * @param onBehalf The address of the position owner.
   * @param lpAmount The amount of LP tokens to supply.
   */
  function supplyDexLp(MarketParams calldata marketParams, address onBehalf, uint256 lpAmount) external nonReentrant {
    require(lpAmount > 0, "zero lp amount");
    require(marketParams.collateralToken == TOKEN, "invalid collateral token");

    // transfer lp from the user
    IERC20(dexLP).safeTransferFrom(msg.sender, address(this), lpAmount);

    // 1:1 mint collateral token
    IStableSwapLPCollateral(TOKEN).mint(address(this), lpAmount);

    // supply collateral to moolah
    IERC20(TOKEN).safeIncreaseAllowance(address(MOOLAH), lpAmount);
    MOOLAH.supplyCollateral(marketParams, lpAmount, onBehalf, "");

    // sync balances after position change
    _syncPosition(marketParams.id(), onBehalf);

    emit SupplyCollateral(onBehalf, TOKEN, lpAmount, 0, 0);
  }

  /**
   * @dev Withdraw stableswap LP tokens from Moolah.
   * @param marketParams The market parameters.
   * @param onBehalf The address of the position owner.
   * @param assets The amount of LP tokens to withdraw.
   * @param receiver The address to receive the withdrawn LP tokens.
   */
  function withdrawDexLp(
    MarketParams memory marketParams,
    uint256 assets,
    address onBehalf,
    address receiver
  ) external nonReentrant {
    require(isSenderAuthorized(msg.sender, onBehalf), "unauthorized sender");
    require(marketParams.collateralToken == TOKEN, "invalid collateral token");

    // withdraw collateral token from moolah
    MOOLAH.withdrawCollateral(marketParams, assets, onBehalf, address(this));

    // sync balances after position change
    _syncPosition(marketParams.id(), onBehalf);

    // burn collateral token
    IStableSwapLPCollateral(TOKEN).burn(address(this), assets);

    // transfer lp to user
    IERC20(dexLP).safeTransfer(receiver, assets);
    emit WithdrawCollateral(TOKEN, onBehalf, assets, 0, 0, receiver);
  }

  /**
   * @dev Supplies liquidity to the stableswap pool and uses the resulting LP tokens as collateral in Moolah.
   * @param marketParams The market parameters.
   * @param onBehalf The address of the position owner.
   * @param amount0 The amount of token0 to add as liquidity.
   * @param amount1 The amount of token1 to add as liquidity.
   * @param minLpAmount The minimum amount of LP tokens to receive (slippage tolerance).
   */
  function supplyCollateral(
    MarketParams calldata marketParams,
    address onBehalf,
    uint256 amount0,
    uint256 amount1,
    uint256 minLpAmount
  ) external payable nonReentrant {
    require(marketParams.collateralToken == TOKEN, "invalid collateral token");
    address token0 = token(0);
    address token1 = token(1);

    // validate msg.value, amount0 and amount1
    if (token0 == BNB_ADDRESS) {
      require(amount0 == msg.value, "amount0 should equal msg.value");
    } else if (token1 == BNB_ADDRESS) {
      require(amount1 == msg.value, "amount1 should equal msg.value");
    } else {
      require(msg.value == 0, "msg.value must be 0");
    }
    require(amount0 > 0 || amount1 > 0, "invalid amounts");

    // add liquidity to the stableswap pool
    uint256 actualLpAmount = IERC20(dexLP).balanceOf(address(this));
    if (token0 == BNB_ADDRESS) {
      IERC20(token1).safeIncreaseAllowance(dex, amount1);
      if (amount1 > 0) IERC20(token1).safeTransferFrom(msg.sender, address(this), amount1);
    } else if (token1 == BNB_ADDRESS) {
      IERC20(token0).safeIncreaseAllowance(dex, amount0);
      if (amount0 > 0) IERC20(token0).safeTransferFrom(msg.sender, address(this), amount0);
    } else {
      IERC20(token0).safeIncreaseAllowance(dex, amount0);
      IERC20(token1).safeIncreaseAllowance(dex, amount1);

      if (amount0 > 0) IERC20(token0).safeTransferFrom(msg.sender, address(this), amount0);
      if (amount1 > 0) IERC20(token1).safeTransferFrom(msg.sender, address(this), amount1);
    }
    IStableSwap(dex).add_liquidity{ value: msg.value }([amount0, amount1], minLpAmount);

    // validate the actual LP amount minted
    actualLpAmount = IERC20(dexLP).balanceOf(address(this)) - actualLpAmount;
    require(actualLpAmount > 0, "no lp minted");

    // 1:1 mint collateral token
    IStableSwapLPCollateral(TOKEN).mint(address(this), actualLpAmount);

    // supply collateral to moolah
    IERC20(TOKEN).safeIncreaseAllowance(address(MOOLAH), actualLpAmount);
    MOOLAH.supplyCollateral(marketParams, actualLpAmount, onBehalf, "");

    // sync balances after position change
    _syncPosition(marketParams.id(), onBehalf);

    emit SupplyCollateral(onBehalf, TOKEN, actualLpAmount, amount0, amount1);
  }

  /**
   * @dev Withdraws liquidity according to the tokens proportions in the pool.
   * @param marketParams The market parameters.
   * @param collateralAmount The amount of lp to withdraw.
   * @param minToken0Amount The minimum amount of token0 to receive (slippage tolerance).
   * @param minToken1Amount The minimum amount of token1 to receive (slippage tolerance).
   * @param onBehalf The address of the position owner.
   * @param receiver The address to receive the withdrawn tokens.
   */
  function withdrawCollateral(
    MarketParams calldata marketParams,
    uint256 collateralAmount,
    uint256 minToken0Amount,
    uint256 minToken1Amount,
    address onBehalf,
    address payable receiver
  ) external nonReentrant {
    require(collateralAmount > 0, "zero withdrawal amount");
    require(receiver != address(0), ErrorsLib.ZERO_ADDRESS);
    require(isSenderAuthorized(msg.sender, onBehalf), "unauthorized sender");
    require(marketParams.collateralToken == TOKEN, "invalid collateral token");

    // remove liquidity from the stableswap pool
    (uint256 token0Amount, uint256 token1Amount) = _redeemLp(collateralAmount, minToken0Amount, minToken1Amount);

    // withdraw collateral
    MOOLAH.withdrawCollateral(marketParams, collateralAmount, onBehalf, address(this));

    // sync balances after position change
    _syncPosition(marketParams.id(), onBehalf);

    // burn collateral token
    IStableSwapLPCollateral(TOKEN).burn(address(this), collateralAmount);

    if (token0Amount > 0) transferOutTo(0, token0Amount, receiver);
    if (token1Amount > 0) transferOutTo(1, token1Amount, receiver);

    emit WithdrawCollateral(TOKEN, onBehalf, collateralAmount, token0Amount, token1Amount, receiver);
  }

  /**
   * @dev Withdraws liquidity in an imbalanced way, allowing the user to specify exact amounts of token0 and token1 to withdraw.
   * @param marketParams The market parameters.
   * @param token0Amount The exact amount of token0 to withdraw.
   * @param token1Amount The exact amount of token1 to withdraw.
   * @param maxCollateralAmount The maximum amount of collateral (LP tokens) to burn for the withdrawal (slippage tolerance).
   * @param onBehalf The address of the position owner.
   * @param receiver The address to receive the withdrawn tokens.
   */
  function withdrawCollateralImbalance(
    MarketParams calldata marketParams,
    uint256 token0Amount,
    uint256 token1Amount,
    uint256 maxCollateralAmount,
    address onBehalf,
    address payable receiver
  ) external nonReentrant {
    require(token0Amount > 0 || token1Amount > 0, "zero withdrawal amount");
    require(receiver != address(0), ErrorsLib.ZERO_ADDRESS);
    require(isSenderAuthorized(msg.sender, onBehalf), "unauthorized sender");
    require(marketParams.collateralToken == TOKEN, "invalid collateral token");
    require(maxCollateralAmount > 0, "invalid collateral amount");

    uint256[2] memory amounts = [token0Amount, token1Amount];

    // remove liquidity from the stableswap pool
    uint256 actualBurnAmount = IERC20(dexLP).balanceOf(address(this));
    IStableSwap(dex).remove_liquidity_imbalance(amounts, maxCollateralAmount);
    actualBurnAmount = actualBurnAmount - IERC20(dexLP).balanceOf(address(this));

    // withdraw collateral
    MOOLAH.withdrawCollateral(marketParams, actualBurnAmount, onBehalf, address(this));

    // sync balances after position change
    _syncPosition(marketParams.id(), onBehalf);

    // burn collateral token
    IStableSwapLPCollateral(TOKEN).burn(address(this), actualBurnAmount);

    if (token0Amount > 0) transferOutTo(0, token0Amount, receiver);
    if (token1Amount > 0) transferOutTo(1, token1Amount, receiver);

    emit WithdrawCollateral(TOKEN, onBehalf, actualBurnAmount, token0Amount, token1Amount, receiver);
  }

  /**
   * @dev Withdraws liquidity in a single token, allowing the user to specify which token to withdraw.
   * @param marketParams The market parameters.
   * @param collateralAmount The amount of lp to withdraw.
   * @param i The index of the token to withdraw (0 or 1).
   * @param minTokenAmount The minimum amount of the specified token i to receive (slippage tolerance).
   * @param onBehalf The address of the position owner.
   * @param receiver The address to receive the withdrawn tokens.
   */
  function withdrawCollateralOneCoin(
    MarketParams calldata marketParams,
    uint256 collateralAmount,
    uint256 i,
    uint256 minTokenAmount,
    address onBehalf,
    address payable receiver
  ) external nonReentrant {
    require(collateralAmount > 0, "zero withdrawal amount");
    require(receiver != address(0), ErrorsLib.ZERO_ADDRESS);
    require(isSenderAuthorized(msg.sender, onBehalf), "unauthorized sender");
    require(marketParams.collateralToken == TOKEN, "invalid collateral token");
    require(i == 0 || i == 1, "invalid token index");

    uint256 actualAmount = getTokenBalance(i);
    IStableSwap(dex).remove_liquidity_one_coin(collateralAmount, i, minTokenAmount);

    actualAmount = getTokenBalance(i) - actualAmount;

    // withdraw collateral
    MOOLAH.withdrawCollateral(marketParams, collateralAmount, onBehalf, address(this));

    // sync balances after position change
    _syncPosition(marketParams.id(), onBehalf);

    // burn collateral token
    IStableSwapLPCollateral(TOKEN).burn(address(this), collateralAmount);

    if (actualAmount > 0) transferOutTo(i, actualAmount, receiver);

    emit WithdrawCollateral(
      TOKEN,
      onBehalf,
      collateralAmount,
      i == 0 ? actualAmount : 0,
      i == 1 ? actualAmount : 0,
      receiver
    );
  }

  /**
   * @dev Transfers the specified amount of the token i to the receiver.
   * @param i The index of the token (0 or 1).
   * @param amount The amount of the token to transfer.
   * @param receiver The address to receive the tokens.
   */
  function transferOutTo(uint256 i, uint256 amount, address payable receiver) private {
    address _token = token(i);

    if (_token == BNB_ADDRESS) {
      // if token is BNB, transfer BNB
      (bool success, ) = receiver.call{ value: amount }("");
      require(success, "Transfer BNB failed");
    } else {
      // if token is ERC20, transfer ERC20
      IERC20(_token).safeTransfer(receiver, amount);
    }
  }

  function liquidate(Id id, address borrower) external onlyMoolah {
    // sync balances after position change
    _syncPosition(id, borrower);
  }

  /**
   * @notice Liquidates a position by burning the seized collateral token and removing liquidity from the stableswap pool.
   * @notice The seized tokens (token0 and token1) are then sent to the liquidator.
   * @notice This function assumes that the liquidator has already received the seized collateral token which will be burned.
   * @param lpAmount The amount of collateral to be redeemed (in LP tokens).
   * @param minAmount0 The minimum amount of token0 to receive (slippage tolerance).
   * @param minAmount1 The minimum amount of token1 to receive (slippage tolerance).
   * @return The amount of token0 and token1 redeemed.
   */
  function redeemLpCollateral(
    uint256 lpAmount,
    uint256 minAmount0,
    uint256 minAmount1
  ) external nonReentrant returns (uint256, uint256) {
    require(lpAmount > 0, "zero seized assets");
    // burn collateral token sent to the liquidator before
    IStableSwapLPCollateral(TOKEN).burn(msg.sender, lpAmount);

    // remove liquidity from the stableswap pool
    (uint256 token0Amount, uint256 token1Amount) = _redeemLp(lpAmount, minAmount0, minAmount1);

    // send token0 and token1 to the liquidator
    if (token0Amount > 0) transferOutTo(0, token0Amount, payable(msg.sender));
    if (token1Amount > 0) transferOutTo(1, token1Amount, payable(msg.sender));

    emit RedeemLpCollateral(msg.sender, lpAmount, token0Amount, token1Amount);
    return (token0Amount, token1Amount);
  }

  function _redeemLp(
    uint256 lpAmount,
    uint256 minAmount0,
    uint256 minAmount1
  ) private returns (uint256 token0Amount, uint256 token1Amount) {
    token0Amount = getTokenBalance(0);
    token1Amount = getTokenBalance(1);

    // redeem lp token
    IStableSwap(dex).remove_liquidity(lpAmount, [minAmount0, minAmount1]);

    // validate the actual token amounts after removing liquidity
    token0Amount = getTokenBalance(0) - token0Amount;
    token1Amount = getTokenBalance(1) - token1Amount;
  }

  /// @dev Returns whether the sender is authorized to manage `onBehalf`'s positions.
  /// @param sender The address of the sender to check.
  /// @param onBehalf The address of the position owner.
  function isSenderAuthorized(address sender, address onBehalf) public view returns (bool) {
    return sender == onBehalf || MOOLAH.isAuthorized(onBehalf, sender);
  }

  /// @param i The index of the token (0 or 1).
  function getTokenBalance(uint256 i) public view returns (uint256) {
    address _token = token(i);

    if (_token == BNB_ADDRESS) {
      return address(this).balance;
    } else {
      return IERC20(_token).balanceOf(address(this));
    }
  }

  /// @dev Returns the address of the token at index `i`.
  function token(uint256 i) public view returns (address) {
    require(i < 2, "Invalid token index");
    return IStableSwap(dex).coins(i);
  }

  /// @dev Returns the price of the token in 8 decimal format.
  function peek(address _token) external view returns (uint256) {
    if (_token == TOKEN || _token == dexLP) {
      // if token is dexLP, return the price of the LP token
      // LP value = min(token0_price, token1_price) * virtual_price
      uint256 minPrice = UtilsLib.min(_peek(token(0)), _peek(token(1)));
      uint256 virtualPrice = IStableSwap(dex).get_virtual_price(); // 1e18
      return (minPrice * virtualPrice) / 1e18;
    }

    return _peek(_token);
  }

  function _peek(address _token) private view returns (uint256) {
    return IOracle(resilientOracle).peek(_token);
  }

  /// @dev Returns the oracle configuration for the specified token.
  function getTokenConfig(address _token) external view returns (TokenConfig memory) {
    if (_token == TOKEN || _token == dexLP) {
      return
        TokenConfig({
          asset: _token,
          oracles: [address(this), address(0), address(0)],
          enableFlagsForOracles: [true, false, false],
          timeDeltaTolerance: 0
        });
    } else {
      return IOracle(resilientOracle).getTokenConfig(_token);
    }
  }

  function _syncPosition(Id id, address account) private returns (bool, uint256) {
    require(MOOLAH.idToMarketParams(id).collateralToken == TOKEN, "invalid market");
    uint256 userMarketSupplyCollateral = MOOLAH.position(id, account).collateral;
    if (MOOLAH.providers(id, TOKEN) != address(this)) {
      userMarketSupplyCollateral = 0;
    }
    if (userMarketSupplyCollateral >= userMarketDeposit[account][id]) {
      uint256 depositAmount = userMarketSupplyCollateral - userMarketDeposit[account][id];
      userTotalDeposit[account] += depositAmount;
    } else {
      uint256 withdrawAmount = userMarketDeposit[account][id] - userMarketSupplyCollateral;
      userTotalDeposit[account] -= withdrawAmount;
    }
    userMarketDeposit[account][id] = userMarketSupplyCollateral;

    if (slisBNBxMinter == address(0)) {
      return (false, 0);
    } else {
      return ISlisBNBxMinter(slisBNBxMinter).rebalance(account);
    }
  }

  /* ----------------------- slisBNBx Re-balancing ----------------------- */
  /**
   * @dev sync user's slisBNBx balance to retain a consistent ratio with token balance
   * @param _account user address to sync
   */
  function syncUserBalance(Id id, address _account) external {
    (bool rebalanced, ) = _syncPosition(id, _account);
    require(rebalanced, "already synced");
  }

  /**
   * @dev sync multiple user's slisBNBx balance to retain a consistent ratio with token balance
   * @param _accounts user address to sync
   */
  function bulkSyncUserBalance(Id[] calldata ids, address[] calldata _accounts) external {
    for (uint256 i = 0; i < _accounts.length; i++) {
      for (uint256 j = 0; j < ids.length; j++) {
        // sync user's total balance and market balance
        _syncPosition(ids[j], _accounts[i]);
      }
    }
  }

  /// @dev Returns the user's lp collateral value in BNB.
  /// @param account The address of the user.
  function getUserBalanceInBnb(address account) external view returns (uint256) {
    // invoke pool's `get_virtual_price` to ensure the underlying pool not in reentrant state
    IStableSwap(dex).get_virtual_price();

    // how many lp tokens the account has as collateral
    uint256 balance = userTotalDeposit[account];

    // convert lp tokens to bnb value
    uint256[2] memory amounts = IStableSwapPoolInfo(dexInfo).calc_coins_amount(dex, balance);
    uint256 token0Price = _peek(token(0)); // 8 decimals
    uint256 token1Price = _peek(token(1)); // 8 decimals
    uint256 dps0 = (token(0) == BNB_ADDRESS) ? 18 : IERC20Metadata(token(0)).decimals();
    uint256 dps1 = (token(1) == BNB_ADDRESS) ? 18 : IERC20Metadata(token(1)).decimals();

    // calculate lp value in BNB
    uint256 value0 = ((amounts[0] * token0Price) * 1e18) / (10 ** dps0);
    uint256 value1 = ((amounts[1] * token1Price) * 1e18) / (10 ** dps1);
    return (value0 + value1) / _peek(BNB_ADDRESS);
  }

  /// @dev Sets the slisBNBxMinter address.
  function setSlisBNBxMinter(address _slisBNBxMinter) external onlyRole(MANAGER) {
    require(_slisBNBxMinter != address(0), "zero address provided");
    slisBNBxMinter = _slisBNBxMinter;

    emit SlisBNBxMinterChanged(_slisBNBxMinter);
  }

  receive() external payable {
    require(msg.sender == dex, "not dex");
  }

  function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {}
}

lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol

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

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        return $._roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        AccessControlStorage storage $ = _getAccessControlStorage();
        bytes32 previousAdminRole = getRoleAdmin(role);
        $._roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (!hasRole(role, account)) {
            $._roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        AccessControlStorage storage $ = _getAccessControlStorage();
        if (hasRole(role, account)) {
            $._roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/extensions/AccessControlEnumerableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/AccessControlEnumerable.sol)

pragma solidity ^0.8.20;

import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerable, AccessControlUpgradeable {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
    struct AccessControlEnumerableStorage {
        mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;

    function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
        assembly {
            $.slot := AccessControlEnumerableStorageLocation
        }
    }

    function __AccessControlEnumerable_init() internal onlyInitializing {
    }

    function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        return $._roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        return $._roleMembers[role].length();
    }

    /**
     * @dev Return all accounts that have `role`
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function getRoleMembers(bytes32 role) public view virtual returns (address[] memory) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        return $._roleMembers[role].values();
    }

    /**
     * @dev Overload {AccessControl-_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        bool granted = super._grantRole(role, account);
        if (granted) {
            $._roleMembers[role].add(account);
        }
        return granted;
    }

    /**
     * @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        bool revoked = super._revokeRole(role, account);
        if (revoked) {
            $._roleMembers[role].remove(account);
        }
        return revoked;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

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

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    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;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

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

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._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 {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // 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 {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // 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) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165Upgradeable is Initializable, IERC165 {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

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

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlEnumerable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/extensions/IAccessControlEnumerable.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol

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

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

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

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-20 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);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 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);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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 Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

    /**
     * @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
     * {Errors.FailedCall} 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 Errors.InsufficientBalance(address(this).balance, value);
        }
        (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 {Errors.FailedCall}) 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 {Errors.FailedCall} 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 {Errors.FailedCall}.
     */
    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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

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

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     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;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 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) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

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

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

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

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            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) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            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) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

src/dex/interfaces/IStableSwap.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

uint256 constant N_COINS = 2;

// enum
enum StableSwapType {
  BothERC20, // StableSwap with ERC20 tokens
  Token0Bnb, // StableSwap with token0 as BNB
  Token1Bnb, // StableSwap with token1 as BNB
  Others // unknown type
}

interface IStableSwap {
  function support_BNB() external view returns (bool);

  function token() external view returns (address);

  function balances(uint256 i) external view returns (uint256);

  function admin_balances(uint256 i) external view returns (uint256);

  function N_COINS() external view returns (uint256);

  function RATES(uint256 i) external view returns (uint256);

  function coins(uint256 i) external view returns (address);

  function PRECISION_MUL(uint256 i) external view returns (uint256);

  function fee() external view returns (uint256);

  function admin_fee() external view returns (uint256);

  function A() external view returns (uint256);

  function get_virtual_price() external view returns (uint256);

  function fetchOraclePrice() external view returns (uint256[2] memory);

  function checkPriceDiff() external view;

  //  function get_D_mem(uint256[2] memory _balances, uint256 amp) external view returns (uint256);

  //  function get_y(uint256 i, uint256 j, uint256 x, uint256[2] memory xp_) external view returns (uint256);

  function calc_token_amount(uint256[N_COINS] memory amounts, bool _deposit) external view returns (uint256);

  function calc_withdraw_one_coin(uint256 _token_amount, uint256 i) external view returns (uint256);

  function add_liquidity(uint256[N_COINS] memory amounts, uint256 min_mint_amount) external payable;

  function remove_liquidity(uint256 _token_amount, uint256[N_COINS] memory min_amounts) external;

  function remove_liquidity_imbalance(uint256[N_COINS] memory amounts, uint256 max_burn_amount) external;

  function remove_liquidity_one_coin(uint256 _token_amount, uint256 i, uint256 min_amount) external;

  function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external payable;

  function withdraw_admin_fees() external;

  // events
  event TokenExchange(
    address indexed buyer,
    uint256 sold_id,
    uint256 tokens_sold,
    uint256 bought_id,
    uint256 tokens_bought,
    uint256 swap_fee,
    uint256 admin_fee
  );
  event AddLiquidity(
    address indexed provider,
    uint256[N_COINS] token_amounts,
    uint256[N_COINS] fees,
    uint256 invariant,
    uint256 token_supply,
    uint256 admin_fee_rate
  );
  event RemoveLiquidity(
    address indexed provider,
    uint256[N_COINS] token_amounts,
    uint256[N_COINS] fees,
    uint256 token_supply
  );
  event RemoveLiquidityOne(
    address indexed provider,
    uint256 index,
    uint256 token_amount,
    uint256 coin_amount,
    uint256 fee,
    uint256 admin_fee_rate
  );
  event RemoveLiquidityImbalance(
    address indexed provider,
    uint256[N_COINS] token_amounts,
    uint256[N_COINS] fees,
    uint256 invariant,
    uint256 token_supply,
    uint256 admin_fee_rate
  );
  event CommitNewFee(uint256 indexed deadline, uint256 fee, uint256 admin_fee);
  event NewFee(uint256 fee, uint256 admin_fee);
  event RampA(uint256 old_A, uint256 new_A, uint256 initial_time, uint256 future_time);
  event StopRampA(uint256 A, uint256 t);
  event SetBNBGas(uint256 bnb_gas);
  event RevertParameters();
  event DonateAdminFees();
  event ChangePriceDiffThreshold(uint256 price0DiffThreshold, uint256 price1DiffThreshold);
  event SetSkipPriceDiff(bool skipPriceDiff);
  event ChangeOracle(address newOracle);
}

interface IStableSwapPoolInfo {
  function stableSwapType(address stableSwapPool) external view returns (StableSwapType);

  function get_add_liquidity_mint_amount(
    address stableSwapPool,
    uint256[2] memory amounts
  ) external view returns (uint256);

  function calc_coins_amount(address stableSwapPool, uint256 _lpAmount) external view returns (uint256[2] memory);
}

src/dex/interfaces/IStableSwapLPCollateral.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

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

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IStableSwapLPCollateral is IERC20 {
  function burn(address account, uint256 amount) external;

  function mint(address account, uint256 amount) external;
}

src/moolah-vault/interfaces/IMoolahVault.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";

import { IMoolah, Id, MarketParams } from "moolah/interfaces/IMoolah.sol";

import { MarketConfig, PendingUint192, PendingAddress } from "../libraries/PendingLib.sol";

struct MarketAllocation {
  /// @notice The market to allocate.
  MarketParams marketParams;
  /// @notice The amount of assets to allocate.
  uint256 assets;
}

interface IMulticall {
  function multicall(bytes[] calldata) external returns (bytes[] memory);
}

interface IOwnable {
  function transferOwnership(address) external;
  function renounceOwnership() external;
  function acceptOwnership() external;
}

/// @dev This interface is used for factorizing IMoolahVaultStaticTyping and IMoolahVault.
/// @dev Consider using the IMoolahVault interface instead of this one.
interface IMoolahVaultBase {
  /// @notice The address of the Moolah contract.
  function MOOLAH() external view returns (IMoolah);
  function DECIMALS_OFFSET() external view returns (uint8);

  /// @notice The current fee.
  function fee() external view returns (uint96);

  /// @notice The fee recipient.
  function feeRecipient() external view returns (address);

  /// @notice The skim recipient.
  function skimRecipient() external view returns (address);

  /// @dev Stores the order of markets on which liquidity is supplied upon deposit.
  /// @dev Can contain any market. A market is skipped as soon as its supply cap is reached.
  function supplyQueue(uint256) external view returns (Id);

  /// @notice Returns the length of the supply queue.
  function supplyQueueLength() external view returns (uint256);

  /// @dev Stores the order of markets from which liquidity is withdrawn upon withdrawal.
  /// @dev Always contain all non-zero cap markets as well as all markets on which the vault supplies liquidity,
  /// without duplicate.
  function withdrawQueue(uint256) external view returns (Id);

  /// @notice Returns the length of the withdraw queue.
  function withdrawQueueLength() external view returns (uint256);

  /// @notice Stores the total assets managed by this vault when the fee was last accrued.
  /// @dev May be greater than `totalAssets()` due to removal of markets with non-zero supply or socialized bad debt.
  /// This difference will decrease the fee accrued until one of the functions updating `lastTotalAssets` is
  /// triggered (deposit/mint/withdraw/redeem/setFee/setFeeRecipient).
  function lastTotalAssets() external view returns (uint256);

  /// @notice The address of the provider.
  function provider() external view returns (address);

  /// @notice set market removal
  function setMarketRemoval(MarketParams memory) external;

  /// @notice submit cap
  function setCap(MarketParams memory, uint256) external;

  /// @notice Skims the vault `token` balance to `skimRecipient`.
  function skim(address) external;

  /// @notice Sets the `fee` to `newFee`.
  function setFee(uint256 newFee) external;

  /// @notice Sets `feeRecipient` to `newFeeRecipient`.
  function setFeeRecipient(address newFeeRecipient) external;

  /// @notice Sets `skimRecipient` to `newSkimRecipient`.
  function setSkimRecipient(address newSkimRecipient) external;

  /// @notice Sets `supplyQueue` to `newSupplyQueue`.
  /// @param newSupplyQueue is an array of enabled markets, and can contain duplicate markets, but it would only
  /// increase the cost of depositing to the vault.
  function setSupplyQueue(Id[] calldata newSupplyQueue) external;

  /// @notice Updates the withdraw queue. Some markets can be removed, but no market can be added.
  /// @notice Removing a market requires the vault to have 0 supply on it, or to have previously submitted a removal
  /// for this market (with the function `submitMarketRemoval`).
  /// @notice Warning: Anyone can supply on behalf of the vault so the call to `updateWithdrawQueue` that expects a
  /// market to be empty can be griefed by a front-run. To circumvent this, the allocator can simply bundle a
  /// reallocation that withdraws max from this market with a call to `updateWithdrawQueue`.
  /// @dev Warning: Removing a market with supply will decrease the fee accrued until one of the functions updating
  /// `lastTotalAssets` is triggered (deposit/mint/withdraw/redeem/setFee/setFeeRecipient).
  /// @dev Warning: `updateWithdrawQueue` is not idempotent. Submitting twice the same tx will change the queue twice.
  /// @param indexes The indexes of each market in the previous withdraw queue, in the new withdraw queue's order.
  function updateWithdrawQueue(uint256[] calldata indexes) external;

  /// @notice Reallocates the vault's liquidity so as to reach a given allocation of assets on each given market.
  /// @dev The behavior of the reallocation can be altered by state changes, including:
  /// - Deposits on the vault that supplies to markets that are expected to be supplied to during reallocation.
  /// - Withdrawals from the vault that withdraws from markets that are expected to be withdrawn from during
  /// reallocation.
  /// - Donations to the vault on markets that are expected to be supplied to during reallocation.
  /// - Withdrawals from markets that are expected to be withdrawn from during reallocation.
  /// @dev Sender is expected to pass `assets = type(uint256).max` with the last MarketAllocation of `allocations` to
  /// supply all the remaining withdrawn liquidity, which would ensure that `totalWithdrawn` = `totalSupplied`.
  /// @dev A supply in a reallocation step will make the reallocation revert if the amount is greater than the net
  /// amount from previous steps (i.e. total withdrawn minus total supplied).
  function reallocate(MarketAllocation[] calldata allocations) external;
  function setBotRole(address _address) external;
  function revokeBotRole(address _address) external;
  /// @notice Sets the address of the provider.
  function setProvider(address _provider) external;

  /// @notice Set a custom vault name.
  function setName(string calldata newName) external;
  /// @notice Set a custom vault symbol.
  function setSymbol(string calldata newSymbol) external;

  /// @notice Add or remove an account from the whitelist.
  function setWhiteList(address account, bool enabled) external;
  /// @notice Returns the list of whitelisted accounts.
  function getWhiteList() external view returns (address[] memory);
  /// @notice Returns `true` if `account` is whitelisted.
  function isWhiteList(address account) external view returns (bool);

  /// @notice The smoothing buffer pointer (or `address(0)` when smoothing is disabled).
  function lockBuffer() external view returns (address);
  function setLockBuffer(address buf) external;
}

/// @dev This interface is inherited by MoolahVault so that function signatures are checked by the compiler.
/// @dev Consider using the IMoolahVault interface instead of this one.
interface IMoolahVaultStaticTyping is IMoolahVaultBase {
  /// @notice Returns the current configuration of each market.
  function config(Id) external view returns (uint184 cap, bool enabled, uint64 removableAt);
}

/// @title IMoolahVault
/// @author Lista DAO
/// @dev Use this interface for MoolahVault to have access to all the functions with the appropriate function signatures.
interface IMoolahVault is IMoolahVaultBase, IERC4626, IERC20Permit, IOwnable, IMulticall {
  /// @notice Returns the current configuration of each market.
  function config(Id) external view returns (MarketConfig memory);

  /// @notice Returns `true` if `account` has been granted `role`.
  function hasRole(bytes32 role, address account) external view returns (bool);

  /// @dev Returns the number of accounts that have `role`.
  function getRoleMemberCount(bytes32 role) external view returns (uint256);

  /// @notice grants `role` to `account`.
  function grantRole(bytes32 role, address account) external;

  /// @notice revokes `role` from `account`.
  function revokeRole(bytes32 role, address account) external;

  /// @notice called by provider to withdraw assets from the vault.
  function withdrawFor(uint256 assets, address owner, address sender) external returns (uint256 shares);

  /// @notice called by provider to redeem shares from the vault.
  function redeemFor(uint256 shares, address owner, address sender) external returns (uint256 assets);
}

src/moolah-vault/libraries/PendingLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

struct MarketConfig {
  /// @notice The maximum amount of assets that can be allocated to the market.
  uint184 cap;
  /// @notice Whether the market is in the withdraw queue.
  bool enabled;
  /// @notice The timestamp at which the market can be instantly removed from the withdraw queue.
  uint64 removableAt;
}

struct PendingUint192 {
  /// @notice The pending value to set.
  uint192 value;
  /// @notice The timestamp at which the pending value becomes valid.
  uint64 validAt;
}

struct PendingAddress {
  /// @notice The pending value to set.
  address value;
  /// @notice The timestamp at which the pending value becomes valid.
  uint64 validAt;
}

/// @title PendingLib
/// @author Lista DAO
/// @notice Library to manage pending values and their validity timestamp.
library PendingLib {
  /// @dev Updates `pending`'s value to `newValue` and its corresponding `validAt` timestamp.
  /// @dev Assumes `timelock` <= `MAX_TIMELOCK`.
  function update(PendingUint192 storage pending, uint184 newValue, uint256 timelock) internal {
    pending.value = newValue;
    // Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
    pending.validAt = uint64(block.timestamp + timelock);
  }

  /// @dev Updates `pending`'s value to `newValue` and its corresponding `validAt` timestamp.
  /// @dev Assumes `timelock` <= `MAX_TIMELOCK`.
  function update(PendingAddress storage pending, address newValue, uint256 timelock) internal {
    pending.value = newValue;
    // Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
    pending.validAt = uint64(block.timestamp + timelock);
  }
}

src/moolah/interfaces/IMoolah.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

type Id is bytes32;

struct MarketParams {
  address loanToken;
  address collateralToken;
  address oracle;
  address irm;
  uint256 lltv;
}

/// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
/// accrual.
struct Position {
  uint256 supplyShares;
  uint128 borrowShares;
  uint128 collateral;
}

/// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
/// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
/// interest accrual.
struct Market {
  uint128 totalSupplyAssets;
  uint128 totalSupplyShares;
  uint128 totalBorrowAssets;
  uint128 totalBorrowShares;
  uint128 lastUpdate;
  uint128 fee;
}

struct Authorization {
  address authorizer;
  address authorized;
  bool isAuthorized;
  uint256 nonce;
  uint256 deadline;
}

struct Signature {
  uint8 v;
  bytes32 r;
  bytes32 s;
}

/// @dev This interface is used for factorizing IMoolahStaticTyping and IMoolah.
/// @dev Consider using the IMoolah interface instead of this one.
interface IMoolahBase {
  /// @notice The EIP-712 domain separator used in the encoding of the signatures for `setAuthorizationWithSig`.
  function domainSeparator() external view returns (bytes32);

  /// @notice The fee recipient of all markets.
  /// @dev The recipient receives the fees of a given market through a supply position on that market.
  function feeRecipient() external view returns (address);

  /// @notice Whether the `irm` is enabled.
  function isIrmEnabled(address irm) external view returns (bool);

  /// @notice Whether the `lltv` is enabled.
  function isLltvEnabled(uint256 lltv) external view returns (bool);

  /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
  /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
  function isAuthorized(address authorizer, address authorized) external view returns (bool);

  /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
  function nonce(address authorizer) external view returns (uint256);

  /// @notice Enables `irm` as a possible IRM for market creation.
  /// @dev Warning: It is not possible to disable an IRM.
  function enableIrm(address irm) external;

  /// @notice Enables `lltv` as a possible LLTV for market creation.
  /// @dev Warning: It is not possible to disable a LLTV.
  function enableLltv(uint256 lltv) external;

  /// @notice Sets the `newFee` for the given market `marketParams`.
  /// @param newFee The new fee, scaled by WAD.
  /// @dev Warning: The recipient can be the zero address.
  function setFee(MarketParams memory marketParams, uint256 newFee) external;

  /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
  /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
  /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
  /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
  function setFeeRecipient(address newFeeRecipient) external;

  /// @notice Creates the market `marketParams`.
  /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
  /// Moolah behaves as expected:
  /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
  /// - The token balance of Moolah should only decrease on `transfer` and `transferFrom`. In particular, tokens with
  /// burn functions are not supported.
  /// - The token should not re-enter Moolah on `transfer` nor `transferFrom`.
  /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
  /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
  /// - The IRM should not re-enter Moolah.
  /// - The oracle should return a price with the correct scaling.
  /// @dev Here is a list of properties on the market's dependencies that could break Moolah's liveness properties
  /// (funds could get stuck):
  /// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
  /// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
  /// `toSharesDown` overflow.
  /// - The IRM can revert on `borrowRate`.
  /// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
  /// overflow.
  /// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
  /// `liquidate` from being used under certain market conditions.
  /// - The price from the oracle must have 8 decimals.
  /// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
  /// the computation of `assetsRepaid` in `liquidate` overflow.
  /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
  /// the point where `totalBorrowShares` is very large and borrowing overflows.
  function createMarket(MarketParams memory marketParams) external;

  /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
  /// `onMoolahSupply` function with the given `data`.
  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
  /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
  /// amount of shares is given for full compatibility and precision.
  /// @dev Supplying a large amount can revert for overflow.
  /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
  /// Consider using the `assets` parameter to avoid this.
  /// @param marketParams The market to supply assets to.
  /// @param assets The amount of assets to supply.
  /// @param shares The amount of shares to mint.
  /// @param onBehalf The address that will own the increased supply position.
  /// @param data Arbitrary data to pass to the `onMoolahSupply` callback. Pass empty data if not needed.
  /// @return assetsSupplied The amount of assets supplied.
  /// @return sharesSupplied The amount of shares minted.
  function supply(
    MarketParams memory marketParams,
    uint256 assets,
    uint256 shares,
    address onBehalf,
    bytes memory data
  ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);

  /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
  /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
  /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
  /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
  /// conversion roundings between shares and assets.
  /// @param marketParams The market to withdraw assets from.
  /// @param assets The amount of assets to withdraw.
  /// @param shares The amount of shares to burn.
  /// @param onBehalf The address of the owner of the supply position.
  /// @param receiver The address that will receive the withdrawn assets.
  /// @return assetsWithdrawn The amount of assets withdrawn.
  /// @return sharesWithdrawn The amount of shares burned.
  function withdraw(
    MarketParams memory marketParams,
    uint256 assets,
    uint256 shares,
    address onBehalf,
    address receiver
  ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);

  /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
  /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
  /// given for full compatibility and precision.
  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
  /// @dev Borrowing a large amount can revert for overflow.
  /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
  /// Consider using the `assets` parameter to avoid this.
  /// @param marketParams The market to borrow assets from.
  /// @param assets The amount of assets to borrow.
  /// @param shares The amount of shares to mint.
  /// @param onBehalf The address that will own the increased borrow position.
  /// @param receiver The address that will receive the borrowed assets.
  /// @return assetsBorrowed The amount of assets borrowed.
  /// @return sharesBorrowed The amount of shares minted.
  function borrow(
    MarketParams memory marketParams,
    uint256 assets,
    uint256 shares,
    address onBehalf,
    address receiver
  ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);

  /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
  /// `onMoolahRepay` function with the given `data`.
  /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
  /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
  /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
  /// roundings between shares and assets.
  /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
  /// @param marketParams The market to repay assets to.
  /// @param assets The amount of assets to repay.
  /// @param shares The amount of shares to burn.
  /// @param onBehalf The address of the owner of the debt position.
  /// @param data Arbitrary data to pass to the `onMoolahRepay` callback. Pass empty data if not needed.
  /// @return assetsRepaid The amount of assets repaid.
  /// @return sharesRepaid The amount of shares burned.
  function repay(
    MarketParams memory marketParams,
    uint256 assets,
    uint256 shares,
    address onBehalf,
    bytes memory data
  ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);

  /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
  /// `onMoolahSupplyCollateral` function with the given `data`.
  /// @dev Interest are not accrued since it's not required and it saves gas.
  /// @dev Supplying a large amount can revert for overflow.
  /// @param marketParams The market to supply collateral to.
  /// @param assets The amount of collateral to supply.
  /// @param onBehalf The address that will own the increased collateral position.
  /// @param data Arbitrary data to pass to the `onMoolahSupplyCollateral` callback. Pass empty data if not needed.
  function supplyCollateral(
    MarketParams memory marketParams,
    uint256 assets,
    address onBehalf,
    bytes memory data
  ) external;

  /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
  /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
  /// @param marketParams The market to withdraw collateral from.
  /// @param assets The amount of collateral to withdraw.
  /// @param onBehalf The address of the owner of the collateral position.
  /// @param receiver The address that will receive the collateral assets.
  function withdrawCollateral(
    MarketParams memory marketParams,
    uint256 assets,
    address onBehalf,
    address receiver
  ) external;

  /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
  /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
  /// `onMoolahLiquidate` function with the given `data`.
  /// @dev Either `seizedAssets` or `repaidShares` should be zero.
  /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
  /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
  /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
  /// @param marketParams The market of the position.
  /// @param borrower The owner of the position.
  /// @param seizedAssets The amount of collateral to seize.
  /// @param repaidShares The amount of shares to repay.
  /// @param data Arbitrary data to pass to the `onMoolahLiquidate` callback. Pass empty data if not needed.
  /// @return The amount of assets seized.
  /// @return The amount of assets repaid.
  function liquidate(
    MarketParams memory marketParams,
    address borrower,
    uint256 seizedAssets,
    uint256 repaidShares,
    bytes memory data
  ) external returns (uint256, uint256);

  /// @notice Liquidates the broker position of `borrower` by burning `badDebtShares` from the fee recipient's supply
  /// position.
  /// @dev This function can only be called by the market's broker.
  /// @dev This function does not check whether the position is unhealthy. It is the broker's responsibility to only
  /// call this function when the position is unhealthy.
  /// @param marketParams The market of the position.
  /// @param borrower The owner of the position.
  /// @param badDebtShares The amount of borrow shares to liquidate.
  /// @return The amount of assets seized.
  /// @return The amount of assets repaid.
  function liquidateBrokerPosition(
    MarketParams memory marketParams,
    address borrower,
    uint256 badDebtShares
  ) external returns (uint256, uint256);

  /// @notice Executes a flash loan.
  /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
  /// markets combined, plus donations).
  /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
  /// - `flashFee` is zero.
  /// - `maxFlashLoan` is the token's balance of this contract.
  /// - The receiver of `assets` is the caller.
  /// @param token The token to flash loan.
  /// @param assets The amount of assets to flash loan.
  /// @param data Arbitrary data to pass to the `onMoolahFlashLoan` callback.
  function flashLoan(address token, uint256 assets, bytes calldata data) external;

  /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
  /// @param authorized The authorized address.
  /// @param newIsAuthorized The new authorization status.
  function setAuthorization(address authorized, bool newIsAuthorized) external;

  /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
  /// @dev Warning: Reverts if the signature has already been submitted.
  /// @dev The signature is malleable, but it has no impact on the security here.
  /// @dev The nonce is passed as argument to be able to revert with a different error message.
  /// @param authorization The `Authorization` struct.
  /// @param signature The signature.
  function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;

  /// @notice Accrues interest for the given market `marketParams`.
  function accrueInterest(MarketParams memory marketParams) external;

  /// @notice Add/removes `accounts` from the liquidation whitelist of markets `ids`.
  function batchToggleLiquidationWhitelist(Id[] memory ids, address[][] memory accounts, bool isAddition) external;

  /// @notice Returns the liquidation whitelist of the market `id`.
  function getLiquidationWhitelist(Id id) external view returns (address[] memory);

  /// @notice Returns whether `account` is in the liquidation whitelist of the market `id`.
  function isLiquidationWhitelist(Id id, address account) external view returns (bool);
  /// @notice Set the minimum loan token assets(USD) (supply and borrow).
  function setMinLoanValue(uint256 minLoan) external;

  /// @notice get the minimum loan token assets (supply and borrow) for the market.
  function minLoan(MarketParams memory marketParams) external view returns (uint256);

  /// @notice add/remove the provider for the token.
  function setProvider(Id id, address provider, bool isAddition) external;

  /// @notice get the provider for the market.
  function providers(Id id, address token) external view returns (address);

  /// @notice get the broker for the market
  function brokers(Id id) external view returns (address);

  /// @notice Return the whitelist of the market `id`.
  function getWhiteList(Id id) external view returns (address[] memory);

  /// @notice Returns `true` if `account` is whitelisted of market `id`.
  function isWhiteList(Id id, address account) external view returns (bool);

  /// @notice Add/Remove `account` from the whitelist of the market `id`.
  function setWhiteList(Id id, address account, bool isAddition) external;

  /// @notice Returns the default market fee.
  function defaultMarketFee() external view returns (uint256);

  /// @notice Returns whether `token` is blacklisted for flash loans.
  function flashLoanTokenBlacklist(address token) external view returns (bool);

  /// @notice Set the default market fee for new markets.
  function setDefaultMarketFee(uint256 newFee) external;

  /// @notice Sets the flash loan token blacklist status.
  function setFlashLoanTokenBlacklist(address token, bool isBlacklisted) external;

  /// @notice Returns whether `account` is blacklisted.
  function vaultBlacklist(address account) external view returns (bool);

  /// @notice Sets the blacklist status of `account`.
  function setVaultBlacklist(address account, bool isBlacklisted) external;

  /// @notice Set/Remove the market broker for the market `id`.
  function setMarketBroker(Id id, address broker, bool isAddition) external;
}

/// @dev This interface is inherited by Moolah so that function signatures are checked by the compiler.
/// @dev Consider using the IMoolah interface instead of this one.
interface IMoolahStaticTyping is IMoolahBase {
  /// @notice The state of the position of `user` on the market corresponding to `id`.
  /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
  /// accrual.
  function position(
    Id id,
    address user
  ) external view returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);

  /// @notice The state of the market corresponding to `id`.
  /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
  /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
  /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
  /// accrual.
  function market(
    Id id
  )
    external
    view
    returns (
      uint128 totalSupplyAssets,
      uint128 totalSupplyShares,
      uint128 totalBorrowAssets,
      uint128 totalBorrowShares,
      uint128 lastUpdate,
      uint128 fee
    );

  /// @notice The market params corresponding to `id`.
  /// @dev This mapping is not used in Moolah. It is there to enable reducing the cost associated to calldata on layer
  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
  function idToMarketParams(
    Id id
  ) external view returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);

  /// @notice Returns whether the position of `borrower` in the given market `marketParams` is healthy.
  function isHealthy(MarketParams memory marketParams, Id id, address borrower) external view returns (bool);
}

/// @title IMoolah
/// @author Lista DAO
/// @dev Use this interface for Moolah to have access to all the functions with the appropriate function signatures.
interface IMoolah is IMoolahBase {
  /// @notice The state of the position of `user` on the market corresponding to `id`.
  /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
  /// accrual.
  function position(Id id, address user) external view returns (Position memory p);

  /// @notice The state of the market corresponding to `id`.
  /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
  /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
  /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
  /// interest accrual.
  function market(Id id) external view returns (Market memory m);

  /// @notice The market params corresponding to `id`.
  /// @dev This mapping is not used in Moolah. It is there to enable reducing the cost associated to calldata on layer
  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
  function idToMarketParams(Id id) external view returns (MarketParams memory);

  function getPrice(MarketParams calldata marketParams) external view returns (uint256);

  function _getPrice(MarketParams memory marketParams, address user) external view returns (uint256);

  /// @notice grants `role` to `account`.
  function grantRole(bytes32 role, address account) external;
}

src/moolah/interfaces/IOracle.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

struct TokenConfig {
  /// @notice asset address
  address asset;
  /// @notice `oracles` stores the oracles based on their role in the following order:
  /// [main, pivot, fallback],
  /// It can be indexed with the corresponding enum OracleRole value
  address[3] oracles;
  /// @notice `enableFlagsForOracles` stores the enabled state
  /// for each oracle in the same order as `oracles`
  bool[3] enableFlagsForOracles;
  /// @notice `timeDeltaTolerance` stores the tolerance of
  /// the difference between the block timestamp and the price update time
  /// the unit is seconds
  uint256 timeDeltaTolerance;
}

/// @title IOracle
/// @author Lista Dao
/// @notice Interface that oracles used by Lista Dao must implement.
/// @dev It is the user's responsibility to select markets with safe oracles.
interface IOracle {
  function peek(address asset) external view returns (uint256);
  function getTokenConfig(address asset) external view returns (TokenConfig memory);
}

src/moolah/libraries/ErrorsLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

/// @title ErrorsLib
/// @author Lista DAO
/// @notice Library exposing error messages.
library ErrorsLib {
  /// @notice Thrown when the LLTV to enable exceeds the maximum LLTV.
  string internal constant MAX_LLTV_EXCEEDED = "max LLTV exceeded";

  /// @notice Thrown when the fee to set exceeds the maximum fee.
  string internal constant MAX_FEE_EXCEEDED = "max fee exceeded";

  /// @notice Thrown when the value is already set.
  string internal constant ALREADY_SET = "already set";

  /// @notice Thrown when the value is not set.
  string internal constant NOT_SET = "not set";

  /// @notice Thrown when the IRM is not enabled at market creation.
  string internal constant IRM_NOT_ENABLED = "IRM not enabled";

  /// @notice Thrown when the LLTV is not enabled at market creation.
  string internal constant LLTV_NOT_ENABLED = "LLTV not enabled";

  /// @notice Thrown when the market is already created.
  string internal constant MARKET_ALREADY_CREATED = "market already created";

  /// @notice Thrown when a token to transfer doesn't have code.
  string internal constant NO_CODE = "no code";

  /// @notice Thrown when the market is not created.
  string internal constant MARKET_NOT_CREATED = "market not created";

  /// @notice Thrown when not exactly one of the input amount is zero.
  string internal constant INCONSISTENT_INPUT = "inconsistent input";

  /// @notice Thrown when zero assets is passed as input.
  string internal constant ZERO_ASSETS = "zero assets";

  /// @notice Thrown when a zero address is passed as input.
  string internal constant ZERO_ADDRESS = "zero address";

  /// @notice Thrown when the caller is not authorized to conduct an action.
  string internal constant UNAUTHORIZED = "unauthorized";

  /// @notice Thrown when the caller is not provider.
  string internal constant NOT_PROVIDER = "not provider";

  /// @notice Thrown when the collateral is insufficient to `borrow` or `withdrawCollateral`.
  string internal constant INSUFFICIENT_COLLATERAL = "insufficient collateral";

  /// @notice Thrown when the liquidity is insufficient to `withdraw` or `borrow`.
  string internal constant INSUFFICIENT_LIQUIDITY = "insufficient liquidity";

  /// @notice Thrown when the position to liquidate is healthy.
  string internal constant HEALTHY_POSITION = "position is healthy";

  /// @notice Thrown when the position to liquidate is healthy.
  string internal constant UNHEALTHY_POSITION = "position is unhealthy";

  /// @notice Thrown when the authorization signature is invalid.
  string internal constant INVALID_SIGNATURE = "invalid signature";

  /// @notice Thrown when the authorization signature is expired.
  string internal constant SIGNATURE_EXPIRED = "signature expired";

  /// @notice Thrown when the nonce is invalid.
  string internal constant INVALID_NONCE = "invalid nonce";

  /// @notice Thrown when a token transfer reverted.
  string internal constant TRANSFER_REVERTED = "transfer reverted";

  /// @notice Thrown when a token transfer returned false.
  string internal constant TRANSFER_RETURNED_FALSE = "transfer returned false";

  /// @notice Thrown when a token transferFrom reverted.
  string internal constant TRANSFER_FROM_REVERTED = "transferFrom reverted";

  /// @notice Thrown when a token transferFrom returned false
  string internal constant TRANSFER_FROM_RETURNED_FALSE = "transferFrom returned false";

  /// @notice Thrown when the maximum uint128 is exceeded.
  string internal constant MAX_UINT128_EXCEEDED = "max uint128 exceeded";

  /// @notice Thrown when account is not in the liquidation whitelist.
  string internal constant NOT_LIQUIDATION_WHITELIST = "not liquidation whitelist";

  /// @notice Thrown when the caller is not in the whitelist.
  string internal constant NOT_WHITELIST = "not whitelist";

  /// @notice Thrown when the remaining supply is too low.
  string internal constant REMAIN_SUPPLY_TOO_LOW = "remain supply too low";

  /// @notice Thrown when the remaining borrow is too low.
  string internal constant REMAIN_BORROW_TOO_LOW = "remain borrow too low";

  string internal constant TOKEN_BLACKLISTED = "token blacklisted";

  /// @notice Thrown when broker's loan token or collateral token is invalid.
  string internal constant INVALID_BROKER = "invalid broker";

  string internal constant BLACKLISTED = "blacklisted";

  /// @notice Thrown when the caller is not a broker.
  string internal constant NOT_BROKER = "not broker";

  string internal constant BROKER_POSITION = "broker position cannot be liquidated directly";

  string internal constant EXCEED_MPC_CAP = "exceed mpc cap";

  string internal constant EXCEED_BORROW_SHARES = "exceed borrow shares";
}

src/moolah/libraries/MarketParamsLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

import { Id, MarketParams } from "../interfaces/IMoolah.sol";

/// @title MarketParamsLib
/// @author Lista DAO
/// @notice Library to convert a market to its id.
library MarketParamsLib {
  /// @notice The length of the data used to compute the id of a market.
  /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
  uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;

  /// @notice Returns the id of the market `marketParams`.
  function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
    assembly ("memory-safe") {
      marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
    }
  }
}

src/moolah/libraries/MathLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

uint256 constant WAD = 1e18;

/// @title MathLib
/// @author Lista DAO
/// @notice Library to manage fixed-point arithmetic.
library MathLib {
  /// @dev Returns (`x` * `y`) / `WAD` rounded down.
  function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
    return mulDivDown(x, y, WAD);
  }

  /// @dev Returns (`x` * `WAD`) / `y` rounded down.
  function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
    return mulDivDown(x, WAD, y);
  }

  /// @dev Returns (`x` * `WAD`) / `y` rounded up.
  function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
    return mulDivUp(x, WAD, y);
  }

  /// @dev Returns (`x` * `y`) / `d` rounded down.
  function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
    return (x * y) / d;
  }

  /// @dev Returns (`x` * `y`) / `d` rounded up.
  function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
    return (x * y + (d - 1)) / d;
  }

  /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
  /// continuous compound interest rate.
  function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
    uint256 firstTerm = x * n;
    uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
    uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);

    return firstTerm + secondTerm + thirdTerm;
  }
}

src/moolah/libraries/SharesMathLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

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

/// @title SharesMathLib
/// @author Lista DAO
/// @notice Shares management library.
/// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
/// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
library SharesMathLib {
  using MathLib for uint256;

  /// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
  /// high precision computations.
  /// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
  /// stays low enough not to inflate these assets to a significant value.
  /// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
  uint256 internal constant VIRTUAL_SHARES = 1e6;

  /// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
  /// empty.
  uint256 internal constant VIRTUAL_ASSETS = 1;

  /// @dev Calculates the value of `assets` quoted in shares, rounding down.
  function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
    return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
  }

  /// @dev Calculates the value of `shares` quoted in assets, rounding down.
  function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
    return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
  }

  /// @dev Calculates the value of `assets` quoted in shares, rounding up.
  function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
    return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
  }

  /// @dev Calculates the value of `shares` quoted in assets, rounding up.
  function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
    return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
  }
}

src/moolah/libraries/UtilsLib.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

import { ErrorsLib } from "../libraries/ErrorsLib.sol";

/// @title UtilsLib
/// @author Lista DAO
/// @notice Library exposing helpers.
library UtilsLib {
  /// @dev Returns true if there is exactly one zero among `x` and `y`.
  function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
    assembly {
      z := xor(iszero(x), iszero(y))
    }
  }

  /// @dev Returns the min of `x` and `y`.
  function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
    assembly {
      z := xor(x, mul(xor(x, y), lt(y, x)))
    }
  }

  /// @dev Returns `x` safely cast to uint128.
  function toUint128(uint256 x) internal pure returns (uint128) {
    require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);
    return uint128(x);
  }

  /// @dev Returns max(0, x - y).
  function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
    assembly {
      z := mul(gt(x, y), sub(x, y))
    }
  }
}

src/provider/interfaces/IProvider.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

import { MarketParams, Id } from "moolah/interfaces/IMoolah.sol";

interface IProvider {
  function liquidate(Id id, address borrower) external;

  function TOKEN() external view returns (address);
}
interface ISlisBnbProvider is IProvider {
  function supplyCollateral(
    MarketParams memory marketParams,
    uint256 assets,
    address onBehalf,
    bytes calldata data
  ) external;

  function withdrawCollateral(
    MarketParams memory marketParams,
    uint256 assets,
    address onBehalf,
    address receiver
  ) external;

  function userTotalDeposit(address account) external view returns (uint256);

  function slisBNBxMinter() external view returns (address);

  function STAKE_MANAGER() external view returns (address);

  function MOOLAH() external view returns (address);
}
interface ISmartProvider is IProvider {
  function dexLP() external view returns (address);

  function token(uint256 id) external view returns (address);

  function redeemLpCollateral(
    uint256 lpAmount,
    uint256 minToken0Out,
    uint256 minToken1Out
  ) external returns (uint256 token0Out, uint256 token1Out);
}

src/utils/interfaces/ISlisBNBx.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.34;

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

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface ISlisBNBx is IERC20 {
  function burn(address account, uint256 amount) external;

  function mint(address account, uint256 amount) external;

  function decimals() external view returns (uint8);

  function addMinter(address minter) external;
}

interface ISlisBNBxModule {
  /// @notice Get user balance in BNB
  function getUserBalanceInBnb(address account) external pure returns (uint256);
}

interface ISlisBNBxMinter {
  function userModuleBalance(address account, address module) external view returns (uint256 userPart, uint256 feePart);

  /// @notice Rebalance user slisBNB tokens
  /// @param account The user address
  /// @return success True if rebalance is successful and new slisBNBx balance
  function rebalance(address account) external returns (bool, uint256);

  /// @notice Sync delegatee for user; can only be called by a module
  function syncDelegatee(address account, address newDelegatee) external;

  /// @notice Delegate all of the caller's slisBNBx to `newDelegatee`
  function delegateAllTo(address newDelegatee) external;

  /// @notice Get delegatee for user
  function delegation(address account) external view returns (address);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 20,
    "enabled": true
  },
  "evmVersion": "osaka",
  "remappings": [
    "@src/=src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "moolah/=src/moolah/",
    "moolah-vault/=src/moolah-vault/",
    "liquidator/=src/liquidator/",
    "interest-rate-model/=src/interest-rate-model/",
    "vault-allocator/=src/vault-allocator/",
    "@solady/=lib/solady/src/",
    "forge-std/=lib/forge-std/src/",
    "timelock/=src/timelock/",
    "revenue/=src/revenue/",
    "murky/=lib/murky/",
    "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol",
    "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol",
    "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol",
    "lib/lista-dao-contracts.git/:@openzeppelin/contracts-upgradeable/=lib/lista-dao-contracts.git/node_modules/@openzeppelin/contracts-upgradeable/",
    "@chainlink/=lib/lista-dao-contracts.git/node_modules/@chainlink/",
    "@pythnetwork/=lib/lista-dao-contracts.git/node_modules/@pythnetwork/",
    "ds-test/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "eth-gas-reporter/=lib/lista-dao-contracts.git/node_modules/eth-gas-reporter/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/lista-dao-contracts.git/node_modules/hardhat/",
    "lista-dao-contracts.git/=lib/lista-dao-contracts.git/contracts/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/murky/lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "solady/=lib/solady/src/",
    "solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.