ETH Price: $2,128.09 (+2.77%)

Contract

0x7CACd4E098E2837643eEAaAefC040B87dF29c332
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
AaveFundingPool

Compiler Version
v0.8.26+commit.8a97fa7a

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { IAaveV3Pool } from "../../interfaces/Aave/IAaveV3Pool.sol";
import { IAaveFundingPool } from "../../interfaces/IAaveFundingPool.sol";
import { IPegKeeper } from "../../interfaces/IPegKeeper.sol";

import { WordCodec } from "../../common/codec/WordCodec.sol";
import { Math } from "../../libraries/Math.sol";
import { BasePool } from "./BasePool.sol";

contract AaveFundingPool is BasePool, IAaveFundingPool {
  using WordCodec for bytes32;

  /*************
   * Constants *
   *************/

  /// @dev The offset of *open ratio* in `fundingMiscData`.
  uint256 private constant OPEN_RATIO_OFFSET = 0;

  /// @dev The offset of *open ratio step* in `fundingMiscData`.
  uint256 private constant OPEN_RATIO_STEP_OFFSET = 30;

  /// @dev The offset of *close fee ratio* in `fundingMiscData`.
  uint256 private constant CLOSE_FEE_RATIO_OFFSET = 90;

  /// @dev The offset of *funding ratio* in `fundingMiscData`.
  uint256 private constant FUNDING_RATIO_OFFSET = 120;

  /// @dev The offset of *interest rate* in `fundingMiscData`.
  uint256 private constant INTEREST_RATE_OFFSET = 152;

  /// @dev The offset of *timestamp* in `fundingMiscData`.
  uint256 private constant TIMESTAMP_OFFSET = 220;

  /// @dev The maximum value of *funding ratio*.
  uint256 private constant MAX_FUNDING_RATIO = 4294967295;

  /// @dev The minimum Aave borrow index snapshot delay.
  uint256 private constant MIN_SNAPSHOT_DELAY = 30 minutes;

  /***********************
   * Immutable Variables *
   ***********************/

  /// @dev The address of Aave V3 `LendingPool` contract.
  address private immutable lendingPool;

  /// @dev The address of asset used for interest calculation.
  address private immutable baseAsset;

  /***********
   * Structs *
   ***********/

  /// @dev The struct for AAVE borrow rate snapshot.
  /// @param borrowIndex The current borrow index of AAVE, multiplied by 1e27.
  /// @param lastInterestRate The last recorded interest rate, multiplied by 1e18.
  /// @param timestamp The timestamp when the snapshot is taken.
  struct BorrowRateSnapshot {
    // The initial value of `borrowIndex` is `10^27`, it is very unlikely this value will exceed `2^128`.
    uint128 borrowIndex;
    uint80 lastInterestRate;
    uint48 timestamp;
  }

  /*********************
   * Storage Variables *
   *********************/

  /// @dev `fundingMiscData` is a storage slot that can be used to store unrelated pieces of information.
  ///
  /// - The *open ratio* is the fee ratio for opening position, multiplied by 1e9.
  /// - The *open ratio step* is the fee ratio step for opening position, multiplied by 1e18.
  /// - The *close fee ratio* is the fee ratio for closing position, multiplied by 1e9.
  /// - The *funding ratio* is the scalar for funding rate, multiplied by 1e9.
  ///   The maximum value is `4.294967296`.
  ///
  /// [ open ratio | open ratio step | close fee ratio | funding ratio | reserved ]
  /// [  30  bits  |     60 bits     |     30 bits     |    32 bits    | 104 bits ]
  /// [ MSB                                                                   LSB ]
  bytes32 private fundingMiscData;

  /// @notice The snapshot for AAVE borrow rate.
  BorrowRateSnapshot public borrowRateSnapshot;

  /***************
   * Constructor *
   ***************/

  constructor(address _poolManager, address _lendingPool, address _baseAsset) BasePool(_poolManager) {
    _checkAddressNotZero(_lendingPool);
    _checkAddressNotZero(_baseAsset);

    lendingPool = _lendingPool;
    baseAsset = _baseAsset;
  }

  function initialize(
    address admin,
    string memory name_,
    string memory symbol_,
    address _collateralToken,
    address _priceOracle
  ) external initializer {
    __Context_init();
    __ERC165_init();
    __ERC721_init(name_, symbol_);
    __AccessControl_init();

    __PoolStorage_init(_collateralToken, _priceOracle);
    __TickLogic_init();
    __PositionLogic_init();
    __BasePool_init();

    _grantRole(DEFAULT_ADMIN_ROLE, admin);

    _updateOpenRatio(1000000, 50000000000000000); // 0.1% and 5%
    _updateCloseFeeRatio(1000000); // 0.1%

    uint256 borrowIndex = IAaveV3Pool(lendingPool).getReserveNormalizedVariableDebt(baseAsset);
    IAaveV3Pool.ReserveDataLegacy memory reserveData = IAaveV3Pool(lendingPool).getReserveData(baseAsset);
    _updateInterestRate(borrowIndex, reserveData.currentVariableBorrowRate / 1e9);
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Get open fee ratio related parameters.
  /// @return ratio The value of open ratio, multiplied by 1e9.
  /// @return step The value of open ratio step, multiplied by 1e18.
  function getOpenRatio() external view returns (uint256 ratio, uint256 step) {
    return _getOpenRatio();
  }

  /// @notice Return the value of funding ratio, multiplied by 1e9.
  function getFundingRatio() external view returns (uint256) {
    return _getFundingRatio();
  }

  /// @notice Return the fee ratio for opening position, multiplied by 1e9.
  function getOpenFeeRatio() public view returns (uint256) {
    (uint256 openRatio, uint256 openRatioStep) = _getOpenRatio();
    (, uint256 rate) = _getAverageInterestRate(borrowRateSnapshot);
    unchecked {
      uint256 aaveRatio = rate <= openRatioStep ? 1 : (rate - 1) / openRatioStep;
      return aaveRatio * openRatio;
    }
  }

  /// @notice Return the fee ratio for closing position, multiplied by 1e9.
  function getCloseFeeRatio() external view returns (uint256) {
    return _getCloseFeeRatio();
  }

  /************************
   * Restricted Functions *
   ************************/

  /// @notice Update the fee ratio for opening position.
  /// @param ratio The open ratio value, multiplied by 1e9.
  /// @param step The open ratio step value, multiplied by 1e18.
  function updateOpenRatio(uint256 ratio, uint256 step) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateOpenRatio(ratio, step);
  }

  /// @notice Update the fee ratio for closing position.
  /// @param ratio The close ratio value, multiplied by 1e9.
  function updateCloseFeeRatio(uint256 ratio) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateCloseFeeRatio(ratio);
  }

  /// @notice Update the funding ratio.
  /// @param ratio The funding ratio value, multiplied by 1e9.
  function updateFundingRatio(uint256 ratio) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateFundingRatio(ratio);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to get open ratio and open ratio step.
  /// @return ratio The value of open ratio, multiplied by 1e9.
  /// @return step The value of open ratio step, multiplied by 1e18.
  function _getOpenRatio() internal view returns (uint256 ratio, uint256 step) {
    bytes32 data = fundingMiscData;
    ratio = data.decodeUint(OPEN_RATIO_OFFSET, 30);
    step = data.decodeUint(OPEN_RATIO_STEP_OFFSET, 60);
  }

  /// @dev Internal function to update the fee ratio for opening position.
  /// @param ratio The open ratio value, multiplied by 1e9.
  /// @param step The open ratio step value, multiplied by 1e18.
  function _updateOpenRatio(uint256 ratio, uint256 step) internal {
    _checkValueTooLarge(ratio, FEE_PRECISION);
    _checkValueTooLarge(step, PRECISION);

    bytes32 data = fundingMiscData;
    data = data.insertUint(ratio, OPEN_RATIO_OFFSET, 30);
    fundingMiscData = data.insertUint(step, OPEN_RATIO_STEP_OFFSET, 60);

    emit UpdateOpenRatio(ratio, step);
  }

  /// @dev Internal function to get the value of close ratio, multiplied by 1e9.
  function _getCloseFeeRatio() internal view returns (uint256) {
    return fundingMiscData.decodeUint(CLOSE_FEE_RATIO_OFFSET, 30);
  }

  /// @dev Internal function to update the fee ratio for closing position.
  /// @param newRatio The close fee ratio value, multiplied by 1e9.
  function _updateCloseFeeRatio(uint256 newRatio) internal {
    _checkValueTooLarge(newRatio, FEE_PRECISION);

    bytes32 data = fundingMiscData;
    uint256 oldRatio = data.decodeUint(CLOSE_FEE_RATIO_OFFSET, 30);
    fundingMiscData = data.insertUint(newRatio, CLOSE_FEE_RATIO_OFFSET, 30);

    emit UpdateCloseFeeRatio(oldRatio, newRatio);
  }

  /// @dev Internal function to get the value of funding ratio, multiplied by 1e9.
  function _getFundingRatio() internal view returns (uint256) {
    return fundingMiscData.decodeUint(FUNDING_RATIO_OFFSET, 32);
  }

  /// @dev Internal function to update the funding ratio.
  /// @param newRatio The funding ratio value, multiplied by 1e9.
  function _updateFundingRatio(uint256 newRatio) internal {
    _checkValueTooLarge(newRatio, MAX_FUNDING_RATIO);

    bytes32 data = fundingMiscData;
    uint256 oldRatio = data.decodeUint(FUNDING_RATIO_OFFSET, 32);
    fundingMiscData = data.insertUint(newRatio, FUNDING_RATIO_OFFSET, 32);

    emit UpdateFundingRatio(oldRatio, newRatio);
  }

  /// @dev Internal function to return interest rate snapshot.
  /// @param snapshot The previous borrow index snapshot.
  /// @return newBorrowIndex The current borrow index, multiplied by 1e27.
  /// @return rate The annual interest rate, multiplied by 1e18.
  function _getAverageInterestRate(
    BorrowRateSnapshot memory snapshot
  ) internal view returns (uint256 newBorrowIndex, uint256 rate) {
    uint256 prevBorrowIndex = snapshot.borrowIndex;
    newBorrowIndex = IAaveV3Pool(lendingPool).getReserveNormalizedVariableDebt(baseAsset);
    // absolute rate change is (new - prev) / prev
    // annual interest rate is (new - prev) / prev / duration * 365 days
    uint256 duration = block.timestamp - snapshot.timestamp;
    // @note Users can trigger this every `MIN_SNAPSHOT_DELAY` seconds and make the interest rate never change.
    // We allow users to do so, since the risk is not very high. And if we remove this if, the computed interest
    // rate may not correct due to small `duration`.
    if (duration < MIN_SNAPSHOT_DELAY) {
      rate = snapshot.lastInterestRate;
    } else {
      rate = ((newBorrowIndex - prevBorrowIndex) * 365 days * PRECISION) / (prevBorrowIndex * duration);
      if (rate == 0) rate = snapshot.lastInterestRate;
    }
  }

  /// @dev Internal function to update interest rate snapshot.
  function _updateInterestRate(uint256 newBorrowIndex, uint256 lastInterestRate) internal {
    BorrowRateSnapshot memory snapshot = borrowRateSnapshot;
    snapshot.borrowIndex = uint128(newBorrowIndex);
    snapshot.lastInterestRate = uint80(lastInterestRate);
    snapshot.timestamp = uint48(block.timestamp);
    borrowRateSnapshot = snapshot;

    emit SnapshotAaveBorrowIndex(newBorrowIndex, block.timestamp);
  }

  /// @inheritdoc BasePool
  function _updateCollAndDebtIndex() internal virtual override returns (uint256 newCollIndex, uint256 newDebtIndex) {
    (newDebtIndex, newCollIndex) = _getDebtAndCollateralIndex();

    BorrowRateSnapshot memory snapshot = borrowRateSnapshot;
    uint256 duration = block.timestamp - snapshot.timestamp;
    if (duration > 0) {
      (uint256 borrowIndex, uint256 interestRate) = _getAverageInterestRate(snapshot);
      if (IPegKeeper(pegKeeper).isFundingEnabled()) {
        (, uint256 totalColls) = _getDebtAndCollateralShares();
        uint256 totalRawColls = _convertToRawColl(totalColls, newCollIndex, Math.Rounding.Down);
        uint256 funding = (totalRawColls * interestRate * duration) / (365 days * PRECISION);
        funding = ((funding * _getFundingRatio()) / FEE_PRECISION);

        // update collateral index with funding costs
        newCollIndex = (newCollIndex * totalRawColls) / (totalRawColls - funding);
        _updateCollateralIndex(newCollIndex);
      }

      // update interest snapshot
      _updateInterestRate(borrowIndex, interestRate);
    }
  }

  /// @inheritdoc BasePool
  function _deductProtocolFees(int256 rawColl) internal view virtual override returns (uint256) {
    if (rawColl > 0) {
      // open position or add collateral
      uint256 feeRatio = getOpenFeeRatio();
      if (feeRatio > FEE_PRECISION) feeRatio = FEE_PRECISION;
      return (uint256(rawColl) * feeRatio) / FEE_PRECISION;
    } else {
      // close position or remove collateral
      return (uint256(-rawColl) * _getCloseFeeRatio()) / FEE_PRECISION;
    }
  }
}

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

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

File 4 of 32 : ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.20;

import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../../utils/introspection/ERC165Upgradeable.sol";
import {IERC721Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
abstract contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721, IERC721Metadata, IERC721Errors {
    using Strings for uint256;

    /// @custom:storage-location erc7201:openzeppelin.storage.ERC721
    struct ERC721Storage {
        // Token name
        string _name;

        // Token symbol
        string _symbol;

        mapping(uint256 tokenId => address) _owners;

        mapping(address owner => uint256) _balances;

        mapping(uint256 tokenId => address) _tokenApprovals;

        mapping(address owner => mapping(address operator => bool)) _operatorApprovals;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC721")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC721StorageLocation = 0x80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab0079300;

    function _getERC721Storage() private pure returns (ERC721Storage storage $) {
        assembly {
            $.slot := ERC721StorageLocation
        }
    }

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC721_init_unchained(name_, symbol_);
    }

    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC721Storage storage $ = _getERC721Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual returns (uint256) {
        ERC721Storage storage $ = _getERC721Storage();
        if (owner == address(0)) {
            revert ERC721InvalidOwner(address(0));
        }
        return $._balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual returns (address) {
        return _requireOwned(tokenId);
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual returns (string memory) {
        ERC721Storage storage $ = _getERC721Storage();
        return $._name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual returns (string memory) {
        ERC721Storage storage $ = _getERC721Storage();
        return $._symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
        _requireOwned(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual {
        _approve(to, tokenId, _msgSender());
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual returns (address) {
        _requireOwned(tokenId);

        return _getApproved(tokenId);
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
        ERC721Storage storage $ = _getERC721Storage();
        return $._operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(address from, address to, uint256 tokenId) public virtual {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        // Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
        address previousOwner = _update(to, tokenId, _msgSender());
        if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) public {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
        transferFrom(from, to, tokenId);
        _checkOnERC721Received(from, to, tokenId, data);
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     *
     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
     * core ERC721 logic MUST be matched with the use of {_increaseBalance} to keep balances
     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        ERC721Storage storage $ = _getERC721Storage();
        return $._owners[tokenId];
    }

    /**
     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
     */
    function _getApproved(uint256 tokenId) internal view virtual returns (address) {
        ERC721Storage storage $ = _getERC721Storage();
        return $._tokenApprovals[tokenId];
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
     * particular (ignoring whether it is owned by `owner`).
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
        return
            spender != address(0) &&
            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
    }

    /**
     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
     * Reverts if `spender` does not have approval from the provided `owner` for the given token or for all its assets
     * the `spender` for the specific `tokenId`.
     *
     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
     * assumption.
     */
    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
        if (!_isAuthorized(owner, spender, tokenId)) {
            if (owner == address(0)) {
                revert ERC721NonexistentToken(tokenId);
            } else {
                revert ERC721InsufficientApproval(spender, tokenId);
            }
        }
    }

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
     *
     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the
     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
     * remain consistent with one another.
     */
    function _increaseBalance(address account, uint128 value) internal virtual {
        ERC721Storage storage $ = _getERC721Storage();
        unchecked {
            $._balances[account] += value;
        }
    }

    /**
     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that
     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).
     *
     * Emits a {Transfer} event.
     *
     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
     */
    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
        ERC721Storage storage $ = _getERC721Storage();
        address from = _ownerOf(tokenId);

        // Perform (optional) operator check
        if (auth != address(0)) {
            _checkAuthorized(from, auth, tokenId);
        }

        // Execute the update
        if (from != address(0)) {
            // Clear approval. No need to re-authorize or emit the Approval event
            _approve(address(0), tokenId, address(0), false);

            unchecked {
                $._balances[from] -= 1;
            }
        }

        if (to != address(0)) {
            unchecked {
                $._balances[to] += 1;
            }
        }

        $._owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        return from;
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner != address(0)) {
            revert ERC721InvalidSender(address(0));
        }
    }

    /**
     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
        _mint(to, tokenId);
        _checkOnERC721Received(address(0), to, tokenId, data);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal {
        address previousOwner = _update(address(0), tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(address from, address to, uint256 tokenId) internal {
        if (to == address(0)) {
            revert ERC721InvalidReceiver(address(0));
        }
        address previousOwner = _update(to, tokenId, address(0));
        if (previousOwner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        } else if (previousOwner != from) {
            revert ERC721IncorrectOwner(from, tokenId, previousOwner);
        }
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
     * are aware of the ERC721 standard to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is like {safeTransferFrom} in the sense that it invokes
     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `tokenId` token must exist and be owned by `from`.
     * - `to` cannot be the zero address.
     * - `from` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(address from, address to, uint256 tokenId) internal {
        _safeTransfer(from, to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
        _transfer(from, to, tokenId);
        _checkOnERC721Received(from, to, tokenId, data);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
     * either the owner of the token, or approved to operate on all tokens held by this owner.
     *
     * Emits an {Approval} event.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address to, uint256 tokenId, address auth) internal {
        _approve(to, tokenId, auth, true);
    }

    /**
     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
     * emitted in the context of transfers.
     */
    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
        ERC721Storage storage $ = _getERC721Storage();
        // Avoid reading the owner unless necessary
        if (emitEvent || auth != address(0)) {
            address owner = _requireOwned(tokenId);

            // We do not use _isAuthorized because single-token approvals should not be able to call approve
            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
                revert ERC721InvalidApprover(auth);
            }

            if (emitEvent) {
                emit Approval(owner, to, tokenId);
            }
        }

        $._tokenApprovals[tokenId] = to;
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Requirements:
     * - operator can't be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        ERC721Storage storage $ = _getERC721Storage();
        if (operator == address(0)) {
            revert ERC721InvalidOperator(operator);
        }
        $._operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
     * Returns the owner.
     *
     * Overrides to ownership logic should be done to {_ownerOf}.
     */
    function _requireOwned(uint256 tokenId) internal view returns (address) {
        address owner = _ownerOf(tokenId);
        if (owner == address(0)) {
            revert ERC721NonexistentToken(tokenId);
        }
        return owner;
    }

    /**
     * @dev Private function to invoke {IERC721Receiver-onERC721Received} on a target address. This will revert if the
     * recipient doesn't accept the token transfer. The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     */
    function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory data) private {
        if (to.code.length > 0) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                if (retval != IERC721Receiver.onERC721Received.selector) {
                    revert ERC721InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert ERC721InvalidReceiver(to);
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        }
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC165 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;
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 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, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
     *   {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
     *   a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the address zero.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}

File 11 of 32 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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);
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

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

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

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

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

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

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

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// solhint-disable no-inline-assembly

/// @dev A subset copied from the following contracts:
///
/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol`
/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol`
library WordCodec {
  /// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word,
  /// replacing the old value. Returns the new word.
  function insertUint(
    bytes32 word,
    uint256 value,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (bytes32 result) {
    // Equivalent to:
    // uint256 mask = (1 << bitLength) - 1;
    // bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));
    // result = clearedWord | bytes32(value << offset);
    assembly {
      let mask := sub(shl(bitLength, 1), 1)
      let clearedWord := and(word, not(shl(offset, mask)))
      result := or(clearedWord, shl(offset, value))
    }
  }

  /// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word.
  function decodeUint(
    bytes32 word,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (uint256 result) {
    // Equivalent to:
    // result = uint256(word >> offset) & ((1 << bitLength) - 1);
    assembly {
      result := and(shr(offset, word), sub(shl(bitLength, 1), 1))
    }
  }

  /// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
  /// the new word.
  ///
  /// Assumes `value` can be represented using `bitLength` bits.
  function insertInt(
    bytes32 word,
    int256 value,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (bytes32) {
    unchecked {
      uint256 mask = (1 << bitLength) - 1;
      bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));
      // Integer values need masking to remove the upper bits of negative values.
      return clearedWord | bytes32((uint256(value) & mask) << offset);
    }
  }

  /// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word.
  function decodeInt(
    bytes32 word,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (int256 result) {
    unchecked {
      int256 maxInt = int256((1 << (bitLength - 1)) - 1);
      uint256 mask = (1 << bitLength) - 1;

      int256 value = int256(uint256(word >> offset) & mask);
      // In case the decoded value is greater than the max positive integer that can be represented with bitLength
      // bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
      // representation.
      //
      // Equivalent to:
      // result = value > maxInt ? (value | int256(~mask)) : value;
      assembly {
        result := or(mul(gt(value, maxInt), not(mask)), value)
      }
    }
  }

  /// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
  function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) {
    // Equivalent to:
    // result = (uint256(word >> offset) & 1) == 1;
    assembly {
      result := and(shr(offset, word), 1)
    }
  }

  /// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
  /// word.
  function insertBool(
    bytes32 word,
    bool value,
    uint256 offset
  ) internal pure returns (bytes32 result) {
    // Equivalent to:
    // bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset));
    // bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
    assembly {
      let clearedWord := and(word, not(shl(offset, 1)))
      result := or(clearedWord, shl(offset, value))
    }
  }

  function clearWordAtPosition(
    bytes32 word,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (bytes32 clearedWord) {
    unchecked {
      uint256 mask = (1 << bitLength) - 1;
      clearedWord = bytes32(uint256(word) & ~(mask << offset));
    }
  }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { IPegKeeper } from "../../interfaces/IPegKeeper.sol";
import { IPool } from "../../interfaces/IPool.sol";
import { IPoolManager } from "../../interfaces/IPoolManager.sol";
import { IPriceOracle } from "../../price-oracle/interfaces/IPriceOracle.sol";

import { WordCodec } from "../../common/codec/WordCodec.sol";
import { Math } from "../../libraries/Math.sol";
import { TickBitmap } from "../../libraries/TickBitmap.sol";
import { PositionLogic } from "./PositionLogic.sol";
import { TickLogic } from "./TickLogic.sol";

abstract contract BasePool is TickLogic, PositionLogic {
  using TickBitmap for mapping(int8 => uint256);
  using WordCodec for bytes32;

  /***********
   * Structs *
   ***********/

  struct OperationMemoryVar {
    int256 tick;
    uint48 node;
    uint256 positionColl;
    uint256 positionDebt;
    int256 newColl;
    int256 newDebt;
    uint256 collIndex;
    uint256 debtIndex;
    uint256 globalColl;
    uint256 globalDebt;
    uint256 price;
  }

  /*************
   * Modifiers *
   *************/

  modifier onlyPoolManager() {
    if (_msgSender() != poolManager) {
      revert ErrorCallerNotPoolManager();
    }
    _;
  }

  /***************
   * Constructor *
   ***************/

  constructor(address _poolManager) {
    _checkAddressNotZero(_poolManager);

    poolManager = _poolManager;
    fxUSD = IPoolManager(_poolManager).fxUSD();
    pegKeeper = IPoolManager(_poolManager).pegKeeper();
  }

  function __BasePool_init() internal onlyInitializing {
    _updateDebtIndex(E96);
    _updateCollateralIndex(E96);
    _updateDebtRatioRange(500000000000000000, 857142857142857142); // 1/2 ~ 6/7
    _updateMaxRedeemRatioPerTick(200000000); // 20%
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @inheritdoc IPool
  function operate(
    uint256 positionId,
    int256 newRawColl,
    int256 newRawDebt,
    address owner
  ) external onlyPoolManager returns (uint256, int256, int256, uint256) {
    if (newRawColl == 0 && newRawDebt == 0) revert ErrorNoSupplyAndNoBorrow();
    if (newRawColl != 0 && (newRawColl > -MIN_COLLATERAL && newRawColl < MIN_COLLATERAL)) {
      revert ErrorCollateralTooSmall();
    }
    if (newRawDebt != 0 && (newRawDebt > -MIN_DEBT && newRawDebt < MIN_DEBT)) {
      revert ErrorDebtTooSmall();
    }
    if (newRawDebt > 0 && (_isBorrowPaused() || !IPegKeeper(pegKeeper).isBorrowAllowed())) {
      revert ErrorBorrowPaused();
    }

    OperationMemoryVar memory op;
    // price precision and ratio precision are both 1e18, use min price here
    op.price = IPriceOracle(priceOracle).getExchangePrice();
    (op.globalDebt, op.globalColl) = _getDebtAndCollateralShares();
    (op.collIndex, op.debtIndex) = _updateCollAndDebtIndex();
    if (positionId == 0) {
      positionId = _mintPosition(owner);
    } else {
      // make sure position is owned and check owner only in case of withdraw or borrow
      if (ownerOf(positionId) != owner && (newRawColl < 0 || newRawDebt > 0)) {
        revert ErrorNotPositionOwner();
      }
      PositionInfo memory position = _getAndUpdatePosition(positionId);
      // temporarily remove position from tick tree for simplicity
      _removePositionFromTick(position);
      op.tick = position.tick;
      op.node = position.nodeId;
      op.positionDebt = position.debts;
      op.positionColl = position.colls;

      // cannot withdraw or borrow when the position is above liquidation ratio
      if (newRawColl < 0 || newRawDebt > 0) {
        uint256 rawColls = _convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down);
        uint256 rawDebts = _convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Down);
        (uint256 debtRatio, ) = _getLiquidateRatios();
        if (rawDebts * PRECISION * PRECISION > debtRatio * rawColls * op.price) revert ErrorPositionInLiquidationMode();
      }
    }

    uint256 protocolFees;
    // supply or withdraw
    if (newRawColl > 0) {
      protocolFees = _deductProtocolFees(newRawColl);
      newRawColl -= int256(protocolFees);
      op.newColl = int256(_convertToCollShares(uint256(newRawColl), op.collIndex, Math.Rounding.Down));
      op.positionColl += uint256(op.newColl);
      op.globalColl += uint256(op.newColl);
    } else if (newRawColl < 0) {
      if (newRawColl == type(int256).min) {
        // this is max withdraw
        newRawColl = -int256(_convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down));
        op.newColl = -int256(op.positionColl);
      } else {
        // this is partial withdraw, rounding up removing extra wei from collateral
        op.newColl = -int256(_convertToCollShares(uint256(-newRawColl), op.collIndex, Math.Rounding.Up));
        if (uint256(-op.newColl) > op.positionColl) revert ErrorWithdrawExceedSupply();
      }
      unchecked {
        op.positionColl -= uint256(-op.newColl);
        op.globalColl -= uint256(-op.newColl);
      }
      protocolFees = _deductProtocolFees(newRawColl);
      newRawColl += int256(protocolFees);
    }

    // borrow or repay
    if (newRawDebt > 0) {
      // rounding up adding extra wei in debt
      op.newDebt = int256(_convertToDebtShares(uint256(newRawDebt), op.debtIndex, Math.Rounding.Up));
      op.positionDebt += uint256(op.newDebt);
      op.globalDebt += uint256(op.newDebt);
    } else if (newRawDebt < 0) {
      if (newRawDebt == type(int256).min) {
        // this is max repay, rounding up amount that will be transferred in to pay back full debt:
        // subtracting -1 of negative debtAmount newDebt_ for safe rounding (increasing payback)
        newRawDebt = -int256(_convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Up));
        op.newDebt = -int256(op.positionDebt);
      } else {
        // this is partial repay, safe rounding up negative amount to rounding reduce payback
        op.newDebt = -int256(_convertToDebtShares(uint256(-newRawDebt), op.debtIndex, Math.Rounding.Up));
      }
      op.positionDebt -= uint256(-op.newDebt);
      op.globalDebt -= uint256(-op.newDebt);
    }

    // final debt ratio check
    {
      // check position debt ratio is between `minDebtRatio` and `maxDebtRatio`.
      uint256 rawColls = _convertToRawColl(op.positionColl, op.collIndex, Math.Rounding.Down);
      uint256 rawDebts = _convertToRawDebt(op.positionDebt, op.debtIndex, Math.Rounding.Down);
      (uint256 minDebtRatio, uint256 maxDebtRatio) = _getDebtRatioRange();
      if (rawDebts * PRECISION * PRECISION > maxDebtRatio * rawColls * op.price) revert ErrorDebtRatioTooLarge();
      if (rawDebts * PRECISION * PRECISION < minDebtRatio * rawColls * op.price) revert ErrorDebtRatioTooSmall();
    }

    // update position state to storage
    (op.tick, op.node) = _addPositionToTick(op.positionColl, op.positionDebt, true);

    if (op.positionColl > type(uint96).max) revert ErrorOverflow();
    if (op.positionDebt > type(uint96).max) revert ErrorOverflow();
    positionData[positionId] = PositionInfo(int16(op.tick), op.node, uint96(op.positionColl), uint96(op.positionDebt));

    // update global state to storage
    _updateDebtAndCollateralShares(op.globalDebt, op.globalColl);

    emit PositionSnapshot(positionId, int16(op.tick), op.positionColl, op.positionDebt, op.price);

    return (positionId, newRawColl, newRawDebt, protocolFees);
  }

  /// @inheritdoc IPool
  function redeem(uint256 rawDebts) external onlyPoolManager returns (uint256 rawColls) {
    if (_isRedeemPaused()) revert ErrorRedeemPaused();

    (uint256 cachedCollIndex, uint256 cachedDebtIndex) = _updateCollAndDebtIndex();
    (uint256 cachedTotalDebts, uint256 cachedTotalColls) = _getDebtAndCollateralShares();
    uint256 price = IPriceOracle(priceOracle).getRedeemPrice();
    // check global debt ratio, if global debt ratio >= 1, disable redeem
    {
      uint256 totalRawColls = _convertToRawColl(cachedTotalColls, cachedCollIndex, Math.Rounding.Down);
      uint256 totalRawDebts = _convertToRawDebt(cachedTotalDebts, cachedDebtIndex, Math.Rounding.Down);
      if (totalRawDebts * PRECISION >= totalRawColls * price) revert ErrorPoolUnderCollateral();
    }

    int16 tick = _getTopTick();
    bool hasDebt = true;
    uint256 debtShare = _convertToDebtShares(rawDebts, cachedDebtIndex, Math.Rounding.Down);
    while (debtShare > 0) {
      if (!hasDebt) {
        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
      } else {
        uint256 node = tickData[tick];
        bytes32 value = tickTreeData[node].value;
        uint256 tickDebtShare = value.decodeUint(DEBT_SHARE_OFFSET, 128);
        // skip bad debt
        {
          uint256 tickCollShare = value.decodeUint(COLL_SHARE_OFFSET, 128);
          if (
            _convertToRawDebt(tickDebtShare, cachedDebtIndex, Math.Rounding.Down) * PRECISION >
            _convertToRawColl(tickCollShare, cachedCollIndex, Math.Rounding.Down) * price
          ) {
            hasDebt = false;
            tick = tick;
            continue;
          }
        }

        // redeem at most `maxRedeemRatioPerTick`
        uint256 debtShareToRedeem = (tickDebtShare * _getMaxRedeemRatioPerTick()) / FEE_PRECISION;
        if (debtShareToRedeem > debtShare) debtShareToRedeem = debtShare;
        uint256 rawCollRedeemed = (_convertToRawDebt(debtShareToRedeem, cachedDebtIndex, Math.Rounding.Down) *
          PRECISION) / price;
        uint256 collShareRedeemed = _convertToCollShares(rawCollRedeemed, cachedCollIndex, Math.Rounding.Down);
        _liquidateTick(tick, collShareRedeemed, debtShareToRedeem, price);
        debtShare -= debtShareToRedeem;
        rawColls += rawCollRedeemed;

        cachedTotalColls -= collShareRedeemed;
        cachedTotalDebts -= debtShareToRedeem;

        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
      }
      if (tick == type(int16).min) break;
    }
    _updateDebtAndCollateralShares(cachedTotalDebts, cachedTotalColls);
  }

  /// @inheritdoc IPool
  function rebalance(int16 tick, uint256 maxRawDebts) external onlyPoolManager returns (RebalanceResult memory result) {
    (uint256 cachedCollIndex, uint256 cachedDebtIndex) = _updateCollAndDebtIndex();
    (, uint256 price, ) = IPriceOracle(priceOracle).getPrice(); // use min price
    uint256 node = tickData[tick];
    bytes32 value = tickTreeData[node].value;
    uint256 tickRawColl = _convertToRawColl(
      value.decodeUint(COLL_SHARE_OFFSET, 128),
      cachedCollIndex,
      Math.Rounding.Down
    );
    uint256 tickRawDebt = _convertToRawDebt(
      value.decodeUint(DEBT_SHARE_OFFSET, 128),
      cachedDebtIndex,
      Math.Rounding.Down
    );
    (uint256 rebalanceDebtRatio, uint256 rebalanceBonusRatio) = _getRebalanceRatios();
    (uint256 liquidateDebtRatio, ) = _getLiquidateRatios();
    // rebalance only debt ratio >= `rebalanceDebtRatio` and ratio < `liquidateDebtRatio`
    if (tickRawDebt * PRECISION * PRECISION < rebalanceDebtRatio * tickRawColl * price) {
      revert ErrorRebalanceDebtRatioNotReached();
    }
    if (tickRawDebt * PRECISION * PRECISION >= liquidateDebtRatio * tickRawColl * price) {
      revert ErrorRebalanceOnLiquidatableTick();
    }

    // compute debts to rebalance to make debt ratio to `rebalanceDebtRatio`
    result.rawDebts = _getRawDebtToRebalance(tickRawColl, tickRawDebt, price, rebalanceDebtRatio, rebalanceBonusRatio);
    if (maxRawDebts < result.rawDebts) result.rawDebts = maxRawDebts;

    uint256 debtShareToRebalance = _convertToDebtShares(result.rawDebts, cachedDebtIndex, Math.Rounding.Down);
    result.rawColls = (result.rawDebts * PRECISION) / price;
    result.bonusRawColls = (result.rawColls * rebalanceBonusRatio) / FEE_PRECISION;
    if (result.bonusRawColls > tickRawColl - result.rawColls) {
      result.bonusRawColls = tickRawColl - result.rawColls;
    }
    uint256 collShareToRebalance = _convertToCollShares(
      result.rawColls + result.bonusRawColls,
      cachedCollIndex,
      Math.Rounding.Down
    );

    _liquidateTick(tick, collShareToRebalance, debtShareToRebalance, price);
    unchecked {
      (uint256 totalDebts, uint256 totalColls) = _getDebtAndCollateralShares();
      _updateDebtAndCollateralShares(totalDebts - debtShareToRebalance, totalColls - collShareToRebalance);
    }
  }

  struct RebalanceVars {
    uint256 tickCollShares;
    uint256 tickDebtShares;
    uint256 tickRawColls;
    uint256 tickRawDebts;
    uint256 maxRawDebts;
    uint256 rebalanceDebtRatio;
    uint256 rebalanceBonusRatio;
    uint256 price;
    uint256 collIndex;
    uint256 debtIndex;
    uint256 totalCollShares;
    uint256 totalDebtShares;
  }

  /// @inheritdoc IPool
  function rebalance(uint256 maxRawDebts) external onlyPoolManager returns (RebalanceResult memory result) {
    RebalanceVars memory vars;
    vars.maxRawDebts = maxRawDebts;
    (vars.rebalanceDebtRatio, vars.rebalanceBonusRatio) = _getRebalanceRatios();
    (, vars.price, ) = IPriceOracle(priceOracle).getPrice();
    (vars.collIndex, vars.debtIndex) = _updateCollAndDebtIndex();
    (vars.totalDebtShares, vars.totalCollShares) = _getDebtAndCollateralShares();
    (uint256 liquidateDebtRatio, ) = _getLiquidateRatios();

    int16 tick = _getTopTick();
    bool hasDebt = true;
    while (vars.maxRawDebts > 0) {
      if (!hasDebt) {
        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
      } else {
        (vars.tickCollShares, vars.tickDebtShares, vars.tickRawColls, vars.tickRawDebts) = _getTickRawCollAndDebts(
          tick,
          vars.collIndex,
          vars.debtIndex
        );
        // skip bad debt and liquidatable positions: coll * price * liquidateDebtRatio <= debts
        if (vars.tickRawColls * vars.price * liquidateDebtRatio <= vars.tickRawDebts * PRECISION * PRECISION) {
          hasDebt = false;
          tick = tick;
          continue;
        }
        // skip dust
        if (vars.tickRawDebts < uint256(MIN_DEBT)) {
          hasDebt = false;
          tick = tick;
          continue;
        }
        // no more rebalanceable tick: coll * price * rebalanceDebtRatio > debts
        if (vars.tickRawColls * vars.price * vars.rebalanceDebtRatio > vars.tickRawDebts * PRECISION * PRECISION) {
          break;
        }
        // rebalance this tick
        (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls) = _rebalanceTick(tick, vars);
        result.rawDebts += rawDebts;
        result.rawColls += rawColls;
        result.bonusRawColls += bonusRawColls;

        // goto next tick
        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
      }
      if (tick == type(int16).min) break;
    }

    _updateDebtAndCollateralShares(vars.totalDebtShares, vars.totalCollShares);
  }

  struct LiquidateVars {
    uint256 tickCollShares;
    uint256 tickDebtShares;
    uint256 tickRawColls;
    uint256 tickRawDebts;
    uint256 maxRawDebts;
    uint256 reservedRawColls;
    uint256 liquidateDebtRatio;
    uint256 liquidateBonusRatio;
    uint256 price;
    uint256 collIndex;
    uint256 debtIndex;
    uint256 totalCollShares;
    uint256 totalDebtShares;
  }

  /// @inheritdoc IPool
  function liquidate(
    uint256 maxRawDebts,
    uint256 reservedRawColls
  ) external onlyPoolManager returns (LiquidateResult memory result) {
    LiquidateVars memory vars;
    vars.maxRawDebts = maxRawDebts;
    vars.reservedRawColls = reservedRawColls;
    (vars.liquidateDebtRatio, vars.liquidateBonusRatio) = _getLiquidateRatios();
    (, vars.price, ) = IPriceOracle(priceOracle).getPrice();
    (vars.collIndex, vars.debtIndex) = _updateCollAndDebtIndex();
    (vars.totalDebtShares, vars.totalCollShares) = _getDebtAndCollateralShares();

    int16 tick = _getTopTick();
    bool hasDebt = true;
    while (vars.maxRawDebts > 0) {
      if (!hasDebt) {
        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
      } else {
        (vars.tickCollShares, vars.tickDebtShares, vars.tickRawColls, vars.tickRawDebts) = _getTickRawCollAndDebts(
          tick,
          vars.collIndex,
          vars.debtIndex
        );
        // no more liquidatable tick: coll * price * liquidateDebtRatio > debts
        if (vars.tickRawColls * vars.price * vars.liquidateDebtRatio > vars.tickRawDebts * PRECISION * PRECISION) {
          // skip dust, since the results might be wrong
          if (vars.tickRawDebts < uint256(MIN_DEBT)) {
            hasDebt = false;
            tick = tick;
            continue;
          }
          break;
        }
        // rebalance this tick
        (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls, uint256 bonusFromReserve) = _liquidateTick(
          tick,
          vars
        );
        result.rawDebts += rawDebts;
        result.rawColls += rawColls;
        result.bonusRawColls += bonusRawColls;
        result.bonusFromReserve += bonusFromReserve;

        // goto next tick
        (tick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(tick - 1);
      }
      if (tick == type(int16).min) break;
    }

    _updateDebtAndCollateralShares(vars.totalDebtShares, vars.totalCollShares);
    _updateDebtIndex(vars.debtIndex);
  }

  /************************
   * Restricted Functions *
   ************************/

  /// @notice Update the borrow and redeem status.
  /// @param borrowStatus The new borrow status.
  /// @param redeemStatus The new redeem status.
  function updateBorrowAndRedeemStatus(bool borrowStatus, bool redeemStatus) external onlyRole(EMERGENCY_ROLE) {
    _updateBorrowStatus(borrowStatus);
    _updateRedeemStatus(redeemStatus);
  }

  /// @notice Update debt ratio range.
  /// @param minRatio The minimum allowed debt ratio to update, multiplied by 1e18.
  /// @param maxRatio The maximum allowed debt ratio to update, multiplied by 1e18.
  function updateDebtRatioRange(uint256 minRatio, uint256 maxRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateDebtRatioRange(minRatio, maxRatio);
  }

  /// @notice Update maximum redeem ratio per tick.
  /// @param ratio The ratio to update, multiplied by 1e9.
  function updateMaxRedeemRatioPerTick(uint256 ratio) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateMaxRedeemRatioPerTick(ratio);
  }

  /// @notice Update ratio for rebalance.
  /// @param debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
  /// @param bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
  function updateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateRebalanceRatios(debtRatio, bonusRatio);
  }

  /// @notice Update ratio for liquidate.
  /// @param debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
  /// @param bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
  function updateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updateLiquidateRatios(debtRatio, bonusRatio);
  }

  /// @notice Update the address of price oracle.
  /// @param newOracle The address of new price oracle.
  function updatePriceOracle(address newOracle) external onlyRole(DEFAULT_ADMIN_ROLE) {
    _updatePriceOracle(newOracle);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to compute the amount of debt to rebalance to reach certain debt ratio.
  /// @param coll The amount of collateral tokens.
  /// @param debt The amount of debt tokens.
  /// @param price The price of the collateral token.
  /// @param targetDebtRatio The target debt ratio, multiplied by 1e18.
  /// @param incentiveRatio The bonus ratio, multiplied by 1e9.
  /// @return rawDebts The amount of debt tokens to rebalance.
  function _getRawDebtToRebalance(
    uint256 coll,
    uint256 debt,
    uint256 price,
    uint256 targetDebtRatio,
    uint256 incentiveRatio
  ) internal pure returns (uint256 rawDebts) {
    // we have
    //   1. (debt - x) / (price * (coll - y * (1 + incentive))) <= target_ratio
    //   2. debt / (price * coll) >= target_ratio
    // then
    // => debt - x <= target * price * (coll - y * (1 + incentive)) and y = x / price
    // => debt - target_ratio * price * coll <= (1 - (1 + incentive) * target) * x
    // => x >= (debt - target_ratio * price * coll) / (1 - (1 + incentive) * target)
    rawDebts =
      (debt * PRECISION * PRECISION - targetDebtRatio * price * coll) /
      (PRECISION * PRECISION - (PRECISION * targetDebtRatio * (FEE_PRECISION + incentiveRatio)) / FEE_PRECISION);
  }

  function _getTickRawCollAndDebts(
    int16 tick,
    uint256 collIndex,
    uint256 debtIndex
  ) internal view returns (uint256 colls, uint256 debts, uint256 rawColls, uint256 rawDebts) {
    uint256 node = tickData[tick];
    bytes32 value = tickTreeData[node].value;
    colls = value.decodeUint(COLL_SHARE_OFFSET, 128);
    debts = value.decodeUint(DEBT_SHARE_OFFSET, 128);
    rawColls = _convertToRawColl(colls, collIndex, Math.Rounding.Down);
    rawDebts = _convertToRawDebt(debts, debtIndex, Math.Rounding.Down);
  }

  function _rebalanceTick(
    int16 tick,
    RebalanceVars memory vars
  ) internal returns (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls) {
    // compute debts to rebalance to make debt ratio to `rebalanceDebtRatio`
    rawDebts = _getRawDebtToRebalance(
      vars.tickRawColls,
      vars.tickRawDebts,
      vars.price,
      vars.rebalanceDebtRatio,
      vars.rebalanceBonusRatio
    );
    if (vars.maxRawDebts < rawDebts) rawDebts = vars.maxRawDebts;

    uint256 debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);
    rawColls = (rawDebts * PRECISION) / vars.price;
    bonusRawColls = (rawColls * vars.rebalanceBonusRatio) / FEE_PRECISION;
    if (bonusRawColls > vars.tickRawColls - rawColls) {
      bonusRawColls = vars.tickRawColls - rawColls;
    }
    uint256 collShares = _convertToCollShares(rawColls + bonusRawColls, vars.collIndex, Math.Rounding.Down);

    _liquidateTick(tick, collShares, debtShares, vars.price);
    vars.totalCollShares -= collShares;
    vars.totalDebtShares -= debtShares;
    vars.maxRawDebts -= rawDebts;
  }

  function _liquidateTick(
    int16 tick,
    LiquidateVars memory vars
  ) internal returns (uint256 rawDebts, uint256 rawColls, uint256 bonusRawColls, uint256 bonusFromReserve) {
    uint256 virtualTickRawColls = vars.tickRawColls + vars.reservedRawColls;
    rawDebts = vars.tickRawDebts;
    if (rawDebts > vars.maxRawDebts) rawDebts = vars.maxRawDebts;
    rawColls = (rawDebts * PRECISION) / vars.price;
    uint256 debtShares;
    uint256 collShares;
    if (rawDebts == vars.tickRawDebts) {
      // full liquidation
      debtShares = vars.tickDebtShares;
    } else {
      // partial liquidation
      debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);
    }
    if (virtualTickRawColls <= rawColls) {
      // even reserve funds cannot cover bad debts, no bonus and will trigger bad debt redistribution
      rawColls = virtualTickRawColls;
      bonusFromReserve = vars.reservedRawColls;
      rawDebts = (virtualTickRawColls * vars.price) / PRECISION;
      debtShares = _convertToDebtShares(rawDebts, vars.debtIndex, Math.Rounding.Down);
      collShares = vars.tickCollShares;
    } else {
      // Bonus is from colls in tick, if it is not enough will use reserve funds
      bonusRawColls = (rawColls * vars.liquidateBonusRatio) / FEE_PRECISION;
      uint256 rawCollWithBonus = bonusRawColls + rawColls;
      if (rawCollWithBonus > virtualTickRawColls) {
        rawCollWithBonus = virtualTickRawColls;
        bonusRawColls = rawCollWithBonus - rawColls;
      }
      if (rawCollWithBonus >= vars.tickRawColls) {
        bonusFromReserve = rawCollWithBonus - vars.tickRawColls;
        collShares = vars.tickCollShares;
      } else {
        collShares = _convertToCollShares(rawCollWithBonus, vars.collIndex, Math.Rounding.Down);
      }
    }

    vars.reservedRawColls -= bonusFromReserve;
    if (collShares == vars.tickCollShares && debtShares < vars.tickDebtShares) {
      // trigger bad debt redistribution
      uint256 rawBadDebt = _convertToRawDebt(vars.tickDebtShares - debtShares, vars.debtIndex, Math.Rounding.Down);
      debtShares = vars.tickDebtShares;
      vars.totalCollShares -= collShares;
      vars.totalDebtShares -= debtShares;
      vars.debtIndex += (rawBadDebt * E96) / vars.totalDebtShares;
    } else {
      vars.totalCollShares -= collShares;
      vars.totalDebtShares -= debtShares;
    }
    vars.maxRawDebts -= rawDebts;
    _liquidateTick(tick, collShares, debtShares, vars.price);
  }

  /// @dev Internal function to update collateral and debt index.
  /// @return newCollIndex The updated collateral index.
  /// @return newDebtIndex The updated debt index.
  function _updateCollAndDebtIndex() internal virtual returns (uint256 newCollIndex, uint256 newDebtIndex);

  /// @dev Internal function to compute the protocol fees.
  /// @param rawColl The amount of collateral tokens involved.
  /// @return fees The expected protocol fees.
  function _deductProtocolFees(int256 rawColl) internal view virtual returns (uint256 fees);

  /**
   * @dev This empty reserved space is put in place to allow future versions to add new
   * variables without shifting down storage in the inheritance chain.
   */
  uint256[50] private __gap;
}

File 18 of 32 : PoolConstant.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { IPool } from "../../interfaces/IPool.sol";

abstract contract PoolConstant is IPool {
  /*************
   * Constants *
   *************/

  /// @dev The role for emergency operations.
  bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");

  /// @dev The value of minimum collateral.
  int256 internal constant MIN_COLLATERAL = 1e9;

  /// @dev The value of minimum debts.
  int256 internal constant MIN_DEBT = 1e9;

  /// @dev The precision used for various calculation.
  uint256 internal constant PRECISION = 1e18;

  /// @dev The precision used for fee ratio calculation.
  uint256 internal constant FEE_PRECISION = 1e9;

  /// @dev bit operation related constants
  uint256 internal constant E60 = 2 ** 60; // 2^60
  uint256 internal constant E96 = 2 ** 96; // 2^96

  uint256 internal constant X60 = 0xfffffffffffffff; // 2^60 - 1
  uint256 internal constant X96 = 0xffffffffffffffffffffffff; // 2^96 - 1

  /***********************
   * Immutable Variables *
   ***********************/

  /// @inheritdoc IPool
  address public immutable fxUSD;

  /// @inheritdoc IPool
  address public immutable poolManager;

  /// @inheritdoc IPool
  address public immutable pegKeeper;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

abstract contract PoolErrors {
  /**********
   * Errors *
   **********/
  
  /// @dev Thrown when the given address is zero.
  error ErrorZeroAddress();

  /// @dev Thrown when the given value exceeds maximum value.
  error ErrorValueTooLarge();
  
  /// @dev Thrown when the caller is not pool manager.
  error ErrorCallerNotPoolManager();
  
  /// @dev Thrown when the debt amount is too small.
  error ErrorDebtTooSmall();

  /// @dev Thrown when the collateral amount is too small.
  error ErrorCollateralTooSmall();
  
  /// @dev Thrown when both collateral amount and debt amount are zero.
  error ErrorNoSupplyAndNoBorrow();
  
  /// @dev Thrown when borrow is paused.
  error ErrorBorrowPaused();

  /// @dev Thrown when redeem is paused.
  error ErrorRedeemPaused();
  
  /// @dev Thrown when the caller is not position owner during withdraw or borrow.
  error ErrorNotPositionOwner();
  
  /// @dev Thrown when withdraw more than supplied.
  error ErrorWithdrawExceedSupply();
  
  /// @dev Thrown when the debt ratio is too small.
  error ErrorDebtRatioTooSmall();

  /// @dev Thrown when the debt ratio is too large.
  error ErrorDebtRatioTooLarge();
  
  /// @dev Thrown when pool is under collateral.
  error ErrorPoolUnderCollateral();
  
  /// @dev Thrown when the current debt ratio <= rebalance debt ratio.
  error ErrorRebalanceDebtRatioNotReached();

  /// @dev Thrown when the current debt ratio > liquidate debt ratio.
  error ErrorPositionInLiquidationMode();

  error ErrorRebalanceOnLiquidatableTick();

  error ErrorRebalanceOnLiquidatablePosition();

  error ErrorInsufficientCollateralToLiquidate();

  error ErrorOverflow();

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to check value not too large.
  /// @param value The value to check.
  /// @param upperBound The upper bound for the given value.
  function _checkValueTooLarge(uint256 value, uint256 upperBound) internal pure {
    if (value > upperBound) revert ErrorValueTooLarge();
  }

  function _checkAddressNotZero(address value) internal pure {
    if (value == address(0)) revert ErrorZeroAddress();
  }
}

File 20 of 32 : PoolStorage.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import { ERC721Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";

import { IPool } from "../../interfaces/IPool.sol";

import { WordCodec } from "../../common/codec/WordCodec.sol";
import { PoolConstant } from "./PoolConstant.sol";
import { PoolErrors } from "./PoolErrors.sol";

abstract contract PoolStorage is ERC721Upgradeable, AccessControlUpgradeable, PoolConstant, PoolErrors {
  using WordCodec for bytes32;

  /*************
   * Constants *
   *************/

  /// @dev Below are offsets of each variables in `miscData`.
  uint256 private constant BORROW_FLAG_OFFSET = 0;
  uint256 private constant REDEEM_FLAG_OFFSET = 1;
  uint256 private constant TOP_TICK_OFFSET = 2;
  uint256 private constant NEXT_POSITION_OFFSET = 18;
  uint256 private constant NEXT_NODE_OFFSET = 50;
  uint256 private constant MIN_DEBT_RATIO_OFFSET = 98;
  uint256 private constant MAX_DEBT_RATIO_OFFSET = 158;
  uint256 private constant MAX_REDEEM_RATIO_OFFSET = 218;

  /// @dev Below are offsets of each variables in `rebalanceRatioData`.
  uint256 private constant REBALANCE_DEBT_RATIO_OFFSET = 0;
  uint256 private constant REBALANCE_BONUS_RATIO_OFFSET = 60;
  uint256 private constant LIQUIDATE_DEBT_RATIO_OFFSET = 90;
  uint256 private constant LIQUIDATE_BONUS_RATIO_OFFSET = 150;

  /// @dev Below are offsets of each variables in `indexData`.
  uint256 private constant DEBT_INDEX_OFFSET = 0;
  uint256 private constant COLLATERAL_INDEX_OFFSET = 128;

  /// @dev Below are offsets of each variables in `sharesData`.
  uint256 private constant DEBT_SHARES_OFFSET = 0;
  uint256 private constant COLLATERAL_SHARES_OFFSET = 128;

  /***********
   * Structs *
   ***********/

  /// @dev if nodeId = 0, tick is not used and this position only has collateral
  ///
  /// @param tick The tick this position belongs to at the beginning.
  /// @param nodeId The tree node id this position belongs to at the beginning.
  /// @param colls The collateral shares this position has.
  /// @param debts The debt shares this position has.
  struct PositionInfo {
    int16 tick;
    uint48 nodeId;
    // `uint96` is enough, since we use `86` bits in `PoolManager`.
    uint96 colls;
    // `uint96` is enough, since we use `96` bits in `PoolManager`.
    uint96 debts;
  }

  /// @dev The compiler will pack it into two `uint256`.
  /// @param metadata The metadata for tree node.
  ///   ```text
  ///   * Field           Bits    Index       Comments
  ///   * parent          48      0           The index for parent tree node.
  ///   * tick            16      48          The original tick for this tree node.
  ///   * coll ratio      64      64          The remained coll share ratio base on parent node, the value is real ratio * 2^60.
  ///   * debt ratio      64      128         The remained debt share ratio base on parent node, the value is real ratio * 2^60.
  ///   ```
  /// @param value The value for tree node
  ///   ```text
  ///   * Field           Bits    Index       Comments
  ///   * coll share      128     0           The original total coll share before rebalance or redeem.
  ///   * debt share      128     128         The original total debt share before rebalance or redeem.
  ///   ```
  struct TickTreeNode {
    bytes32 metadata;
    bytes32 value;
  }

  /*********************
   * Storage Variables *
   *********************/

  /// @inheritdoc IPool
  address public collateralToken;

  /// @inheritdoc IPool
  address public priceOracle;

  /// @dev `miscData` is a storage slot that can be used to store unrelated pieces of information.
  ///
  /// - The *borrow flag* indicates whether borrow fxUSD is allowed, 1 means paused.
  /// - The *redeem flag* indicates whether redeem fxUSD is allowed, 1 means paused.
  /// - The *top tick* is the largest tick with debts.
  /// - The *next position* is the next unassigned position id.
  /// - The *next node* is the next unassigned tree node id.
  /// - The *min debt ratio* is the minimum allowed debt ratio, multiplied by 1e18.
  /// - The *max debt ratio* is the maximum allowed debt ratio, multiplied by 1e18.
  /// - The *max redeem ratio* is the maximum allowed redeem ratio per tick, multiplied by 1e9.
  ///
  /// [ borrow flag | redeem flag | top tick | next position | next node | min debt ratio | max debt ratio | max redeem ratio | reserved ]
  /// [    1 bit    |    1 bit    | 16  bits |    32 bits    |  48 bits  |    60  bits    |    60  bits    |      30 bits     |  8 bits  ]
  /// [ MSB                                                                                                                          LSB ]
  bytes32 private miscData;

  /// @dev `rebalanceRatioData` is a storage slot used to store rebalance and liquidate information.
  ///
  /// - The *rebalance debt ratio* is the min debt ratio to start rebalance, multiplied by 1e18.
  /// - The *rebalance bonus ratio* is the bonus ratio during rebalance, multiplied by 1e9.
  /// - The *liquidate debt ratio* is the min debt ratio to start liquidate, multiplied by 1e18.
  /// - The *liquidate bonus ratio* is the bonus ratio during liquidate, multiplied by 1e9.
  ///
  /// [ rebalance debt ratio | rebalance bonus ratio | liquidate debt ratio | liquidate bonus ratio | reserved ]
  /// [       60  bits       |        30 bits        |       60  bits       |        30 bits        | 76  bits ]
  /// [ MSB                                                                                                LSB ]
  bytes32 private rebalanceRatioData;

  /// @dev `indexData` is a storage slot used to store debt/collateral index.
  ///
  /// - The *debt index* is the index for each debt shares, only increasing, starting from 2^96, max 2^128-1.
  /// - The *collateral index* is the index for each collateral shares, only increasing, starting from 2^96, max 2^128-1
  ///
  /// [ debt index | collateral index ]
  /// [  128 bits  |     128 bits     ]
  /// [ MSB                       LSB ]
  bytes32 private indexData;

  /// @dev `sharesData` is a storage slot used to store debt/collateral shares.
  ///
  /// - The *debt shares* is the total debt shares. The actual number of total debts
  ///   is `<debt shares> * <debt index>`.
  /// - The *collateral shares* is the total collateral shares. The actual number of
  ///   total collateral is `<collateral shares> / <collateral index>`.
  ///
  /// [ debt shares | collateral shares ]
  /// [  128  bits  |     128  bits     ]
  /// [ MSB                         LSB ]
  bytes32 private sharesData;

  /// @dev Mapping from position id to position information.
  mapping(uint256 => PositionInfo) public positionData;

  /// @dev Mapping from position id to position metadata.
  /// [ open timestamp | reserved ]
  /// [    40  bits    | 216 bits ]
  /// [ MSB                   LSB ]
  mapping(uint256 => bytes32) public positionMetadata;

  /// @dev The bitmap for ticks with debts.
  mapping(int8 => uint256) public tickBitmap;

  /// @dev Mapping from tick to tree node id.
  mapping(int256 => uint48) public tickData;

  /// @dev Mapping from tree node id to tree node data.
  mapping(uint256 => TickTreeNode) public tickTreeData;

  /***************
   * Constructor *
   ***************/

  function __PoolStorage_init(address _collateralToken, address _priceOracle) internal onlyInitializing {
    _checkAddressNotZero(_collateralToken);

    collateralToken = _collateralToken;
    _updatePriceOracle(_priceOracle);
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc AccessControlUpgradeable
  function supportsInterface(
    bytes4 interfaceId
  ) public view virtual override(AccessControlUpgradeable, ERC721Upgradeable) returns (bool) {
    return super.supportsInterface(interfaceId);
  }

  /// @inheritdoc IPool
  function isBorrowPaused() external view returns (bool) {
    return _isBorrowPaused();
  }

  /// @inheritdoc IPool
  function isRedeemPaused() external view returns (bool) {
    return _isRedeemPaused();
  }

  /// @inheritdoc IPool
  function getTopTick() external view returns (int16) {
    return _getTopTick();
  }

  /// @inheritdoc IPool
  function getNextPositionId() external view returns (uint32) {
    return _getNextPositionId();
  }

  /// @inheritdoc IPool
  function getNextTreeNodeId() external view returns (uint48) {
    return _getNextTreeNodeId();
  }

  /// @inheritdoc IPool
  function getDebtRatioRange() external view returns (uint256, uint256) {
    return _getDebtRatioRange();
  }

  /// @inheritdoc IPool
  function getMaxRedeemRatioPerTick() external view returns (uint256) {
    return _getMaxRedeemRatioPerTick();
  }

  /// @inheritdoc IPool
  function getRebalanceRatios() external view returns (uint256, uint256) {
    return _getRebalanceRatios();
  }

  /// @inheritdoc IPool
  function getLiquidateRatios() external view returns (uint256, uint256) {
    return _getLiquidateRatios();
  }

  /// @inheritdoc IPool
  function getDebtAndCollateralIndex() external view returns (uint256, uint256) {
    return _getDebtAndCollateralIndex();
  }

  /// @inheritdoc IPool
  function getDebtAndCollateralShares() external view returns (uint256, uint256) {
    return _getDebtAndCollateralShares();
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to update price oracle.
  /// @param newOracle The address of new price oracle;
  function _updatePriceOracle(address newOracle) internal {
    _checkAddressNotZero(newOracle);

    address oldOracle = priceOracle;
    priceOracle = newOracle;

    emit UpdatePriceOracle(oldOracle, newOracle);
  }

  /*************************************
   * Internal Functions For `miscData` *
   *************************************/

  /// @dev Internal function to get the borrow pause status.
  function _isBorrowPaused() internal view returns (bool) {
    return miscData.decodeBool(BORROW_FLAG_OFFSET);
  }

  /// @dev Internal function to update borrow pause status.
  /// @param status The status to update.
  function _updateBorrowStatus(bool status) internal {
    miscData = miscData.insertBool(status, BORROW_FLAG_OFFSET);

    emit UpdateBorrowStatus(status);
  }

  /// @dev Internal function to get the redeem pause status.
  function _isRedeemPaused() internal view returns (bool) {
    return miscData.decodeBool(REDEEM_FLAG_OFFSET);
  }

  /// @dev Internal function to update redeem pause status.
  /// @param status The status to update.
  function _updateRedeemStatus(bool status) internal {
    miscData = miscData.insertBool(status, REDEEM_FLAG_OFFSET);

    emit UpdateRedeemStatus(status);
  }

  /// @dev Internal function to get the value of top tick.
  function _getTopTick() internal view returns (int16) {
    return int16(miscData.decodeInt(TOP_TICK_OFFSET, 16));
  }

  /// @dev Internal function to update the top tick.
  /// @param tick The new top tick.
  function _updateTopTick(int16 tick) internal {
    miscData = miscData.insertInt(tick, TOP_TICK_OFFSET, 16);
  }

  /// @dev Internal function to get next available position id.
  function _getNextPositionId() internal view returns (uint32) {
    return uint32(miscData.decodeUint(NEXT_POSITION_OFFSET, 32));
  }

  /// @dev Internal function to update next available position id.
  /// @param id The position id to update.
  function _updateNextPositionId(uint32 id) internal {
    miscData = miscData.insertUint(id, NEXT_POSITION_OFFSET, 32);
  }

  /// @dev Internal function to get next available tree node id.
  function _getNextTreeNodeId() internal view returns (uint48) {
    return uint48(miscData.decodeUint(NEXT_NODE_OFFSET, 48));
  }

  /// @dev Internal function to update next available tree node id.
  /// @param id The tree node id to update.
  function _updateNextTreeNodeId(uint48 id) internal {
    miscData = miscData.insertUint(id, NEXT_NODE_OFFSET, 48);
  }

  /// @dev Internal function to get `minDebtRatio` and `maxDebtRatio`, both multiplied by 1e18.
  function _getDebtRatioRange() internal view returns (uint256 minDebtRatio, uint256 maxDebtRatio) {
    bytes32 data = miscData;
    minDebtRatio = data.decodeUint(MIN_DEBT_RATIO_OFFSET, 60);
    maxDebtRatio = data.decodeUint(MAX_DEBT_RATIO_OFFSET, 60);
  }

  /// @dev Internal function to update debt ratio range.
  /// @param minDebtRatio The minimum allowed debt ratio to update, multiplied by 1e18.
  /// @param maxDebtRatio The maximum allowed debt ratio to update, multiplied by 1e18.
  function _updateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio) internal {
    _checkValueTooLarge(minDebtRatio, maxDebtRatio);
    _checkValueTooLarge(maxDebtRatio, PRECISION);

    bytes32 data = miscData;
    data = data.insertUint(minDebtRatio, MIN_DEBT_RATIO_OFFSET, 60);
    miscData = data.insertUint(maxDebtRatio, MAX_DEBT_RATIO_OFFSET, 60);

    emit UpdateDebtRatioRange(minDebtRatio, maxDebtRatio);
  }

  /// @dev Internal function to get the `maxRedeemRatioPerTick`.
  function _getMaxRedeemRatioPerTick() internal view returns (uint256) {
    return miscData.decodeUint(MAX_REDEEM_RATIO_OFFSET, 30);
  }

  /// @dev Internal function to update maximum redeem ratio per tick.
  /// @param ratio The ratio to update, multiplied by 1e9.
  function _updateMaxRedeemRatioPerTick(uint256 ratio) internal {
    _checkValueTooLarge(ratio, FEE_PRECISION);

    miscData = miscData.insertUint(ratio, MAX_REDEEM_RATIO_OFFSET, 30);

    emit UpdateMaxRedeemRatioPerTick(ratio);
  }

  /***********************************************
   * Internal Functions For `rebalanceRatioData` *
   ***********************************************/

  /// @dev Internal function to get `debtRatio` and `bonusRatio` for rebalance.
  /// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
  /// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
  function _getRebalanceRatios() internal view returns (uint256 debtRatio, uint256 bonusRatio) {
    bytes32 data = rebalanceRatioData;
    debtRatio = data.decodeUint(REBALANCE_DEBT_RATIO_OFFSET, 60);
    bonusRatio = data.decodeUint(REBALANCE_BONUS_RATIO_OFFSET, 30);
  }

  /// @dev Internal function to update ratio for rebalance.
  /// @param debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
  /// @param bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
  function _updateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio) internal {
    _checkValueTooLarge(debtRatio, PRECISION);
    _checkValueTooLarge(bonusRatio, FEE_PRECISION);

    bytes32 data = rebalanceRatioData;
    data = data.insertUint(debtRatio, REBALANCE_DEBT_RATIO_OFFSET, 60);
    rebalanceRatioData = data.insertUint(bonusRatio, REBALANCE_BONUS_RATIO_OFFSET, 30);

    emit UpdateRebalanceRatios(debtRatio, bonusRatio);
  }

  /// @dev Internal function to get `debtRatio` and `bonusRatio` for liquidate.
  /// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
  /// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
  function _getLiquidateRatios() internal view returns (uint256 debtRatio, uint256 bonusRatio) {
    bytes32 data = rebalanceRatioData;
    debtRatio = data.decodeUint(LIQUIDATE_DEBT_RATIO_OFFSET, 60);
    bonusRatio = data.decodeUint(LIQUIDATE_BONUS_RATIO_OFFSET, 30);
  }

  /// @dev Internal function to update ratio for liquidate.
  /// @param debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
  /// @param bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
  function _updateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio) internal {
    _checkValueTooLarge(debtRatio, PRECISION);
    _checkValueTooLarge(bonusRatio, FEE_PRECISION);

    bytes32 data = rebalanceRatioData;
    data = data.insertUint(debtRatio, LIQUIDATE_DEBT_RATIO_OFFSET, 60);
    rebalanceRatioData = data.insertUint(bonusRatio, LIQUIDATE_BONUS_RATIO_OFFSET, 30);

    emit UpdateLiquidateRatios(debtRatio, bonusRatio);
  }

  /**************************************
   * Internal Functions For `indexData` *
   **************************************/

  /// @dev Internal function to get debt and collateral index.
  /// @return debtIndex The index for debt shares.
  /// @return collIndex The index for collateral shares.
  function _getDebtAndCollateralIndex() internal view returns (uint256 debtIndex, uint256 collIndex) {
    bytes32 data = indexData;
    debtIndex = data.decodeUint(DEBT_INDEX_OFFSET, 128);
    collIndex = data.decodeUint(COLLATERAL_INDEX_OFFSET, 128);
  }

  /// @dev Internal function to update debt index.
  /// @param index The debt index to update.
  function _updateDebtIndex(uint256 index) internal {
    indexData = indexData.insertUint(index, DEBT_INDEX_OFFSET, 128);

    emit DebtIndexSnapshot(index);
  }

  /// @dev Internal function to update collateral index.
  /// @param index The collateral index to update.
  function _updateCollateralIndex(uint256 index) internal {
    indexData = indexData.insertUint(index, COLLATERAL_INDEX_OFFSET, 128);

    emit CollateralIndexSnapshot(index);
  }

  /**************************************
   * Internal Functions For `sharesData` *
   **************************************/

  /// @dev Internal function to get debt and collateral shares.
  /// @return debtShares The total number of debt shares.
  /// @return collShares The total number of collateral shares.
  function _getDebtAndCollateralShares() internal view returns (uint256 debtShares, uint256 collShares) {
    bytes32 data = sharesData;
    debtShares = data.decodeUint(DEBT_SHARES_OFFSET, 128);
    collShares = data.decodeUint(COLLATERAL_SHARES_OFFSET, 128);
  }

  /// @dev Internal function to update debt and collateral shares.
  /// @param debtShares The debt shares to update.
  /// @param collShares The collateral shares to update.
  function _updateDebtAndCollateralShares(uint256 debtShares, uint256 collShares) internal {
    bytes32 data = sharesData;
    data = data.insertUint(debtShares, DEBT_SHARES_OFFSET, 128);
    sharesData = data.insertUint(collShares, COLLATERAL_SHARES_OFFSET, 128);
  }

  /// @dev Internal function to update debt shares.
  /// @param shares The debt shares to update.
  function _updateDebtShares(uint256 shares) internal {
    sharesData = sharesData.insertUint(shares, DEBT_SHARES_OFFSET, 128);
  }

  /// @dev Internal function to update collateral shares.
  /// @param shares The collateral shares to update.
  function _updateCollateralShares(uint256 shares) internal {
    sharesData = sharesData.insertUint(shares, COLLATERAL_SHARES_OFFSET, 128);
  }

  /**
   * @dev This empty reserved space is put in place to allow future versions to add new
   * variables without shifting down storage in the inheritance chain.
   */
  uint256[40] private __gap;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { IPool } from "../../interfaces/IPool.sol";
import { IPriceOracle } from "../../price-oracle/interfaces/IPriceOracle.sol";

import { WordCodec } from "../../common/codec/WordCodec.sol";
import { Math } from "../../libraries/Math.sol";
import { TickLogic } from "./TickLogic.sol";

abstract contract PositionLogic is TickLogic {
  using WordCodec for bytes32;

  /***************
   * Constructor *
   ***************/

  function __PositionLogic_init() internal onlyInitializing {
    _updateNextPositionId(1);
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc IPool
  function getPosition(uint256 tokenId) public view returns (uint256 rawColls, uint256 rawDebts) {
    // compute actual shares
    PositionInfo memory position = positionData[tokenId];
    rawColls = position.colls;
    rawDebts = position.debts;
    if (position.nodeId > 0) {
      (, uint256 collRatio, uint256 debtRatio) = _getRootNode(position.nodeId);
      rawColls = (rawColls * collRatio) >> 60;
      rawDebts = (rawDebts * debtRatio) >> 60;
    }

    // convert shares to actual amount
    (uint256 debtIndex, uint256 collIndex) = _getDebtAndCollateralIndex();
    rawColls = _convertToRawColl(rawColls, collIndex, Math.Rounding.Down);
    rawDebts = _convertToRawDebt(rawDebts, debtIndex, Math.Rounding.Down);
  }

  /// @inheritdoc IPool
  function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio) {
    (uint256 rawColls, uint256 rawDebts) = getPosition(tokenId);
    // price precision and ratio precision are both 1e18, use anchor price here
    (uint256 price, , ) = IPriceOracle(priceOracle).getPrice();
    if (rawColls == 0) return 0;
    return (rawDebts * PRECISION * PRECISION) / (price * rawColls);
  }

  /// @inheritdoc IPool
  function getTotalRawCollaterals() external view returns (uint256) {
    (, uint256 totalColls) = _getDebtAndCollateralShares();
    (, uint256 collIndex) = _getDebtAndCollateralIndex();
    return _convertToRawColl(totalColls, collIndex, Math.Rounding.Down);
  }

  /// @inheritdoc IPool
  function getTotalRawDebts() external view returns (uint256) {
    (uint256 totalDebts, ) = _getDebtAndCollateralShares();
    (uint256 debtIndex, ) = _getDebtAndCollateralIndex();
    return _convertToRawDebt(totalDebts, debtIndex, Math.Rounding.Down);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to mint a new position.
  /// @param owner The address of position owner.
  /// @return positionId The id of the position.
  function _mintPosition(address owner) internal returns (uint32 positionId) {
    unchecked {
      positionId = _getNextPositionId();
      _updateNextPositionId(positionId + 1);
    }

    positionMetadata[positionId] = bytes32(0).insertUint(block.timestamp, 0, 40);
    _mint(owner, positionId);
  }

  /// @dev Internal function to get and update position.
  /// @param tokenId The id of the position.
  /// @return position The position struct.
  function _getAndUpdatePosition(uint256 tokenId) internal returns (PositionInfo memory position) {
    position = positionData[tokenId];
    if (position.nodeId > 0) {
      (uint256 root, uint256 collRatio, uint256 debtRatio) = _getRootNodeAndCompress(position.nodeId);
      position.colls = uint96((position.colls * collRatio) >> 60);
      position.debts = uint96((position.debts * debtRatio) >> 60);
      position.nodeId = uint32(root);
      positionData[tokenId] = position;
    }
  }

  /// @dev Internal function to convert raw collateral amounts to collateral shares.
  function _convertToCollShares(
    uint256 raw,
    uint256 index,
    Math.Rounding rounding
  ) internal pure returns (uint256 shares) {
    shares = Math.mulDiv(raw, index, E96, rounding);
  }

  /// @dev Internal function to convert raw debt amounts to debt shares.
  function _convertToDebtShares(
    uint256 raw,
    uint256 index,
    Math.Rounding rounding
  ) internal pure returns (uint256 shares) {
    shares = Math.mulDiv(raw, E96, index, rounding);
  }

  /// @dev Internal function to convert raw collateral shares to collateral amounts.
  function _convertToRawColl(
    uint256 shares,
    uint256 index,
    Math.Rounding rounding
  ) internal pure returns (uint256 raw) {
    raw = Math.mulDiv(shares, E96, index, rounding);
  }

  /// @dev Internal function to convert raw debt shares to debt amounts.
  function _convertToRawDebt(
    uint256 shares,
    uint256 index,
    Math.Rounding rounding
  ) internal pure returns (uint256 raw) {
    raw = Math.mulDiv(shares, index, E96, rounding);
  }

  /**
   * @dev This empty reserved space is put in place to allow future versions to add new
   * variables without shifting down storage in the inheritance chain.
   */
  uint256[50] private __gap;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

import { WordCodec } from "../../common/codec/WordCodec.sol";
import { TickBitmap } from "../../libraries/TickBitmap.sol";
import { TickMath } from "../../libraries/TickMath.sol";
import { PoolStorage } from "./PoolStorage.sol";

abstract contract TickLogic is PoolStorage {
  using TickBitmap for mapping(int8 => uint256);
  using WordCodec for bytes32;

  /*************
   * Constants *
   *************/

  /// @dev Below are offsets of each variables in `TickTreeNode.metadata`.
  uint256 private constant PARENT_OFFSET = 0;
  uint256 private constant TICK_OFFSET = 48;
  uint256 private constant COLL_RATIO_OFFSET = 64;
  uint256 private constant DEBT_RATIO_OFFSET = 128;

  /// @dev Below are offsets of each variables in `TickTreeNode.value`.
  uint256 internal constant COLL_SHARE_OFFSET = 0;
  uint256 internal constant DEBT_SHARE_OFFSET = 128;

  /***************
   * Constructor *
   ***************/

  function __TickLogic_init() internal onlyInitializing {
    _updateNextTreeNodeId(1);
    _updateTopTick(type(int16).min);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to get the root of the given tree node.
  /// @param node The id of the given tree node.
  /// @return root The root node id.
  /// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.
  /// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.
  function _getRootNode(uint256 node) internal view returns (uint256 root, uint256 collRatio, uint256 debtRatio) {
    collRatio = E60;
    debtRatio = E60;
    while (true) {
      bytes32 metadata = tickTreeData[node].metadata;
      uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);
      collRatio = (collRatio * metadata.decodeUint(COLL_RATIO_OFFSET, 64)) >> 60;
      debtRatio = (debtRatio * metadata.decodeUint(DEBT_RATIO_OFFSET, 64)) >> 60;
      if (parent == 0) break;
      node = parent;
    }
    root = node;
  }

  /// @dev Internal function to get the root of the given tree node and compress path.
  /// @param node The id of the given tree node.
  /// @return root The root node id.
  /// @return collRatio The actual collateral ratio of the given node, multiplied by 2^60.
  /// @return debtRatio The actual debt ratio of the given node, multiplied by 2^60.
  function _getRootNodeAndCompress(uint256 node) internal returns (uint256 root, uint256 collRatio, uint256 debtRatio) {
    // @note We can change it to non-recursive version to avoid stack overflow. Normally, the depth should be `log(n)`,
    // where `n` is the total number of tree nodes. So we don't need to worry much about this.
    bytes32 metadata = tickTreeData[node].metadata;
    uint256 parent = metadata.decodeUint(PARENT_OFFSET, 48);
    collRatio = metadata.decodeUint(COLL_RATIO_OFFSET, 64);
    debtRatio = metadata.decodeUint(DEBT_RATIO_OFFSET, 64);
    if (parent == 0) {
      root = node;
    } else {
      uint256 collRatioCompressed;
      uint256 debtRatioCompressed;
      (root, collRatioCompressed, debtRatioCompressed) = _getRootNodeAndCompress(parent);
      collRatio = (collRatio * collRatioCompressed) >> 60;
      debtRatio = (debtRatio * debtRatioCompressed) >> 60;
      metadata = metadata.insertUint(root, PARENT_OFFSET, 48);
      metadata = metadata.insertUint(collRatio, COLL_RATIO_OFFSET, 64);
      metadata = metadata.insertUint(debtRatio, DEBT_RATIO_OFFSET, 64);
      tickTreeData[node].metadata = metadata;
    }
  }

  /// @dev Internal function to create a new tree node.
  /// @param tick The tick where this tree node belongs to.
  /// @return node The created tree node id.
  function _newTickTreeNode(int16 tick) internal returns (uint48 node) {
    unchecked {
      node = _getNextTreeNodeId();
      _updateNextTreeNodeId(node + 1);
    }
    tickData[tick] = node;

    bytes32 metadata = bytes32(0);
    metadata = metadata.insertInt(tick, TICK_OFFSET, 16); // set tick
    metadata = metadata.insertUint(E60, COLL_RATIO_OFFSET, 64); // set coll ratio
    metadata = metadata.insertUint(E60, DEBT_RATIO_OFFSET, 64); // set debt ratio
    tickTreeData[node].metadata = metadata;
  }

  /// @dev Internal function to find first tick such that `TickMath.getRatioAtTick(tick) >= debts/colls`.
  /// @param colls The collateral shares.
  /// @param debts The debt shares.
  /// @return tick The value of found first tick.
  function _getTick(uint256 colls, uint256 debts) internal pure returns (int256 tick) {
    uint256 ratio = (debts * TickMath.ZERO_TICK_SCALED_RATIO) / colls;
    uint256 ratioAtTick;
    (tick, ratioAtTick) = TickMath.getTickAtRatio(ratio);
    if (ratio != ratioAtTick) {
      tick++;
      ratio = (ratioAtTick * 10015) / 10000;
    }
  }

  /// @dev Internal function to retrieve or create a tree node.
  /// @param tick The tick where this tree node belongs to.
  /// @return node The tree node id.
  function _getOrCreateTickNode(int256 tick) internal returns (uint48 node) {
    node = tickData[tick];
    if (node == 0) {
      node = _newTickTreeNode(int16(tick));
    }
  }

  /// @dev Internal function to add position collaterals and debts to some tick.
  /// @param colls The collateral shares.
  /// @param debts The debt shares.
  /// @param checkDebts Whether we should check the value of `debts`.
  /// @return tick The tick where this position belongs to.
  /// @return node The corresponding tree node id for this tick.
  function _addPositionToTick(
    uint256 colls,
    uint256 debts,
    bool checkDebts
  ) internal returns (int256 tick, uint48 node) {
    if (debts > 0) {
      if (checkDebts && int256(debts) < MIN_DEBT) {
        revert ErrorDebtTooSmall();
      }

      tick = _getTick(colls, debts);
      node = _getOrCreateTickNode(tick);
      bytes32 value = tickTreeData[node].value;
      uint256 newColls = value.decodeUint(COLL_SHARE_OFFSET, 128) + colls;
      uint256 newDebts = value.decodeUint(DEBT_SHARE_OFFSET, 128) + debts;
      value = value.insertUint(newColls, COLL_SHARE_OFFSET, 128);
      value = value.insertUint(newDebts, DEBT_SHARE_OFFSET, 128);
      tickTreeData[node].value = value;

      if (newDebts == debts) {
        tickBitmap.flipTick(int16(tick));
      }

      // update top tick
      if (tick > _getTopTick()) {
        _updateTopTick(int16(tick));
      }
    }
  }

  /// @dev Internal function to remove position from tick.
  /// @param position The position struct to remove.
  function _removePositionFromTick(PositionInfo memory position) internal {
    if (position.nodeId == 0) return;

    bytes32 value = tickTreeData[position.nodeId].value;
    uint256 oldDebts = value.decodeUint(DEBT_SHARE_OFFSET, 128);
    uint256 newColls = value.decodeUint(COLL_SHARE_OFFSET, 128) - position.colls;
    uint256 newDebts = oldDebts - position.debts;
    value = value.insertUint(newColls, COLL_SHARE_OFFSET, 128);
    value = value.insertUint(newDebts, DEBT_SHARE_OFFSET, 128);
    tickTreeData[position.nodeId].value = value;

    if (newDebts == 0 && oldDebts > 0) {
      int16 tick = int16(tickTreeData[position.nodeId].metadata.decodeInt(TICK_OFFSET, 16));
      tickBitmap.flipTick(tick);

      // top tick gone, update it to new one
      int16 topTick = _getTopTick();
      if (topTick == tick) {
        _resetTopTick(topTick);
      }
    }
  }

  /// @dev Internal function to liquidate a tick.
  ///      The caller make sure `max(liquidatedColl, liquidatedDebt) > 0`.
  ///
  /// @param tick The id of tick to liquidate.
  /// @param liquidatedColl The amount of collateral shares liquidated.
  /// @param liquidatedDebt The amount of debt shares liquidated.
  function _liquidateTick(int16 tick, uint256 liquidatedColl, uint256 liquidatedDebt, uint256 price) internal {
    uint48 node = tickData[tick];
    // create new tree node for this tick
    _newTickTreeNode(tick);
    // clear bitmap first, and it will be updated later if needed.
    tickBitmap.flipTick(tick);

    bytes32 value = tickTreeData[node].value;
    bytes32 metadata = tickTreeData[node].metadata;
    uint256 tickColl = value.decodeUint(COLL_SHARE_OFFSET, 128);
    uint256 tickDebt = value.decodeUint(DEBT_SHARE_OFFSET, 128);
    uint256 tickCollAfter = tickColl - liquidatedColl;
    uint256 tickDebtAfter = tickDebt - liquidatedDebt;
    uint256 collRatio = (tickCollAfter * E60) / tickColl;
    uint256 debtRatio = (tickDebtAfter * E60) / tickDebt;

    // update metadata
    metadata = metadata.insertUint(collRatio, COLL_RATIO_OFFSET, 64);
    metadata = metadata.insertUint(debtRatio, DEBT_RATIO_OFFSET, 64);

    int256 newTick = type(int256).min;
    if (tickDebtAfter > 0) {
      // partial liquidated, move funds to another tick
      uint48 parentNode;
      (newTick, parentNode) = _addPositionToTick(tickCollAfter, tickDebtAfter, false);
      metadata = metadata.insertUint(parentNode, PARENT_OFFSET, 48);
    }
    if (newTick == type(int256).min) {
      emit TickMovement(tick, type(int16).min, tickCollAfter, tickDebtAfter, price);
    } else {
      emit TickMovement(tick, int16(newTick), tickCollAfter, tickDebtAfter, price);
    }

    // top tick liquidated, update it to new one
    int16 topTick = _getTopTick();
    if (topTick == tick && newTick != int256(tick)) {
      _resetTopTick(topTick);
    }
    tickTreeData[node].metadata = metadata;
  }

  /// @dev Internal function to reset top tick.
  /// @param oldTopTick The previous value of top tick.
  function _resetTopTick(int16 oldTopTick) internal {
    while (oldTopTick > type(int16).min) {
      bool hasDebt;
      (oldTopTick, hasDebt) = tickBitmap.nextDebtPositionWithinOneWord(oldTopTick - 1);
      if (hasDebt) break;
    }
    _updateTopTick(oldTopTick);
  }

  /**
   * @dev This empty reserved space is put in place to allow future versions to add new
   * variables without shifting down storage in the inheritance chain.
   */
  uint256[50] private __gap;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IAaveV3Pool {
  struct ReserveConfigurationMap {
    //bit 0-15: LTV
    //bit 16-31: Liq. threshold
    //bit 32-47: Liq. bonus
    //bit 48-55: Decimals
    //bit 56: reserve is active
    //bit 57: reserve is frozen
    //bit 58: borrowing is enabled
    //bit 59: DEPRECATED: stable rate borrowing enabled
    //bit 60: asset is paused
    //bit 61: borrowing in isolation mode is enabled
    //bit 62: siloed borrowing enabled
    //bit 63: flashloaning enabled
    //bit 64-79: reserve factor
    //bit 80-115: borrow cap in whole tokens, borrowCap == 0 => no cap
    //bit 116-151: supply cap in whole tokens, supplyCap == 0 => no cap
    //bit 152-167: liquidation protocol fee
    //bit 168-175: DEPRECATED: eMode category
    //bit 176-211: unbacked mint cap in whole tokens, unbackedMintCap == 0 => minting disabled
    //bit 212-251: debt ceiling for isolation mode with (ReserveConfiguration::DEBT_CEILING_DECIMALS) decimals
    //bit 252: virtual accounting is enabled for the reserve
    //bit 253-255 unused

    uint256 data;
  }

  /**
   * This exists specifically to maintain the `getReserveData()` interface, since the new, internal
   * `ReserveData` struct includes the reserve's `virtualUnderlyingBalance`.
   */
  struct ReserveDataLegacy {
    //stores the reserve configuration
    ReserveConfigurationMap configuration;
    //the liquidity index. Expressed in ray
    uint128 liquidityIndex;
    //the current supply rate. Expressed in ray
    uint128 currentLiquidityRate;
    //variable borrow index. Expressed in ray
    uint128 variableBorrowIndex;
    //the current variable borrow rate. Expressed in ray
    uint128 currentVariableBorrowRate;
    // DEPRECATED on v3.2.0
    uint128 currentStableBorrowRate;
    //timestamp of last update
    uint40 lastUpdateTimestamp;
    //the id of the reserve. Represents the position in the list of the active reserves
    uint16 id;
    //aToken address
    address aTokenAddress;
    // DEPRECATED on v3.2.0
    address stableDebtTokenAddress;
    //variableDebtToken address
    address variableDebtTokenAddress;
    //address of the interest rate strategy
    address interestRateStrategyAddress;
    //the current treasury balance, scaled
    uint128 accruedToTreasury;
    //the outstanding unbacked aTokens minted through the bridging feature
    uint128 unbacked;
    //the outstanding debt borrowed against this asset in isolation mode
    uint128 isolationModeTotalDebt;
  }

  /**
   * @notice Returns the state and configuration of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The state and configuration data of the reserve
   */
  function getReserveData(address asset) external view returns (ReserveDataLegacy memory);

  /**
   * @notice Returns the normalized variable debt per unit of asset
   * @dev WARNING: This function is intended to be used primarily by the protocol itself to get a
   * "dynamic" variable index based on time, current stored index and virtual rate at the current
   * moment (approx. a borrower would get if opening a position). This means that is always used in
   * combination with variable debt supply/balances.
   * If using this function externally, consider that is possible to have an increasing normalized
   * variable debt that is not equivalent to how the variable debt index would be updated in storage
   * (e.g. only updates with non-zero variable debt supply)
   * @param asset The address of the underlying asset of the reserve
   * @return The reserve normalized variable debt
   */
  function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);

  /**
   * @notice Supplies an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
   * - E.g. User supplies 100 USDC and gets in return 100 aUSDC
   * @param asset The address of the underlying asset to supply
   * @param amount The amount to be supplied
   * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
   *   wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
   *   is a different wallet
   * @param referralCode Code used to register the integrator originating the operation, for potential rewards.
   *   0 if the action is executed directly by the user, without any middle-man
   */
  function supply(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;

  /**
   * @notice Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
   * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
   * @param asset The address of the underlying asset to withdraw
   * @param amount The underlying amount to be withdrawn
   *   - Send the value type(uint256).max in order to withdraw the whole aToken balance
   * @param to The address that will receive the underlying, same as msg.sender if the user
   *   wants to receive it on his own wallet, or a different address if the beneficiary is a
   *   different wallet
   * @return The final amount withdrawn
   */
  function withdraw(address asset, uint256 amount, address to) external returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

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

interface IAaveFundingPool is IPool {
  /**********
   * Events *
   **********/

  /// @notice Emitted when interest snapshot is taken.
  /// @param borrowIndex The borrow index, multiplied by 1e27.
  /// @param timestamp The timestamp when this snapshot is taken.
  event SnapshotAaveBorrowIndex(uint256 borrowIndex, uint256 timestamp);

  /// @notice Emitted when the open fee ratio related parameters are updated.
  /// @param ratio The open ratio value, multiplied by 1e9.
  /// @param step The open ratio step value, multiplied by 1e18.
  event UpdateOpenRatio(uint256 ratio, uint256 step);

  /// @notice Emitted when the open fee ratio is updated.
  /// @param oldRatio The value of previous close fee ratio, multiplied by 1e9.
  /// @param newRatio The value of current close fee ratio, multiplied by 1e9.
  event UpdateCloseFeeRatio(uint256 oldRatio, uint256 newRatio);

  /// @notice Emitted when the funding fee ratio is updated.
  /// @param oldRatio The value of previous funding fee ratio, multiplied by 1e9.
  /// @param newRatio The value of current funding fee ratio, multiplied by 1e9.
  event UpdateFundingRatio(uint256 oldRatio, uint256 newRatio);

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return the value of funding ratio, multiplied by 1e9.
  function getFundingRatio() external view returns (uint256);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPegKeeper {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the converter contract is updated.
  /// @param oldConverter The address of previous converter contract.
  /// @param newConverter The address of current converter contract.
  event UpdateConverter(address indexed oldConverter, address indexed newConverter);

  /// @notice Emitted when the curve pool contract is updated.
  /// @param oldPool The address of previous curve pool contract.
  /// @param newPool The address of current curve pool contract.
  event UpdateCurvePool(address indexed oldPool, address indexed newPool);

  /// @notice Emitted when the price threshold is updated.
  /// @param oldThreshold The value of previous price threshold
  /// @param newThreshold The value of current price threshold
  event UpdatePriceThreshold(uint256 oldThreshold, uint256 newThreshold);

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return whether borrow for fxUSD is allowed.
  function isBorrowAllowed() external view returns (bool);

  /// @notice Return whether funding costs is enabled.
  function isFundingEnabled() external view returns (bool);
  
  /// @notice Return the price of fxUSD, multiplied by 1e18
  function getFxUSDPrice() external view returns (uint256);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Buyback fxUSD with stable reserve in FxUSDSave.
  /// @param amountIn the amount of stable token to use.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of fxUSD swapped.
  /// @return bonusOut The amount of bonus fxUSD.
  function buyback(uint256 amountIn, bytes calldata data) external returns (uint256 amountOut, uint256 bonusOut);

  /// @notice Stabilize the fxUSD price in curve pool.
  /// @param srcToken The address of source token (fxUSD or stable token).
  /// @param amountIn the amount of source token to use.
  /// @param data The hook data to `onSwap`.
  /// @return amountOut The amount of target token swapped.
  /// @return bonusOut The amount of bonus token.
  function stabilize(
    address srcToken,
    uint256 amountIn,
    bytes calldata data
  ) external returns (uint256 amountOut, uint256 bonusOut);

  /// @notice Swap callback from `buyback` and `stabilize`.
  /// @param srcToken The address of source token.
  /// @param srcToken The address of target token.
  /// @param amountIn the amount of source token to use.
  /// @param data The callback data.
  /// @return amountOut The amount of target token swapped.
  function onSwap(
    address srcToken,
    address targetToken,
    uint256 amountIn,
    bytes calldata data
  ) external returns (uint256 amountOut);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPool {
  /**********
   * Events *
   **********/

  /// @notice Emitted when price oracle is updated.
  /// @param oldOracle The previous address of price oracle.
  /// @param newOracle The current address of price oracle.
  event UpdatePriceOracle(address oldOracle, address newOracle);

  /// @notice Emitted when borrow status is updated.
  /// @param status The updated borrow status.
  event UpdateBorrowStatus(bool status);

  /// @notice Emitted when redeem status is updated.
  /// @param status The updated redeem status.
  event UpdateRedeemStatus(bool status);

  /// @notice Emitted when debt ratio range is updated.
  /// @param minDebtRatio The current value of minimum debt ratio, multiplied by 1e18.
  /// @param maxDebtRatio The current value of maximum debt ratio, multiplied by 1e18.
  event UpdateDebtRatioRange(uint256 minDebtRatio, uint256 maxDebtRatio);

  /// @notice Emitted when max redeem ratio per tick is updated.
  /// @param ratio The current value of max redeem ratio per tick, multiplied by 1e9.
  event UpdateMaxRedeemRatioPerTick(uint256 ratio);

  /// @notice Emitted when the rebalance ratio is updated.
  /// @param debtRatio The current value of rebalance debt ratio, multiplied by 1e18.
  /// @param bonusRatio The current value of rebalance bonus ratio, multiplied by 1e9.
  event UpdateRebalanceRatios(uint256 debtRatio, uint256 bonusRatio);

  /// @notice Emitted when the liquidate ratio is updated.
  /// @param debtRatio The current value of liquidate debt ratio, multiplied by 1e18.
  /// @param bonusRatio The current value of liquidate bonus ratio, multiplied by 1e9.
  event UpdateLiquidateRatios(uint256 debtRatio, uint256 bonusRatio);

  /// @notice Emitted when position is updated.
  /// @param position The index of this position.
  /// @param tick The index of tick, this position belongs to.
  /// @param collShares The amount of collateral shares in this position.
  /// @param debtShares The amount of debt shares in this position.
  /// @param price The price used for this operation.
  event PositionSnapshot(uint256 position, int16 tick, uint256 collShares, uint256 debtShares, uint256 price);

  /// @notice Emitted when tick moved due to rebalance, liquidate or redeem.
  /// @param oldTick The index of the previous tick.
  /// @param newTick The index of the current tick.
  /// @param collShares The amount of collateral shares added to new tick.
  /// @param debtShares The amount of debt shares added to new tick.
  /// @param price The price used for this operation.
  event TickMovement(int16 oldTick, int16 newTick, uint256 collShares, uint256 debtShares, uint256 price);

  /// @notice Emitted when debt index increase.
  event DebtIndexSnapshot(uint256 index);

  /// @notice Emitted when collateral index increase.
  event CollateralIndexSnapshot(uint256 index);

  /***********
   * Structs *
   ***********/

  /// @dev The result for liquidation.
  /// @param rawColls The amount of collateral tokens liquidated.
  /// @param rawDebts The amount of debt tokens liquidated.
  /// @param bonusRawColls The amount of bonus collateral tokens given.
  /// @param bonusFromReserve The amount of bonus collateral tokens coming from reserve pool.
  struct LiquidateResult {
    uint256 rawColls;
    uint256 rawDebts;
    uint256 bonusRawColls;
    uint256 bonusFromReserve;
  }

  /// @dev The result for rebalance.
  /// @param rawColls The amount of collateral tokens rebalanced.
  /// @param rawDebts The amount of debt tokens rebalanced.
  /// @param bonusRawColls The amount of bonus collateral tokens given.
  struct RebalanceResult {
    uint256 rawColls;
    uint256 rawDebts;
    uint256 bonusRawColls;
  }

  /*************************
   * Public View Functions *
   *************************/

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

  /// @notice The address of `PoolManager` contract.
  function poolManager() external view returns (address);

  /// @notice The address of `PegKeeper` contract.
  function pegKeeper() external view returns (address);

  /// @notice The address of collateral token.
  function collateralToken() external view returns (address);

  /// @notice The address of price oracle.
  function priceOracle() external view returns (address);

  /// @notice Return whether borrow is paused.
  function isBorrowPaused() external view returns (bool);

  /// @notice Return whether redeem is paused.
  function isRedeemPaused() external view returns (bool);

  /// @notice Return the current top tick with debts.
  function getTopTick() external view returns (int16);

  /// @notice Return the next position id.
  function getNextPositionId() external view returns (uint32);

  /// @notice Return the next tick tree node id.
  function getNextTreeNodeId() external view returns (uint48);

  /// @notice Return the debt ratio range.
  /// @param minDebtRatio The minimum required debt ratio, multiplied by 1e18.
  /// @param maxDebtRatio The minimum allowed debt ratio, multiplied by 1e18.
  function getDebtRatioRange() external view returns (uint256 minDebtRatio, uint256 maxDebtRatio);

  /// @notice Return the maximum redeem percentage per tick, multiplied by 1e9.
  function getMaxRedeemRatioPerTick() external view returns (uint256);

  /// @notice Get `debtRatio` and `bonusRatio` for rebalance.
  /// @return debtRatio The minimum debt ratio to start rebalance, multiplied by 1e18.
  /// @return bonusRatio The bonus ratio during rebalance, multiplied by 1e9.
  function getRebalanceRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);

  /// @notice Get `debtRatio` and `bonusRatio` for liquidate.
  /// @return debtRatio The minimum debt ratio to start liquidate, multiplied by 1e18.
  /// @return bonusRatio The bonus ratio during liquidate, multiplied by 1e9.
  function getLiquidateRatios() external view returns (uint256 debtRatio, uint256 bonusRatio);

  /// @notice Get debt and collateral index.
  /// @return debtIndex The index for debt shares.
  /// @return collIndex The index for collateral shares.
  function getDebtAndCollateralIndex() external view returns (uint256 debtIndex, uint256 collIndex);

  /// @notice Get debt and collateral shares.
  /// @return debtShares The total number of debt shares.
  /// @return collShares The total number of collateral shares.
  function getDebtAndCollateralShares() external view returns (uint256 debtShares, uint256 collShares);

  /// @notice Return the details of the given position.
  /// @param tokenId The id of position to query.
  /// @return rawColls The amount of collateral tokens supplied in this position.
  /// @return rawDebts The amount of debt tokens borrowed in this position.
  function getPosition(uint256 tokenId) external view returns (uint256 rawColls, uint256 rawDebts);

  /// @notice Return the debt ratio of the given position.
  /// @param tokenId The id of position to query.
  /// @return debtRatio The debt ratio of this position.
  function getPositionDebtRatio(uint256 tokenId) external view returns (uint256 debtRatio);

  /// @notice The total amount of raw collateral tokens.
  function getTotalRawCollaterals() external view returns (uint256);

  /// @notice The total amount of raw debt tokens.
  function getTotalRawDebts() external view returns (uint256);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Open a new position or operate on an old position.
  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.
  /// @param newRawColl The amount of collateral token to supply (positive value) or withdraw (negative value).
  /// @param newRawColl The amount of debt token to borrow (positive value) or repay (negative value).
  /// @param owner The address of position owner.
  /// @return actualPositionId The id of this position.
  /// @return actualRawColl The actual amount of collateral tokens supplied (positive value) or withdrawn (negative value).
  /// @return actualRawDebt The actual amount of debt tokens borrowed (positive value) or repay (negative value).
  function operate(
    uint256 positionId,
    int256 newRawColl,
    int256 newRawDebt,
    address owner
  ) external returns (uint256 actualPositionId, int256 actualRawColl, int256 actualRawDebt, uint256 protocolFees);

  /// @notice Redeem debt tokens to get collateral tokens.
  /// @param rawDebts The amount of debt tokens to redeem.
  /// @return rawColls The amount of collateral tokens to redeemed.
  function redeem(uint256 rawDebts) external returns (uint256 rawColls);

  /// @notice Rebalance all positions in the given tick.
  /// @param tick The id of tick to rebalance.
  /// @param maxRawDebts The maximum amount of debt tokens to rebalance.
  /// @return result The result of rebalance.
  function rebalance(int16 tick, uint256 maxRawDebts) external returns (RebalanceResult memory result);

  /// @notice Rebalance all ticks in the decreasing order of LTV.
  /// @param maxRawDebts The maximum amount of debt tokens to rebalance.
  /// @return result The result of rebalance.
  function rebalance(uint256 maxRawDebts) external returns (RebalanceResult memory result);

  /// @notice Liquidate all ticks in the decreasing order of LTV.
  /// @param maxRawDebts The maximum amount of debt tokens to liquidate.
  /// @param reservedRawColls The amount of collateral tokens in reserve pool.
  /// @return result The result of liquidate.
  function liquidate(uint256 maxRawDebts, uint256 reservedRawColls) external returns (LiquidateResult memory result);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPoolManager {
  /**********
   * Events *
   **********/
  
  /// @notice Register a new pool.
  /// @param pool The address of fx pool.
  event RegisterPool(address indexed pool);

  /// @notice Emitted when the reward splitter contract is updated.
  /// @param pool The address of fx pool.
  /// @param oldSplitter The address of previous reward splitter contract.
  /// @param newSplitter The address of current reward splitter contract.
  event UpdateRewardSplitter(address indexed pool, address indexed oldSplitter, address indexed newSplitter);

  /// @notice Emitted when the threshold for permissionless liquidate/rebalance is updated.
  /// @param oldThreshold The value of previous threshold.
  /// @param newThreshold The value of current threshold.
  event UpdatePermissionedLiquidationThreshold(uint256 oldThreshold, uint256 newThreshold);

  /// @notice Emitted when token rate is updated.
  /// @param scalar The token scalar to reach 18 decimals.
  /// @param provider The address of token rate provider.
  event UpdateTokenRate(address indexed token, uint256 scalar, address provider);

  /// @notice Emitted when pool capacity is updated.
  /// @param pool The address of fx pool.
  /// @param collateralCapacity The capacity for collateral token.
  /// @param debtCapacity The capacity for debt token.
  event UpdatePoolCapacity(address indexed pool, uint256 collateralCapacity, uint256 debtCapacity);

  /// @notice Emitted when position is updated.
  /// @param pool The address of pool where the position belongs to.
  /// @param position The id of the position.
  /// @param deltaColls The amount of collateral token changes.
  /// @param deltaDebts The amount of debt token changes.
  /// @param protocolFees The amount of protocol fees charges.
  event Operate(
    address indexed pool,
    uint256 indexed position,
    int256 deltaColls,
    int256 deltaDebts,
    uint256 protocolFees
  );
  
  /// @notice Emitted when redeem happened.
  /// @param pool The address of pool redeemed.
  /// @param colls The amount of collateral tokens redeemed.
  /// @param debts The amount of debt tokens redeemed.
  /// @param protocolFees The amount of protocol fees charges.
  event Redeem(address indexed pool, uint256 colls, uint256 debts, uint256 protocolFees);

  /// @notice Emitted when rebalance for a tick happened.
  /// @param pool The address of pool rebalanced.
  /// @param tick The index of tick rebalanced.
  /// @param colls The amount of collateral tokens rebalanced.
  /// @param fxUSDDebts The amount of fxUSD rebalanced.
  /// @param stableDebts The amount of stable token (a.k.a USDC) rebalanced.
  event RebalanceTick(address indexed pool, int16 indexed tick, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);

  /// @notice Emitted when rebalance happened.
  /// @param pool The address of pool rebalanced.
  /// @param colls The amount of collateral tokens rebalanced.
  /// @param fxUSDDebts The amount of fxUSD rebalanced.
  /// @param stableDebts The amount of stable token (a.k.a USDC) rebalanced.
  event Rebalance(address indexed pool, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);

  /// @notice Emitted when liquidate happened.
  /// @param pool The address of pool liquidated.
  /// @param colls The amount of collateral tokens liquidated.
  /// @param fxUSDDebts The amount of fxUSD liquidated.
  /// @param stableDebts The amount of stable token (a.k.a USDC) liquidated.
  event Liquidate(address indexed pool, uint256 colls, uint256 fxUSDDebts, uint256 stableDebts);

  /// @notice Emitted when someone harvest pending rewards.
  /// @param caller The address of caller.
  /// @param amountRewards The amount of total harvested rewards.
  /// @param amountFunding The amount of total harvested funding.
  /// @param performanceFee The amount of harvested rewards distributed to protocol revenue.
  /// @param harvestBounty The amount of harvested rewards distributed to caller as harvest bounty.
  event Harvest(
    address indexed caller,
    address indexed pool,
    uint256 amountRewards,
    uint256 amountFunding,
    uint256 performanceFee,
    uint256 harvestBounty
  );

  /*************************
   * Public View Functions *
   *************************/
  
  /// @notice The address of fxUSD.
  function fxUSD() external view returns (address);

  /// @notice The address of FxUSDSave.
  function fxBASE() external view returns (address);

  /// @notice The address of `PegKeeper`.
  function pegKeeper() external view returns (address);

  /// @notice The address of reward splitter.
  function rewardSplitter(address pool) external view returns (address);

  /****************************
   * Public Mutated Functions *
   ****************************/
  
  /// @notice Open a new position or operate on an old position.
  /// @param pool The address of pool to operate.
  /// @param positionId The id of the position. If `positionId=0`, it means we need to open a new position.
  /// @param newColl The amount of collateral token to supply (positive value) or withdraw (negative value).
  /// @param newDebt The amount of debt token to borrow (positive value) or repay (negative value).
  /// @return actualPositionId The id of this position.
  function operate(
    address pool,
    uint256 positionId,
    int256 newColl,
    int256 newDebt
  ) external returns (uint256 actualPositionId);

  /// @notice Redeem debt tokens to get collateral tokens.
  /// @param pool The address of pool to redeem.
  /// @param debts The amount of debt tokens to redeem.
  /// @param minColls The minimum amount of collateral tokens should redeem.
  /// @return colls The amount of collateral tokens redeemed.
  function redeem(address pool, uint256 debts, uint256 minColls) external returns (uint256 colls);

  /// @notice Rebalance all positions in the given tick.
  /// @param pool The address of pool to rebalance.
  /// @param receiver The address of recipient for rebalanced tokens.
  /// @param tick The index of tick to rebalance.
  /// @param maxFxUSD The maximum amount of fxUSD to rebalance.
  /// @param maxStable The maximum amount of stable token (a.k.a USDC) to rebalance.
  /// @return colls The amount of collateral tokens rebalanced.
  /// @return fxUSDUsed The amount of fxUSD used to rebalance.
  /// @return stableUsed The amount of stable token used to rebalance.
  function rebalance(
    address pool,
    address receiver,
    int16 tick,
    uint256 maxFxUSD,
    uint256 maxStable
  ) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);

  /// @notice Rebalance all positions in the given tick.
  /// @param pool The address of pool to rebalance.
  /// @param receiver The address of recipient for rebalanced tokens.
  /// @param maxFxUSD The maximum amount of fxUSD to rebalance.
  /// @param maxStable The maximum amount of stable token (a.k.a USDC) to rebalance.
  /// @return colls The amount of collateral tokens rebalanced.
  /// @return fxUSDUsed The amount of fxUSD used to rebalance.
  /// @return stableUsed The amount of stable token used to rebalance.
  function rebalance(
    address pool,
    address receiver,
    uint256 maxFxUSD,
    uint256 maxStable
  ) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);

  /// @notice Liquidate a given position.
  /// @param pool The address of pool to liquidate.
  /// @param receiver The address of recipient for liquidated tokens.
  /// @param maxFxUSD The maximum amount of fxUSD to liquidate.
  /// @param maxStable The maximum amount of stable token (a.k.a USDC) to liquidate.
  /// @return colls The amount of collateral tokens liquidated.
  /// @return fxUSDUsed The amount of fxUSD used to liquidate.
  /// @return stableUsed The amount of stable token used to liquidate.
  function liquidate(
    address pool,
    address receiver,
    uint256 maxFxUSD,
    uint256 maxStable
  ) external returns (uint256 colls, uint256 fxUSDUsed, uint256 stableUsed);

  /// @notice Harvest pending rewards of the given pool.
  /// @param pool The address of pool to harvest.
  /// @return amountRewards The amount of rewards harvested.
  /// @return amountFunding The amount of funding harvested.
  function harvest(address pool) external returns (uint256 amountRewards, uint256 amountFunding);
}

// SPDX-License-Identifier: GPL-2.0-or-later

pragma solidity ^0.8.0;

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
///
/// copy from: https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/BitMath.sol
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        if (x >= 0x100000000000000000000000000000000) {
            x >>= 128;
            r += 128;
        }
        if (x >= 0x10000000000000000) {
            x >>= 64;
            r += 64;
        }
        if (x >= 0x100000000) {
            x >>= 32;
            r += 32;
        }
        if (x >= 0x10000) {
            x >>= 16;
            r += 16;
        }
        if (x >= 0x100) {
            x >>= 8;
            r += 8;
        }
        if (x >= 0x10) {
            x >>= 4;
            r += 4;
        }
        if (x >= 0x4) {
            x >>= 2;
            r += 2;
        }
        if (x >= 0x2) r += 1;
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @dev The function satisfies the property:
    ///     (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        r = 255;
        if (x & type(uint128).max > 0) {
            r -= 128;
        } else {
            x >>= 128;
        }
        if (x & type(uint64).max > 0) {
            r -= 64;
        } else {
            x >>= 64;
        }
        if (x & type(uint32).max > 0) {
            r -= 32;
        } else {
            x >>= 32;
        }
        if (x & type(uint16).max > 0) {
            r -= 16;
        } else {
            x >>= 16;
        }
        if (x & type(uint8).max > 0) {
            r -= 8;
        } else {
            x >>= 8;
        }
        if (x & 0xf > 0) {
            r -= 4;
        } else {
            x >>= 4;
        }
        if (x & 0x3 > 0) {
            r -= 2;
        } else {
            x >>= 2;
        }
        if (x & 0x1 > 0) r -= 1;
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

library Math {
  enum Rounding {
    Up,
    Down
  }

  /// @dev Internal return the value of min(a, b).
  function min(uint256 a, uint256 b) internal pure returns (uint256) {
    return a < b ? a : b;
  }

  /// @dev Internal return the value of max(a, b).
  function max(uint256 a, uint256 b) internal pure returns (uint256) {
    return a > b ? a : b;
  }

  /// @dev Internal return the value of a * b / c, with rounding.
  function mulDiv(uint256 a, uint256 b, uint256 c, Rounding rounding) internal pure returns (uint256) {
    return rounding == Rounding.Down ? mulDivDown(a, b, c) : mulDivUp(a, b, c);
  }

  /// @dev Internal return the value of ceil(a * b / c).
  function mulDivUp(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
    return (a * b + c - 1) / c;
  }

  /// @dev Internal return the value of floor(a * b / c).
  function mulDivDown(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
    return (a * b) / c;
  }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.26;

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

library TickBitmap {
  function position(int16 tick) private pure returns (int8 wordPos, uint8 bitPos) {
    assembly {
      wordPos := shr(8, tick)
      bitPos := and(tick, 255)
    }
  }

  function flipTick(mapping(int8 => uint256) storage self, int16 tick) internal {
    (int8 wordPos, uint8 bitPos) = position(tick);
    uint256 mask = 1 << bitPos;
    self[wordPos] ^= mask;
  }

  function isBitSet(mapping(int8 => uint256) storage self, int16 tick) internal view returns (bool) {
    (int8 wordPos, uint8 bitPos) = position(tick);
    uint256 mask = 1 << bitPos;
    return (self[wordPos] & mask) > 0;
  }

  /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is
  /// to the left (less than or equal to).
  function nextDebtPositionWithinOneWord(
    mapping(int8 => uint256) storage self,
    int16 tick
  ) internal view returns (int16 next, bool hasDebt) {
    unchecked {
      // start from the word of the next tick, since the current tick state doesn't matter
      (int8 wordPos, uint8 bitPos) = position(tick);
      // all the 1s at or to the right of the current bitPos
      uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);
      uint256 masked = self[wordPos] & mask;

      // if there are no initialized ticks to the left of the current tick, return leftmost in the word
      hasDebt = masked != 0;
      // overflow/underflow is possible, but prevented externally by limiting tick
      next = hasDebt
        ? (tick - int16(uint16(bitPos - BitMath.mostSignificantBit(masked))))
        : (tick - int16(uint16(bitPos)));
    }
  }
}

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.26;

/// @title library that calculates number "tick" and "ratioX96" from this: ratioX96 = (1.0015^tick) * 2^96
/// @notice this library is used in Fluid Vault protocol for optimiziation.
/// @dev "tick" supports between -32767 and 32767. "ratioX96" supports between 37075072 and 169307877264527972847801929085841449095838922544595
///
/// @dev Copy from https://github.com/Instadapp/fluid-contracts-public/blob/main/contracts/libraries/tickMath.sol
library TickMath {
    /// The minimum tick that can be passed in getRatioAtTick. 1.0015**-32767
    int24 internal constant MIN_TICK = -32767;
    /// The maximum tick that can be passed in getRatioAtTick. 1.0015**32767
    int24 internal constant MAX_TICK = 32767;

    uint256 internal constant FACTOR00 = 0x100000000000000000000000000000000;
    uint256 internal constant FACTOR01 = 0xff9dd7de423466c20352b1246ce4856f; // 2^128/1.0015**1 = 339772707859149738855091969477551883631
    uint256 internal constant FACTOR02 = 0xff3bd55f4488ad277531fa1c725a66d0; // 2^128/1.0015**2 = 339263812140938331358054887146831636176
    uint256 internal constant FACTOR03 = 0xfe78410fd6498b73cb96a6917f853259; // 2^128/1.0015**4 = 338248306163758188337119769319392490073
    uint256 internal constant FACTOR04 = 0xfcf2d9987c9be178ad5bfeffaa123273; // 2^128/1.0015**8 = 336226404141693512316971918999264834163
    uint256 internal constant FACTOR05 = 0xf9ef02c4529258b057769680fc6601b3; // 2^128/1.0015**16 = 332218786018727629051611634067491389875
    uint256 internal constant FACTOR06 = 0xf402d288133a85a17784a411f7aba082; // 2^128/1.0015**32 = 324346285652234375371948336458280706178
    uint256 internal constant FACTOR07 = 0xe895615b5beb6386553757b0352bda90; // 2^128/1.0015**64 = 309156521885964218294057947947195947664
    uint256 internal constant FACTOR08 = 0xd34f17a00ffa00a8309940a15930391a; // 2^128/1.0015**128 = 280877777739312896540849703637713172762 
    uint256 internal constant FACTOR09 = 0xae6b7961714e20548d88ea5123f9a0ff; // 2^128/1.0015**256 = 231843708922198649176471782639349113087
    uint256 internal constant FACTOR10 = 0x76d6461f27082d74e0feed3b388c0ca1; // 2^128/1.0015**512 = 157961477267171621126394973980180876449
    uint256 internal constant FACTOR11 = 0x372a3bfe0745d8b6b19d985d9a8b85bb; // 2^128/1.0015**1024 = 73326833024599564193373530205717235131
    uint256 internal constant FACTOR12 = 0x0be32cbee48979763cf7247dd7bb539d; // 2^128/1.0015**2048 = 15801066890623697521348224657638773661
    uint256 internal constant FACTOR13 = 0x8d4f70c9ff4924dac37612d1e2921e;   // 2^128/1.0015**4096 = 733725103481409245883800626999235102
    uint256 internal constant FACTOR14 = 0x4e009ae5519380809a02ca7aec77;     // 2^128/1.0015**8192 = 1582075887005588088019997442108535
    uint256 internal constant FACTOR15 = 0x17c45e641b6e95dee056ff10;         // 2^128/1.0015**16384 = 7355550435635883087458926352

    /// The minimum value that can be returned from getRatioAtTick. Equivalent to getRatioAtTick(MIN_TICK). ~ Equivalent to `(1 << 96) * (1.0015**-32767)`
    uint256 internal constant MIN_RATIOX96 = 37075072;
    /// The maximum value that can be returned from getRatioAtTick. Equivalent to getRatioAtTick(MAX_TICK).
    /// ~ Equivalent to `(1 << 96) * (1.0015**32767)`, rounding etc. leading to minor difference
    uint256 internal constant MAX_RATIOX96 = 169307877264527972847801929085841449095838922544595;

    uint256 internal constant ZERO_TICK_SCALED_RATIO = 0x1000000000000000000000000; // 1 << 96 // 79228162514264337593543950336
    uint256 internal constant _1E26 = 1e26;

    /// @notice ratioX96 = (1.0015^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return ratioX96 ratio = (debt amount/collateral amount)
    function getRatioAtTick(int tick) internal pure returns (uint256 ratioX96) {
        assembly {
            let absTick_ := sub(xor(tick, sar(255, tick)), sar(255, tick))

            if gt(absTick_, MAX_TICK) {
                revert(0, 0)
            }
            let factor_ := FACTOR00
            if and(absTick_, 0x1) {
                factor_ := FACTOR01
            }
            if and(absTick_, 0x2) {
                factor_ := shr(128, mul(factor_, FACTOR02))
            }
            if and(absTick_, 0x4) {
                factor_ := shr(128, mul(factor_, FACTOR03))
            }
            if and(absTick_, 0x8) {
                factor_ := shr(128, mul(factor_, FACTOR04))
            }
            if and(absTick_, 0x10) {
                factor_ := shr(128, mul(factor_, FACTOR05))
            }
            if and(absTick_, 0x20) {
                factor_ := shr(128, mul(factor_, FACTOR06))
            }
            if and(absTick_, 0x40) {
                factor_ := shr(128, mul(factor_, FACTOR07))
            }
            if and(absTick_, 0x80) {
                factor_ := shr(128, mul(factor_, FACTOR08))
            }
            if and(absTick_, 0x100) {
                factor_ := shr(128, mul(factor_, FACTOR09))
            }
            if and(absTick_, 0x200) {
                factor_ := shr(128, mul(factor_, FACTOR10))
            }
            if and(absTick_, 0x400) {
                factor_ := shr(128, mul(factor_, FACTOR11))
            }
            if and(absTick_, 0x800) {
                factor_ := shr(128, mul(factor_, FACTOR12))
            }
            if and(absTick_, 0x1000) {
                factor_ := shr(128, mul(factor_, FACTOR13))
            }
            if and(absTick_, 0x2000) {
                factor_ := shr(128, mul(factor_, FACTOR14))
            }
            if and(absTick_, 0x4000) {
                factor_ := shr(128, mul(factor_, FACTOR15))
            }

            let precision_ := 0
            if iszero(and(tick, 0x8000000000000000000000000000000000000000000000000000000000000000)) {
                factor_ := div(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, factor_)
                // we round up in the division so getTickAtRatio of the output price is always consistent
                if mod(factor_, 0x100000000) {
                    precision_ := 1
                }
            }
            ratioX96 := add(shr(32, factor_), precision_)
        }
    }

    /// @notice ratioX96 = (1.0015^tick) * 2^96
    /// @dev Throws if ratioX96 > max ratio || ratioX96 < min ratio
    /// @param ratioX96 The input ratio; ratio = (debt amount/collateral amount)
    /// @return tick The output tick for the above formula. Returns in round down form. if tick is 123.23 then 123, if tick is -123.23 then returns -124
    /// @return perfectRatioX96 perfect ratio for the above tick
    function getTickAtRatio(uint256 ratioX96) internal pure returns (int tick, uint perfectRatioX96) {
        assembly {
            if or(gt(ratioX96, MAX_RATIOX96), lt(ratioX96, MIN_RATIOX96)) {
                revert(0, 0)
            }

            let cond := lt(ratioX96, ZERO_TICK_SCALED_RATIO)
            let factor_

            if iszero(cond) {
                // if ratioX96 >= ZERO_TICK_SCALED_RATIO
                factor_ := div(mul(ratioX96, _1E26), ZERO_TICK_SCALED_RATIO)
            }
            if cond {
                // ratioX96 < ZERO_TICK_SCALED_RATIO
                factor_ := div(mul(ZERO_TICK_SCALED_RATIO, _1E26), ratioX96)
            }

            // put in https://www.wolframalpha.com/ whole equation: (1.0015^tick) * 2^96 * 10^26 / 79228162514264337593543950336

            // for tick = 16384
            // ratioX96 = (1.0015^16384) * 2^96 = 3665252098134783297721995888537077351735
            // 3665252098134783297721995888537077351735 * 10^26 / 79228162514264337593543950336 =
            // 4626198540796508716348404308345255985.06131964639489434655721
            if iszero(lt(factor_, 4626198540796508716348404308345255985)) {
                tick := or(tick, 0x4000)
                factor_ := div(mul(factor_, _1E26), 4626198540796508716348404308345255985)
            }
            // for tick = 8192
            // ratioX96 = (1.0015^8192) * 2^96 = 17040868196391020479062776466509865
            // 17040868196391020479062776466509865 * 10^26 / 79228162514264337593543950336 =
            // 21508599537851153911767490449162.3037648642153898377655505172
            if iszero(lt(factor_, 21508599537851153911767490449162)) {
                tick := or(tick, 0x2000)
                factor_ := div(mul(factor_, _1E26), 21508599537851153911767490449162)
            }
            // for tick = 4096
            // ratioX96 = (1.0015^4096) * 2^96 = 36743933851015821532611831851150
            // 36743933851015821532611831851150 * 10^26 / 79228162514264337593543950336 =
            // 46377364670549310883002866648.9777607649742626173648716941385
            if iszero(lt(factor_, 46377364670549310883002866649)) {
                tick := or(tick, 0x1000)
                factor_ := div(mul(factor_, _1E26), 46377364670549310883002866649)
            }
            // for tick = 2048
            // ratioX96 = (1.0015^2048) * 2^96 = 1706210527034005899209104452335
            // 1706210527034005899209104452335 * 10^26 / 79228162514264337593543950336 =
            // 2153540449365864845468344760.06357108484096046743300420319322
            if iszero(lt(factor_, 2153540449365864845468344760)) {
                tick := or(tick, 0x800)
                factor_ := div(mul(factor_, _1E26), 2153540449365864845468344760)
            }
            // for tick = 1024
            // ratioX96 = (1.0015^1024) * 2^96 = 367668226692760093024536487236
            // 367668226692760093024536487236 * 10^26 / 79228162514264337593543950336 =
            // 464062544207767844008185024.950588990554136265212906454481127
            if iszero(lt(factor_, 464062544207767844008185025)) {
                tick := or(tick, 0x400)
                factor_ := div(mul(factor_, _1E26), 464062544207767844008185025)
            }
            // for tick = 512
            // ratioX96 = (1.0015^512) * 2^96 = 170674186729409605620119663668
            // 170674186729409605620119663668 * 10^26 / 79228162514264337593543950336 =
            // 215421109505955298802281577.031879604792139232258508172947569
            if iszero(lt(factor_, 215421109505955298802281577)) {
                tick := or(tick, 0x200)
                factor_ := div(mul(factor_, _1E26), 215421109505955298802281577)
            }
            // for tick = 256
            // ratioX96 = (1.0015^256) * 2^96 = 116285004205991934861656513301
            // 116285004205991934861656513301 * 10^26 / 79228162514264337593543950336 =
            // 146772309890508740607270614.667650899656438875541505058062410
            if iszero(lt(factor_, 146772309890508740607270615)) {
                tick := or(tick, 0x100)
                factor_ := div(mul(factor_, _1E26), 146772309890508740607270615)
            }
            // for tick = 128
            // ratioX96 = (1.0015^128) * 2^96 = 95984619659632141743747099590
            // 95984619659632141743747099590 * 10^26 / 79228162514264337593543950336 =
            // 121149622323187099817270416.157248837742741760456796835775887
            if iszero(lt(factor_, 121149622323187099817270416)) {
                tick := or(tick, 0x80)
                factor_ := div(mul(factor_, _1E26), 121149622323187099817270416)
            }
            // for tick = 64
            // ratioX96 = (1.0015^64) * 2^96 = 87204845308406958006717891124
            // 87204845308406958006717891124 * 10^26 / 79228162514264337593543950336 =
            // 110067989135437147685980801.568068573422377364214113968609839
            if iszero(lt(factor_, 110067989135437147685980801)) {
                tick := or(tick, 0x40)
                factor_ := div(mul(factor_, _1E26), 110067989135437147685980801)
            }
            // for tick = 32
            // ratioX96 = (1.0015^32) * 2^96 = 83120873769022354029916374475
            // 83120873769022354029916374475 * 10^26 / 79228162514264337593543950336 =
            // 104913292358707887270979599.831816586773651266562785765558183
            if iszero(lt(factor_, 104913292358707887270979600)) {
                tick := or(tick, 0x20)
                factor_ := div(mul(factor_, _1E26), 104913292358707887270979600)
            }
            // for tick = 16
            // ratioX96 = (1.0015^16) * 2^96 = 81151180492336368327184716176
            // 81151180492336368327184716176 * 10^26 / 79228162514264337593543950336 =
            // 102427189924701091191840927.762844039579442328381455567932128
            if iszero(lt(factor_, 102427189924701091191840928)) {
                tick := or(tick, 0x10)
                factor_ := div(mul(factor_, _1E26), 102427189924701091191840928)
            }
            // for tick = 8
            // ratioX96 = (1.0015^8) * 2^96 = 80183906840906820640659903620
            // 80183906840906820640659903620 * 10^26 / 79228162514264337593543950336 =
            // 101206318935480056907421312.890625
            if iszero(lt(factor_, 101206318935480056907421313)) {
                tick := or(tick, 0x8)
                factor_ := div(mul(factor_, _1E26), 101206318935480056907421313)
            }
            // for tick = 4
            // ratioX96 = (1.0015^4) * 2^96 = 79704602139525152702959747603
            // 79704602139525152702959747603 * 10^26 / 79228162514264337593543950336 =
            // 100601351350506250000000000
            if iszero(lt(factor_, 100601351350506250000000000)) {
                tick := or(tick, 0x4)
                factor_ := div(mul(factor_, _1E26), 100601351350506250000000000)
            }
            // for tick = 2
            // ratioX96 = (1.0015^2) * 2^96 = 79466025265172787701084167660
            // 79466025265172787701084167660 * 10^26 / 79228162514264337593543950336 =
            // 100300225000000000000000000
            if iszero(lt(factor_, 100300225000000000000000000)) {
                tick := or(tick, 0x2)
                factor_ := div(mul(factor_, _1E26), 100300225000000000000000000)
            }
            // for tick = 1
            // ratioX96 = (1.0015^1) * 2^96 = 79347004758035734099934266261
            // 79347004758035734099934266261 * 10^26 / 79228162514264337593543950336 =
            // 100150000000000000000000000
            if iszero(lt(factor_, 100150000000000000000000000)) {
                tick := or(tick, 0x1)
                factor_ := div(mul(factor_, _1E26), 100150000000000000000000000)
            }
            if iszero(cond) {
                // if ratioX96 >= ZERO_TICK_SCALED_RATIO
                perfectRatioX96 := div(mul(ratioX96, _1E26), factor_)
            }
            if cond {
                // ratioX96 < ZERO_TICK_SCALED_RATIO
                tick := not(tick)
                perfectRatioX96 := div(mul(ratioX96, factor_), 100150000000000000000000000)
            }
            // perfect ratio should always be <= ratioX96
            // not sure if it can ever be bigger but better to have extra checks
            if gt(perfectRatioX96, ratioX96) {
                revert(0, 0)
            }
        }
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPriceOracle {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the value of maximum price deviation is updated.
  /// @param oldValue The value of the previous maximum price deviation.
  /// @param newValue The value of the current maximum price deviation.
  event UpdateMaxPriceDeviation(uint256 oldValue, uint256 newValue);

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return the oracle price with 18 decimal places.
  /// @return anchorPrice The anchor price for this asset, multiplied by 1e18. It should be hard to manipulate,
  ///         like time-weighted average price or chainlink spot price.
  /// @return minPrice The minimum oracle price among all available price sources (including twap), multiplied by 1e18.
  /// @return maxPrice The maximum oracle price among all available price sources (including twap), multiplied by 1e18.
  function getPrice() external view returns (uint256 anchorPrice, uint256 minPrice, uint256 maxPrice);

  /// @notice Return the oracle price for exchange with 18 decimal places.
  function getExchangePrice() external view returns (uint256);

  /// @notice Return the oracle price for liquidation with 18 decimal places.
  function getLiquidatePrice() external view returns (uint256);

  /// @notice Return the oracle price for redemption with 18 decimal places.
  function getRedeemPrice() external view returns (uint256);
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "evmVersion": "cancun",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_poolManager","type":"address"},{"internalType":"address","name":"_lendingPool","type":"address"},{"internalType":"address","name":"_baseAsset","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC721IncorrectOwner","type":"error"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ERC721InsufficientApproval","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC721InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"ERC721InvalidOperator","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"ERC721InvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC721InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC721InvalidSender","type":"error"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ERC721NonexistentToken","type":"error"},{"inputs":[],"name":"ErrorBorrowPaused","type":"error"},{"inputs":[],"name":"ErrorCallerNotPoolManager","type":"error"},{"inputs":[],"name":"ErrorCollateralTooSmall","type":"error"},{"inputs":[],"name":"ErrorDebtRatioTooLarge","type":"error"},{"inputs":[],"name":"ErrorDebtRatioTooSmall","type":"error"},{"inputs":[],"name":"ErrorDebtTooSmall","type":"error"},{"inputs":[],"name":"ErrorInsufficientCollateralToLiquidate","type":"error"},{"inputs":[],"name":"ErrorNoSupplyAndNoBorrow","type":"error"},{"inputs":[],"name":"ErrorNotPositionOwner","type":"error"},{"inputs":[],"name":"ErrorOverflow","type":"error"},{"inputs":[],"name":"ErrorPoolUnderCollateral","type":"error"},{"inputs":[],"name":"ErrorPositionInLiquidationMode","type":"error"},{"inputs":[],"name":"ErrorRebalanceDebtRatioNotReached","type":"error"},{"inputs":[],"name":"ErrorRebalanceOnLiquidatablePosition","type":"error"},{"inputs":[],"name":"ErrorRebalanceOnLiquidatableTick","type":"error"},{"inputs":[],"name":"ErrorRedeemPaused","type":"error"},{"inputs":[],"name":"ErrorValueTooLarge","type":"error"},{"inputs":[],"name":"ErrorWithdrawExceedSupply","type":"error"},{"inputs":[],"name":"ErrorZeroAddress","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"CollateralIndexSnapshot","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"}],"name":"DebtIndexSnapshot","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"position","type":"uint256"},{"indexed":false,"internalType":"int16","name":"tick","type":"int16"},{"indexed":false,"internalType":"uint256","name":"collShares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtShares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"}],"name":"PositionSnapshot","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"borrowIndex","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"SnapshotAaveBorrowIndex","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int16","name":"oldTick","type":"int16"},{"indexed":false,"internalType":"int16","name":"newTick","type":"int16"},{"indexed":false,"internalType":"uint256","name":"collShares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debtShares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"}],"name":"TickMovement","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"status","type":"bool"}],"name":"UpdateBorrowStatus","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRatio","type":"uint256"}],"name":"UpdateCloseFeeRatio","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"minDebtRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"maxDebtRatio","type":"uint256"}],"name":"UpdateDebtRatioRange","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRatio","type":"uint256"}],"name":"UpdateFundingRatio","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"debtRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusRatio","type":"uint256"}],"name":"UpdateLiquidateRatios","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ratio","type":"uint256"}],"name":"UpdateMaxRedeemRatioPerTick","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"ratio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"step","type":"uint256"}],"name":"UpdateOpenRatio","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldOracle","type":"address"},{"indexed":false,"internalType":"address","name":"newOracle","type":"address"}],"name":"UpdatePriceOracle","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"debtRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusRatio","type":"uint256"}],"name":"UpdateRebalanceRatios","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"status","type":"bool"}],"name":"UpdateRedeemStatus","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"EMERGENCY_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowRateSnapshot","outputs":[{"internalType":"uint128","name":"borrowIndex","type":"uint128"},{"internalType":"uint80","name":"lastInterestRate","type":"uint80"},{"internalType":"uint48","name":"timestamp","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fxUSD","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCloseFeeRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtAndCollateralIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtAndCollateralShares","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDebtRatioRange","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getFundingRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidateRatios","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMaxRedeemRatioPerTick","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNextPositionId","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNextTreeNodeId","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOpenFeeRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOpenRatio","outputs":[{"internalType":"uint256","name":"ratio","type":"uint256"},{"internalType":"uint256","name":"step","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getPosition","outputs":[{"internalType":"uint256","name":"rawColls","type":"uint256"},{"internalType":"uint256","name":"rawDebts","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getPositionDebtRatio","outputs":[{"internalType":"uint256","name":"debtRatio","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRebalanceRatios","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTopTick","outputs":[{"internalType":"int16","name":"","type":"int16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalRawCollaterals","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTotalRawDebts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"admin","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"address","name":"_collateralToken","type":"address"},{"internalType":"address","name":"_priceOracle","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isBorrowPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isRedeemPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"maxRawDebts","type":"uint256"},{"internalType":"uint256","name":"reservedRawColls","type":"uint256"}],"name":"liquidate","outputs":[{"components":[{"internalType":"uint256","name":"rawColls","type":"uint256"},{"internalType":"uint256","name":"rawDebts","type":"uint256"},{"internalType":"uint256","name":"bonusRawColls","type":"uint256"},{"internalType":"uint256","name":"bonusFromReserve","type":"uint256"}],"internalType":"struct IPool.LiquidateResult","name":"result","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"positionId","type":"uint256"},{"internalType":"int256","name":"newRawColl","type":"int256"},{"internalType":"int256","name":"newRawDebt","type":"int256"},{"internalType":"address","name":"owner","type":"address"}],"name":"operate","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"int256","name":"","type":"int256"},{"internalType":"int256","name":"","type":"int256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pegKeeper","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"positionData","outputs":[{"internalType":"int16","name":"tick","type":"int16"},{"internalType":"uint48","name":"nodeId","type":"uint48"},{"internalType":"uint96","name":"colls","type":"uint96"},{"internalType":"uint96","name":"debts","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"positionMetadata","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"priceOracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int16","name":"tick","type":"int16"},{"internalType":"uint256","name":"maxRawDebts","type":"uint256"}],"name":"rebalance","outputs":[{"components":[{"internalType":"uint256","name":"rawColls","type":"uint256"},{"internalType":"uint256","name":"rawDebts","type":"uint256"},{"internalType":"uint256","name":"bonusRawColls","type":"uint256"}],"internalType":"struct IPool.RebalanceResult","name":"result","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"maxRawDebts","type":"uint256"}],"name":"rebalance","outputs":[{"components":[{"internalType":"uint256","name":"rawColls","type":"uint256"},{"internalType":"uint256","name":"rawDebts","type":"uint256"},{"internalType":"uint256","name":"bonusRawColls","type":"uint256"}],"internalType":"struct IPool.RebalanceResult","name":"result","type":"tuple"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"rawDebts","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"rawColls","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int8","name":"","type":"int8"}],"name":"tickBitmap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"","type":"int256"}],"name":"tickData","outputs":[{"internalType":"uint48","name":"","type":"uint48"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"tickTreeData","outputs":[{"internalType":"bytes32","name":"metadata","type":"bytes32"},{"internalType":"bytes32","name":"value","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"borrowStatus","type":"bool"},{"internalType":"bool","name":"redeemStatus","type":"bool"}],"name":"updateBorrowAndRedeemStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"ratio","type":"uint256"}],"name":"updateCloseFeeRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"minRatio","type":"uint256"},{"internalType":"uint256","name":"maxRatio","type":"uint256"}],"name":"updateDebtRatioRange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"ratio","type":"uint256"}],"name":"updateFundingRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"debtRatio","type":"uint256"},{"internalType":"uint256","name":"bonusRatio","type":"uint256"}],"name":"updateLiquidateRatios","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"ratio","type":"uint256"}],"name":"updateMaxRedeemRatioPerTick","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"ratio","type":"uint256"},{"internalType":"uint256","name":"step","type":"uint256"}],"name":"updateOpenRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOracle","type":"address"}],"name":"updatePriceOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"debtRatio","type":"uint256"},{"internalType":"uint256","name":"bonusRatio","type":"uint256"}],"name":"updateRebalanceRatios","outputs":[],"stateMutability":"nonpayable","type":"function"}]

610120604052348015610010575f80fd5b5060405161602d38038061602d83398101604081905261002f9161019a565b8261003981610155565b6001600160a01b03811660a081905260408051636dbe4bb960e01b81529051636dbe4bb9916004808201926020929091908290030181865afa158015610081573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906100a591906101da565b6001600160a01b03166080816001600160a01b031681525050806001600160a01b031662799a5e6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156100f9573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061011d91906101da565b6001600160a01b031660c0525061013382610155565b61013c81610155565b6001600160a01b0391821660e0521661010052506101fa565b6001600160a01b03811661017c5760405163a7f9319d60e01b815260040160405180910390fd5b50565b80516001600160a01b0381168114610195575f80fd5b919050565b5f805f606084860312156101ac575f80fd5b6101b58461017f565b92506101c36020850161017f565b91506101d16040850161017f565b90509250925092565b5f602082840312156101ea575f80fd5b6101f38261017f565b9392505050565b60805160a05160c05160e05161010051615da96102845f395f8181611b0d01528181611bb90152613a3001525f8181611b3701528181611be60152613a6801525f81816103d201528181610b5c0152612b7c01525f818161098c01528181610a480152818161147401528181611fdc015281816122eb015261278f01525f6106c50152615da95ff3fe608060405234801561000f575f80fd5b50600436106103c9575f3560e01c806370f3c4b111610200578063b71348d11161011f578063dc4c90d3116100b4578063eb02c30111610084578063eb02c301146109e8578063ee65a03c146109fb578063efc5824014610a03578063f499301814610a16578063f9d45fd214610a29575f80fd5b8063dc4c90d314610987578063df9cbd3a146109ae578063e985e9c5146109cd578063e9a0e8fa146109e0575f80fd5b8063d032c4e5116100ef578063d032c4e514610908578063d296d1f11461091b578063d547741f14610961578063db006a7514610974575f80fd5b8063b71348d1146108c7578063b88d4fde146108da578063c64dc8ca146108ed578063c87b56dd146108f5575f80fd5b806395e79d6111610195578063a22cb46511610165578063a22cb46514610825578063a9cc2e3b14610838578063b2016bd4146108a2578063b67b730b146108b4575f80fd5b806395e79d611461076e578063960a8b9214610776578063a0ab910e14610795578063a217fddf1461081e575f80fd5b8063861b4cfe116101d0578063861b4cfe1461073857806391d148541461074b578063939c0a0c1461075e57806395d89b4114610766575f80fd5b806370f3c4b1146106fa57806375413fdd146107025780637f20a8c61461070a57806384c1999b14610725575f80fd5b80632a033873116102ec578063581bc9c911610281578063673835fd11610251578063673835fd146106a55780636cf1dbed146106ad5780636dbe4bb9146106c057806370a08231146106e7575f80fd5b8063581bc9c91461065c578063623d3a13146106825780636352211e1461068a57806363d36fa41461069d575f80fd5b80633cd9b53c116102bc5780633cd9b53c1461061b5780633dee1f44146106235780633edf0d4e1461063657806342842e0e14610649575f80fd5b80632a033873146105da5780632f2ff15d146105e257806336568abe146105f557806339d1fc8214610608575f80fd5b8063143d557c11610362578063248a9ca311610332578063248a9ca31461057a57806324b333921461058d578063256f3eb4146105b45780632630c12f146105c7575f80fd5b8063143d557c146104f65780631a0dde1c1461051357806320df43591461053257806323b872dd14610567575f80fd5b806306fdde031161039d57806306fdde03146104845780630723d57114610499578063081812fc146104ce578063095ea7b3146104e1575f80fd5b8062799a5e146103cd57806301ffc9a714610411578063032d227614610434578063067f4ddd14610467575b5f80fd5b6103f47f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020015b60405180910390f35b61042461041f3660046153cb565b610a31565b6040519015158152602001610408565b6104476104423660046153fa565b610a41565b604080519485526020850193909352918301526060820152608001610408565b61046f6113a1565b60405163ffffffff9091168152602001610408565b61048c6113af565b6040516104089190615466565b6104ac6104a7366004615478565b611450565b6040805182518152602080840151908201529181015190820152606001610408565b6103f46104dc3660046154a7565b611760565b6104f46104ef3660046154be565b611774565b005b6104fe611783565b60408051928352602083019190915201610408565b61051b611795565b60405165ffffffffffff9091168152602001610408565b6105597fbf233dd2aafeb4d50879c4aa5c81e96d92f6e6945c906a58f9f2d1c1631b4b2681565b604051908152602001610408565b6104f46105753660046154da565b61179e565b6105596105883660046154a7565b61182c565b61051b61059b3660046154a7565b60096020525f908152604090205465ffffffffffff1681565b6104f46105c23660046154a7565b61184c565b6001546103f4906001600160a01b031681565b61055961185f565b6104f46105f0366004615518565b611868565b6104f4610603366004615518565b611884565b6104f4610616366004615546565b6118bc565b6104246118cf565b6104f4610631366004615561565b6118df565b6104f46106443660046154a7565b6118f3565b6104f46106573660046154da565b611906565b6104fe61066a3660046154a7565b600a6020525f90815260409020805460019091015482565b6104fe611920565b6103f46106983660046154a7565b61192a565b6104fe611934565b61055961193e565b6104f46106bb366004615654565b6119d0565b6103f47f000000000000000000000000000000000000000000000000000000000000000081565b6105596106f5366004615546565b611ccc565b610424611d24565b6104fe611d31565b610712611d3b565b60405160019190910b8152602001610408565b6104f4610733366004615561565b611d44565b6105596107463660046154a7565b611d58565b610424610759366004615518565b611e2c565b6104fe611e62565b61048c611e6c565b610559611eaa565b6105596107843660046156f1565b60086020525f908152604090205481565b6107e36107a33660046154a7565b60066020525f9081526040902054600181900b9065ffffffffffff62010000820416906001600160601b03600160401b8204811691600160a01b90041684565b6040805160019590950b855265ffffffffffff90931660208501526001600160601b0391821692840192909252166060820152608001610408565b6105595f81565b6104f461083336600461571d565b611eb3565b60ca5461086d906001600160801b03811690600160801b81046001600160501b031690600160d01b900465ffffffffffff1683565b604080516001600160801b0390941684526001600160501b03909216602084015265ffffffffffff1690820152606001610408565b5f546103f4906001600160a01b031681565b6104f46108c2366004615561565b611ebe565b6104f46108d5366004615749565b611ed2565b6104f46108e8366004615765565b611f0e565b610559611f25565b61048c6109033660046154a7565b611f2e565b6104f46109163660046154a7565b611f9f565b61092e610929366004615561565b611fb2565b60405161040891908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b6104f461096f366004615518565b6122cb565b6105596109823660046154a7565b6122e7565b6103f47f000000000000000000000000000000000000000000000000000000000000000081565b6105596109bc3660046154a7565b60076020525f908152604090205481565b6104246109db3660046157e0565b6125ff565b6104fe61264b565b6104fe6109f63660046154a7565b612655565b61055961272b565b6104f4610a11366004615561565b612757565b6104ac610a243660046154a7565b61276b565b610559612a92565b5f610a3b82612ab7565b92915050565b5f808080337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031614610a8e57604051630a7c22bf60e11b815260040160405180910390fd5b86158015610a9a575085155b15610ab857604051633d38350560e01b815260040160405180910390fd5b8615801590610ae05750610acf633b9aca00615820565b87138015610ae05750633b9aca0087125b15610afe576040516347017a4d60e01b815260040160405180910390fd5b8515801590610b265750610b15633b9aca00615820565b86138015610b265750633b9aca0086125b15610b445760405163ba63dfbf60e01b815260040160405180910390fd5b5f86138015610bdc575060025460011680610bdc57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166349aa2e816040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bb6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bda919061583a565b155b15610bfa57604051636264b44f60e11b815260040160405180910390fd5b610c546040518061016001604052805f81526020015f65ffffffffffff1681526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b60015f9054906101000a90046001600160a01b03166001600160a01b031663a51ff4a26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ca4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cc89190615855565b610140820152610cd6612adb565b610100830152610120820152610cea612b03565b60e083015260c08201525f899003610d1257610d0586612cb5565b63ffffffff169850610e5e565b856001600160a01b0316610d258a61192a565b6001600160a01b031614158015610d4457505f881280610d4457505f87135b15610d62576040516315e005e960e01b815260040160405180910390fd5b5f610d6c8a612d01565b9050610d7781612e85565b805160010b825260208082015165ffffffffffff16908301526060808201516001600160601b0390811691840191909152604080830151909116908301525f891280610dc257505f88135b15610e5c575f610ddc83604001518460c001516001612fee565b90505f610df384606001518560e001516001613007565b90505f610dfe613018565b50610140860151909150610e12848361586c565b610e1c919061586c565b670de0b6b3a7640000610e2f818561586c565b610e39919061586c565b1115610e585760405163d374189360e01b815260040160405180910390fd5b5050505b505b5f80891315610ec857610e708961303b565b9050610e7c818a615883565b9850610e8e898360c001516001613007565b60808301819052604083018051610ea69083906158a2565b905250608082015161010083018051610ec09083906158a2565b905250610f9a565b5f891215610f9a57600160ff1b8903610f1257610eef82604001518360c001516001612fee565b610ef890615820565b98508160400151610f0890615820565b6080830152610f67565b610f29610f1e8a615820565b8360c001515f613007565b610f3290615820565b60808301819052604083015190610f4890615820565b1115610f6757604051631daef16360e01b815260040160405180910390fd5b608082015160408301805182019052610100830180519091019052610f8b8961303b565b9050610f97818a6158b5565b98505b5f881315610feb57610fb1888360e001515f612fee565b60a08301819052606083018051610fc99083906158a2565b90525060a082015161012083018051610fe39083906158a2565b9052506110a0565b5f8812156110a057600160ff1b88036110345761101182606001518360e001515f613007565b61101a90615820565b9750816060015161102a90615820565b60a083015261105a565b61104b61104089615820565b8360e001515f612fee565b61105490615820565b60a08301525b8160a0015161106890615820565b8260600181815161107991906158d4565b90525060a082015161108a90615820565b826101200181815161109c91906158d4565b9052505b5f6110b583604001518460c001516001612fee565b90505f6110cc84606001518560e001516001613007565b90505f806110d86130a5565b61014088015191935091506110ed858361586c565b6110f7919061586c565b670de0b6b3a764000061110a818661586c565b611114919061586c565b1115611133576040516309c89bf560e41b815260040160405180910390fd5b610140860151611143858461586c565b61114d919061586c565b670de0b6b3a7640000611160818661586c565b61116a919061586c565b10156111895760405163e91ee88760e01b815260040160405180910390fd5b505050506111a18260400151836060015160016130c8565b65ffffffffffff166020840152825260408201516001600160601b0310156111dc57604051631f21544b60e11b815260040160405180910390fd5b60608201516001600160601b03101561120857604051631f21544b60e11b815260040160405180910390fd5b6040518060800160405280835f015160010b8152602001836020015165ffffffffffff16815260200183604001516001600160601b0316815260200183606001516001600160601b031681525060065f8c81526020019081526020015f205f820151815f015f6101000a81548161ffff021916908360010b61ffff1602179055506020820151815f0160026101000a81548165ffffffffffff021916908365ffffffffffff1602179055506040820151815f0160086101000a8154816001600160601b0302191690836001600160601b031602179055506060820151815f0160146101000a8154816001600160601b0302191690836001600160601b031602179055509050506113228261012001518361010001516131ed565b7f87c6d2a0cd0c74f592aa5180672ba8d1f3646cb6e00d7622a7cbb4aa7aeb93b88a835f01518460400151856060015186610140015160405161138a95949392919094855260019390930b602085015260408401919091526060830152608082015260a00190565b60405180910390a198999798969795505050505050565b5f6113aa613214565b905090565b5f80516020615d3483398151915280546060919081906113ce906158e7565b80601f01602080910402602001604051908101604052809291908181526020018280546113fa906158e7565b80156114455780601f1061141c57610100808354040283529160200191611445565b820191905f5260205f20905b81548152906001019060200180831161142857829003601f168201915b505050505091505090565b61147160405180606001604052805f81526020015f81526020015f81525090565b337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316146114ba57604051630a7c22bf60e11b815260040160405180910390fd5b5f806114c4612b03565b915091505f60015f9054906101000a90046001600160a01b03166001600160a01b03166398d5fdca6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611519573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061153d919061591f565b50600188810b5f9081526009602090815260408083205465ffffffffffff16808452600a90925282209092015492945090925061158761157f83836080613222565b876001612fee565b90505f6115a161159984608080613222565b876001613007565b90505f806115ad613230565b915091505f6115ba613018565b509050876115c8868561586c565b6115d2919061586c565b670de0b6b3a76400006115e5818761586c565b6115ef919061586c565b101561160e57604051632a866e9760e21b815260040160405180910390fd5b87611619868361586c565b611623919061586c565b670de0b6b3a7640000611636818761586c565b611640919061586c565b1061165e5760405163056c59b760e51b815260040160405180910390fd5b61166b85858a8686613252565b60208c018190528c10156116815760208b018c90525b5f6116928c602001518b6001612fee565b905088670de0b6b3a76400008d602001516116ad919061586c565b6116b7919061595e565b808d52633b9aca00906116cb90859061586c565b6116d5919061595e565b60408d01528b516116e690876158d4565b8c604001511115611703578b516116fd90876158d4565b60408d01525b5f6117228d604001518e5f015161171a91906158a2565b8d6001613007565b90506117308f82848d6132f4565b5f8061173a612adb565b9150915061174c8483038483036131ed565b505050505050505050505050505092915050565b5f61176a82613555565b50610a3b8261358c565b61177f8282336135c5565b5050565b5f8061178d613230565b915091509091565b5f6113aa6135d2565b6001600160a01b0382166117cc57604051633250574960e11b81525f60048201526024015b60405180910390fd5b5f6117d88383336135e4565b9050836001600160a01b0316816001600160a01b031614611826576040516364283d7b60e01b81526001600160a01b03808616600483015260248201849052821660448201526064016117c3565b50505050565b5f9081525f80516020615d54833981519152602052604090206001015490565b5f611856816136e6565b61177f826136f3565b5f6113aa613764565b6118718261182c565b61187a816136e6565b6118268383613776565b6001600160a01b03811633146118ad5760405163334bd91960e11b815260040160405180910390fd5b6118b7828261381e565b505050565b5f6118c6816136e6565b61177f82613897565b5f6113aa600254600190811c1690565b5f6118e9816136e6565b6118b78383613901565b5f6118fd816136e6565b61177f8261397a565b6118b783838360405180602001604052805f815250611f0e565b5f8061178d6130a5565b5f610a3b82613555565b5f8061178d6139e2565b5f805f6119496139f5565b6040805160608101825260ca546001600160801b0381168252600160801b81046001600160501b03166020830152600160d01b900465ffffffffffff169181019190915291935091505f9061199d90613a17565b9150505f828211156119c1578260018303816119bb576119bb61594a565b046119c4565b60015b93909302949350505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f81158015611a155750825b90505f8267ffffffffffffffff166001148015611a315750303b155b905081158015611a3f575080155b15611a5d5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315611a8757845460ff60401b1916600160401b1785555b611a8f613b6d565b611a97613b6d565b611aa18989613b77565b611aa9613b6d565b611ab38787613b89565b611abb613bbd565b611ac3613bdb565b611acb613bed565b611ad55f8b613776565b50611aea620f424066b1a2bc2ec50000613901565b611af6620f42406136f3565b60405163386497fd60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f917f00000000000000000000000000000000000000000000000000000000000000009091169063386497fd90602401602060405180830381865afa158015611b7e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ba29190615855565b6040516335ea6a7560e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301529192505f917f000000000000000000000000000000000000000000000000000000000000000016906335ea6a75906024016101e060405180830381865afa158015611c2c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c5091906159f7565b9050611c7882633b9aca008360800151611c6a9190615b21565b6001600160801b0316613c36565b50508315611cc057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050505050565b5f5f80516020615d348339815191526001600160a01b038316611d04576040516322718ad960e21b81525f60048201526024016117c3565b6001600160a01b039092165f908152600390920160205250604090205490565b5f6113aa60025460011690565b5f8061178d612adb565b5f6113aa613cd9565b5f611d4e816136e6565b6118b78383613cf2565b5f805f611d6484612655565b915091505f60015f9054906101000a90046001600160a01b03166001600160a01b03166398d5fdca6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611db9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ddd919061591f565b50509050825f03611df257505f949350505050565b611dfc838261586c565b670de0b6b3a7640000611e0f818561586c565b611e19919061586c565b611e23919061595e565b95945050505050565b5f9182525f80516020615d54833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f8061178d6139f5565b7f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930180546060915f80516020615d34833981519152916113ce906158e7565b5f6113aa613d68565b61177f338383613d7a565b5f611ec8816136e6565b6118b78383613e29565b7fbf233dd2aafeb4d50879c4aa5c81e96d92f6e6945c906a58f9f2d1c1631b4b26611efc816136e6565b611f0583613ea3565b6118b782613ee8565b611f1984848461179e565b61182684848484613f2a565b5f6113aa614049565b6060611f3982613555565b505f611f4f60408051602081019091525f815290565b90505f815111611f6d5760405180602001604052805f815250611f98565b80611f778461405b565b604051602001611f88929190615b65565b6040516020818303038152906040525b9392505050565b5f611fa9816136e6565b61177f826140eb565b611fd960405180608001604052805f81526020015f81526020015f81526020015f81525090565b337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461202257604051630a7c22bf60e11b815260040160405180910390fd5b612080604051806101a001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6080810184905260a08101839052612096613018565b60e083015260c082015260015460408051634c6afee560e11b815290516001600160a01b03909216916398d5fdca916004808201926060929091908290030181865afa1580156120e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061210c919061591f565b506101008301525061211c612b03565b610140830152610120820152612130612adb565b6101608301526101808201525f612145613cd9565b905060015b6080830151156122a057806121795761216f612167600184615b79565b60089061413d565b9092509050612292565b61218e82846101200151856101400151614198565b6060870181905260408701919091526020860191909152908452670de0b6b3a7640000906121bd90829061586c565b6121c7919061586c565b8360c0015184610100015185604001516121e1919061586c565b6121eb919061586c565b111561220d57633b9aca008360600151101561220857505f61214a565b6122a0565b5f805f8061221b868861420f565b9350935093509350838860200181815161223591906158a2565b9052508751839089906122499083906158a2565b9052506040880180518391906122609083906158a2565b9052506060880180518291906122779083906158a2565b905250612288612167600188615b79565b9096509450505050505b618000600183900b0161214a575b6122b48361018001518461016001516131ed565b6122c283610140015161448f565b50505092915050565b6122d48261182c565b6122dd816136e6565b611826838361381e565b5f337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03161461233157604051630a7c22bf60e11b815260040160405180910390fd5b600254600190811c161561235857604051637e7f033f60e11b815260040160405180910390fd5b5f80612362612b03565b915091505f80612370612adb565b915091505f60015f9054906101000a90046001600160a01b03166001600160a01b03166376cde5646040518163ffffffff1660e01b8152600401602060405180830381865afa1580156123c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123e99190615855565b90505f6123f883876001612fee565b90505f61240785876001613007565b9050612413838361586c565b612425670de0b6b3a76400008361586c565b1061244357604051636fa8dc8960e01b815260040160405180910390fd5b50505f61244e613cd9565b905060015f61245e8a8884612fee565b90505b80156125e857816124845761247a612167600185615b79565b90935091506125da565b600183810b5f9081526009602090815260408083205465ffffffffffff16808452600a909252822090920154906124bd82608080613222565b90505f6124cc83826080613222565b9050876124db828e6001612fee565b6124e5919061586c565b670de0b6b3a76400006124fa848e6001613007565b612504919061586c565b1115612516575f955050505050612461565b505f633b9aca00612525613d68565b61252f908461586c565b612539919061595e565b9050848111156125465750835b5f88670de0b6b3a764000061255d848f6001613007565b612567919061586c565b612571919061595e565b90505f612580828f6001613007565b905061258e8982858d6132f4565b61259883886158d4565b9650818f6125a691906158a2565b9e506125b2818c6158d4565b9a506125be838d6158d4565b9b506125ce61216760018b615b79565b90995097505050505050505b618000600184900b01612461575b6125f286866131ed565b5050505050505050919050565b6001600160a01b039182165f9081527f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab00793056020908152604080832093909416825291909152205460ff1690565b5f8061178d613018565b5f8181526006602090815260409182902082516080810184529054600181900b825265ffffffffffff620100008204169282018390526001600160601b03600160401b82048116948301859052600160a01b909104166060820181905291156126f9575f806126cf836020015165ffffffffffff166144d2565b9250925050603c82866126e2919061586c565b901c9450603c6126f2828661586c565b901c935050505b5f806127036139e2565b9150915061271385826001612fee565b945061272184836001613007565b9350505050915091565b5f80612735612adb565b9150505f6127416139e2565b91505061275082826001612fee565b9250505090565b5f612761816136e6565b6118b7838361454f565b61278c60405180606001604052805f81526020015f81526020015f81525090565b337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316146127d557604051630a7c22bf60e11b815260040160405180910390fd5b61282d6040518061018001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6080810183905261283c613230565b60c083015260a082015260015460408051634c6afee560e11b815290516001600160a01b03909216916398d5fdca916004808201926060929091908290030181865afa15801561288e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128b2919061591f565b5060e0830152506128c1612b03565b6101208301526101008201526128d5612adb565b6101408301526101608201525f6128ea613018565b5090505f6128f6613cd9565b905060015b608084015115612a75578061292257612918612167600184615b79565b9092509050612a67565b61293782856101000151866101200151614198565b6060880181905260408801919091526020870191909152908552670de0b6b3a76400009061296690829061586c565b612970919061586c565b838560e001518660400151612985919061586c565b61298f919061586c565b1161299b57505f6128fb565b633b9aca00846060015110156129b257505f6128fb565b670de0b6b3a76400008085606001516129cb919061586c565b6129d5919061586c565b8460a001518560e0015186604001516129ee919061586c565b6129f8919061586c565b11612a75575f805f612a0a85886145c8565b9250925092508288602001818151612a2291906158a2565b905250875182908990612a369083906158a2565b905250604088018051829190612a4d9083906158a2565b905250612a5e612167600187615b79565b90955093505050505b618000600183900b016128fb575b612a898461016001518561014001516131ed565b50505050919050565b5f80612a9c612adb565b5090505f612aa86139e2565b50905061275082826001613007565b5f6001600160e01b03198216637965db0b60e01b1480610a3b5750610a3b82614704565b6005545f908190612aee81836080613222565b9250612afc81608080613222565b9150509091565b5f80612b0d6139e2565b6040805160608101825260ca546001600160801b0381168252600160801b81046001600160501b03166020830152600160d01b900465ffffffffffff16918101829052919450919250905f90612b6390426158d4565b90508015612caf575f80612b7684613a17565b915091507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166370d00a586040518163ffffffff1660e01b8152600401602060405180830381865afa158015612bd6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bfa919061583a565b15612ca2575f612c08612adb565b9150505f612c1882896001612fee565b90505f612c31670de0b6b3a76400006301e1338061586c565b86612c3c868561586c565b612c46919061586c565b612c50919061595e565b9050633b9aca00612c5f613764565b612c69908361586c565b612c73919061595e565b9050612c7f81836158d4565b612c89838b61586c565b612c93919061595e565b9850612c9e89614753565b5050505b612cac8282613c36565b50505b50509091565b5f612cbe613214565b9050612ccc81600101614796565b612cd95f428160286147b8565b63ffffffff82165f81815260076020526040902091909155612cfc9083906147cc565b919050565b604080516080810182525f808252602082018190529181018290526060810191909152505f8181526006602090815260409182902082516080810184529054600181900b825265ffffffffffff620100008204169282018390526001600160601b03600160401b8204811694830194909452600160a01b9004909216606083015215612cfc575f805f612d9f846020015165ffffffffffff1661482d565b925092509250603c8285604001516001600160601b0316612dc0919061586c565b6001600160601b03911c811660408601526060850151603c91612de59184911661586c565b6001600160601b03911c81166060860190815263ffffffff90941660208087019182525f88815260069091526040908190208751815493519289015197518516600160a01b026001600160a01b0398909516600160401b029790971667ffffffffffffffff65ffffffffffff93909316620100000267ffffffffffffffff1990941661ffff90981697909717929092171694909417179092555050919050565b806020015165ffffffffffff165f03612e9b5750565b60208082015165ffffffffffff165f908152600a909152604081206001015490612ec782608080613222565b60408401519091505f906001600160601b0316612ee684836080613222565b612ef091906158d4565b90505f84606001516001600160601b031683612f0c91906158d4565b9050612f1b84835f60806147b8565b9350612f2a84826080806147b8565b60208087015165ffffffffffff165f908152600a90915260409020600101819055935080158015612f5a57505f83115b15612fe75760208581015165ffffffffffff165f908152600a9091526040812054617fff60309190911c61ffff1690811161ffff1902179050612fc3600882600881901c5f90810b815260209290925260409091208054600160ff9093169290921b9091189055565b5f612fcc613cd9565b90508160010b8160010b03612fe457612fe4816148f6565b50505b5050505050565b5f612fff84600160601b8585614934565b949350505050565b5f612fff8484600160601b85614934565b6003545f90819061302c81605a603c613222565b9250612afc816096601e613222565b5f8082131561307b575f61304d61193e565b9050633b9aca008111156130625750633b9aca005b633b9aca00613071828561586c565b611f98919061595e565b633b9aca00613088614049565b61309184615820565b61309b919061586c565b610a3b919061595e565b6002545f9081906130b9816062603c613222565b9250612afc81609e603c613222565b5f8083156131e5578280156130e05750633b9aca0084125b156130fe5760405163ba63dfbf60e01b815260040160405180910390fd5b6131088585614969565b9150613113826149ce565b65ffffffffffff81165f908152600a60205260408120600101549192508661313d83836080613222565b61314791906158a2565b90505f8661315784608080613222565b61316191906158a2565b905061317083835f60806147b8565b925061317f83826080806147b8565b65ffffffffffff85165f908152600a6020526040902060010181905592508681036131c657600885811c5f90810b8152602091909152604090208054600160ff88161b1890555b6131ce613cd9565b60010b8513156131e1576131e1856149f5565b5050505b935093915050565b6005546131fd81845f60806147b8565b905061320c81836080806147b8565b600555505050565b6002545f906113aa90601260205b6001901b5f190191901c1690565b6003545f9081906132438183603c613222565b9250612afc81603c601e613222565b5f633b9aca0061326283826158a2565b61327485670de0b6b3a764000061586c565b61327e919061586c565b613288919061595e565b61329a670de0b6b3a76400008061586c565b6132a491906158d4565b866132af868661586c565b6132b9919061586c565b670de0b6b3a76400006132cc818961586c565b6132d6919061586c565b6132e091906158d4565b6132ea919061595e565b9695505050505050565b600184900b5f9081526009602052604090205465ffffffffffff1661331885614a10565b50600885811c5f90810b8152602091909152604090208054600160ff88161b18905565ffffffffffff81165f908152600a6020526040812060018101549054909161336583826080613222565b90505f61337484608080613222565b90505f61338189846158d4565b90505f61338e89846158d4565b90505f846133a06001603c1b8561586c565b6133aa919061595e565b90505f846133bc6001603c1b8561586c565b6133c6919061595e565b90506133d587836040806147b8565b96506133e58782608060406147b8565b9650600160ff1b831561341c575f6133fe86865f6130c8565b90925090506134188965ffffffffffff83165f60306147b8565b9850505b600160ff1b8103613494577f5fe96f4d1f13c468b9090d9e0bfa3b28cf26e4fe6439122f08ddbf605998e8a98e617fff1987878f604051613487959493929190600195860b81529390940b602084015260408301919091526060820152608081019190915260a00190565b60405180910390a16134fa565b7f5fe96f4d1f13c468b9090d9e0bfa3b28cf26e4fe6439122f08ddbf605998e8a98e8287878f6040516134f1959493929190600195860b81529390940b602084015260408301919091526060820152608081019190915260a00190565b60405180910390a15b5f613503613cd9565b90508e60010b8160010b14801561351d57508e60010b8214155b1561352b5761352b816148f6565b50505065ffffffffffff9097165f908152600a602052604090209490945550505050505050505050565b5f8061356083614aa3565b90506001600160a01b038116610a3b57604051637e27328960e01b8152600481018490526024016117c3565b5f9081527f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930460205260409020546001600160a01b031690565b6118b78383836001614adc565b6002545f906113aa9060326030613222565b5f5f80516020615d34833981519152816135fd85614aa3565b90506001600160a01b0384161561361957613619818587614bef565b6001600160a01b03811615613655576136345f865f80614adc565b6001600160a01b0381165f908152600383016020526040902080545f190190555b6001600160a01b03861615613685576001600160a01b0386165f9081526003830160205260409020805460010190555b5f85815260028301602052604080822080546001600160a01b0319166001600160a01b038a811691821790925591518893918516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a495945050505050565b6136f08133614c53565b50565b61370181633b9aca00614c8c565b60c9545f61371282605a601e613222565b90506137228284605a601e6147b8565b60c95560408051828152602081018590527fdaf49fa2ee916dacec50caa3c51a56add055165efaf1f17d25725fcd2c99193591015b60405180910390a1505050565b60c9545f906113aa9060786020613222565b5f5f80516020615d5483398151915261378f8484611e2c565b61380e575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556137c43390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a46001915050610a3b565b5f915050610a3b565b5092915050565b5f5f80516020615d548339815191526138378484611e2c565b1561380e575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a46001915050610a3b565b6138a081614cad565b600180546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527ff3920b145a63851522088bd18b14d6bb919fbd12ac87f12498d6001c727ba070910160405180910390a15050565b61390f82633b9aca00614c8c565b61392181670de0b6b3a7640000614c8c565b60c95461393181845f601e6147b8565b90506139418183601e603c6147b8565b60c95560408051848152602081018490527f8874dc26eed942ffa0cacd0a09a6a0e782d014442e67ed2c7d3bcf61b759f6379101613757565b6139888163ffffffff614c8c565b60c9545f6139998260786020613222565b90506139a98284607860206147b8565b60c95560408051828152602081018590527fe6bbe7a165b8fa6949fe8e2bb60416d7af3b8149e381b428196d08c2a166b6359101613757565b6004545f908190612aee81836080613222565b60c9545f908190613a088183601e613222565b9250612afc81601e603c613222565b805160405163386497fd60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301525f9283926001600160801b03909116917f0000000000000000000000000000000000000000000000000000000000000000169063386497fd90602401602060405180830381865afa158015613aad573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ad19190615855565b92505f846040015165ffffffffffff1642613aec91906158d4565b9050610708811015613b0d5784602001516001600160501b03169250613b66565b613b17818361586c565b670de0b6b3a7640000613b2a84876158d4565b613b38906301e1338061586c565b613b42919061586c565b613b4c919061595e565b9250825f03613b665784602001516001600160501b031692505b5050915091565b613b75614cd4565b565b613b7f614cd4565b61177f8282614d1d565b613b91614cd4565b613b9a82614cad565b5f80546001600160a01b0319166001600160a01b03841617905561177f81613897565b613bc5614cd4565b613bcf6001614d4d565b613b75617fff196149f5565b613be3614cd4565b613b756001614796565b613bf5614cd4565b613c02600160601b61448f565b613c0f600160601b614753565b613c296706f05b59d3b20000670be52ee321c36db6613cf2565b613b75630bebc2006140eb565b6040805160608101825260ca80546001600160801b0386168084526001600160501b038616602085018190524265ffffffffffff8116868801819052600160d01b026001600160d01b03600160801b939093026001600160d01b0319909516909317939093171617909155915190917f4bb06cac844a363088e8f86dfbc70a781d8369fdbd4caa71228facb72d50dfc99161375791868252602082015260400190565b60028054617fff911c61ffff1690811161ffff19021790565b613cfc8282614c8c565b613d0e81670de0b6b3a7640000614c8c565b600254613d1f81846062603c6147b8565b9050613d2f8183609e603c6147b8565b60025560408051848152602081018490527f9f4d9f603359ea7747a1caa931ec105693f4fa63d739ca60d729ca98a683bff09101613757565b6002545f906113aa9060da601e613222565b5f80516020615d348339815191526001600160a01b038316613dba57604051630b61174360e31b81526001600160a01b03841660048201526024016117c3565b6001600160a01b038481165f818152600584016020908152604080832094881680845294825291829020805460ff191687151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a350505050565b613e3b82670de0b6b3a7640000614c8c565b613e4981633b9aca00614c8c565b600354613e5a8184605a603c6147b8565b9050613e6a81836096601e6147b8565b60035560408051848152602081018490527f7adbf035b2e2ae03a957c0cd561744f4010902e1001c2d41086c06f54504b7169101613757565b60025460011916811760025560405181151581527f0c62bbdfbcbe8bf3480c55ec19a4923a65eb876e49568f084595873b64cf8386906020015b60405180910390a150565b60025460021916600182901b1760025560405181151581527fe92fbb024677220febae1048128887af04da8455f22497316b00bb175be6b3ed90602001613edd565b6001600160a01b0383163b1561182657604051630a85bd0160e11b81526001600160a01b0384169063150b7a0290613f6c903390889087908790600401615b9c565b6020604051808303815f875af1925050508015613fa6575060408051601f3d908101601f19168201909252613fa391810190615bce565b60015b61400d573d808015613fd3576040519150601f19603f3d011682016040523d82523d5f602084013e613fd8565b606091505b5080515f0361400557604051633250574960e11b81526001600160a01b03851660048201526024016117c3565b805181602001fd5b6001600160e01b03198116630a85bd0160e11b14612fe757604051633250574960e11b81526001600160a01b03851660048201526024016117c3565b60c9545f906113aa90605a601e613222565b60605f61406783614d66565b60010190505f8167ffffffffffffffff81111561408657614086615581565b6040519080825280601f01601f1916602001820160405280156140b0576020820181803683370190505b5090508181016020015b5f19016f181899199a1a9b1b9c1cb0b131b232b360811b600a86061a8153600a85049450846140ba57509392505050565b6140f981633b9aca00614c8c565b60025461410a908260da601e6147b8565b6002556040518181527fa81c6ce7b85dedd389acede97c4c68e7ccd76ae970023b8af6a32d3d5b75e8ae90602001613edd565b600881901c5f81810b8152602084905260408120549091600160ff851690811b80015f190192831680151593908461417a578260ff16870361418b565b61418381614e3d565b830360ff1687035b9550505050509250929050565b600183810b5f9081526009602090815260408083205465ffffffffffff16808452600a90925282209092015490918291829182916141d881846080613222565b95506141e681608080613222565b94506141f486896001612fee565b935061420285886001613007565b9250505093509350935093565b5f805f805f8560a00151866040015161422891906158a2565b905085606001519450856080015185111561424557856080015194505b61010086015161425d670de0b6b3a76400008761586c565b614267919061595e565b93505f80876060015187036142825787602001519150614296565b614293878961014001516001612fee565b91505b8583116142ea578295508760a001519350670de0b6b3a7640000886101000151846142c1919061586c565b6142cb919061595e565b96506142de878961014001516001612fee565b8851909250905061436b565b633b9aca008860e00151876142ff919061586c565b614309919061595e565b94505f61431687876158a2565b90508381111561432f57508261432c87826158d4565b95505b8860400151811061435557604089015161434990826158d4565b89519095509150614369565b614366818a61012001516001613007565b91505b505b838860a00181815161437d91906158d4565b9052508751811480156143935750876020015182105b1561442a575f6143b9838a602001516143ac91906158d4565b8a61014001516001613007565b9050886020015192508189610160018181516143d591906158d4565b905250610180890180518491906143ed9083906158d4565b905250610180890151614404600160601b8361586c565b61440e919061595e565b896101400181815161442091906158a2565b9052506144599050565b80886101600181815161443d91906158d4565b905250610180880180518391906144559083906158d4565b9052505b868860800181815161446b91906158d4565b915081815250506144838982848b61010001516132f4565b50505092959194509250565b60045461449f90825f60806147b8565b6004556040518181527f0eb47678af0fcacabbadc23b52144abfc1b9341bfb37b6ede42d22bb243defda90602001613edd565b5f6001603c1b805b5f848152600a6020526040812054906144f582826030613222565b9050603c61450583604080613222565b61450f908661586c565b901c9350603c6145228360806040613222565b61452c908561586c565b901c9250805f0361453e575050614547565b94506144da9050565b929390929150565b61456182670de0b6b3a7640000614c8c565b61456f81633b9aca00614c8c565b60035461457f81845f603c6147b8565b905061458f8183603c601e6147b8565b60035560408051848152602081018490527f15658fc22e6d738d694640c7ec144edc24a5217d8e1b1cb6a17973b1f1c928759101613757565b5f805f6145ec846040015185606001518660e001518760a001518860c00151613252565b9250828460800151101561460257836080015192505b5f614614848661012001516001612fee565b60e086015190915061462e670de0b6b3a76400008661586c565b614638919061595e565b9250633b9aca008560c001518461464f919061586c565b614659919061595e565b915082856040015161466b91906158d4565b8211156146855782856040015161468291906158d4565b91505b5f6146a061469384866158a2565b8761010001516001613007565b90506146b28782848960e001516132f4565b8086610140018181516146c591906158d4565b905250610160860180518391906146dd9083906158d4565b9052506080860180518691906146f49083906158d4565b9150818152505050509250925092565b5f6001600160e01b031982166380ac58cd60e01b148061473457506001600160e01b03198216635b5e139f60e01b145b80610a3b57506301ffc9a760e01b6001600160e01b0319831614610a3b565b60045461476390826080806147b8565b6004556040518181527fae4d80815d6017051882e2605756a6374b276db7e0552860fa6b7c320a20be0190602001613edd565b6002546147b29063ffffffff808416906012906020906147b816565b60025550565b6001901b5f1901811b1992909216911b1790565b6001600160a01b0382166147f557604051633250574960e11b81525f60048201526024016117c3565b5f61480183835f6135e4565b90506001600160a01b038116156118b7576040516339e3563760e11b81525f60048201526024016117c3565b5f818152600a6020526040812054819081908161484c82826030613222565b905061485a82604080613222565b93506148698260806040613222565b9250805f0361487a578594506148ed565b5f806148858361482d565b91985092509050603c614898838861586c565b901c9550603c6148a8828761586c565b901c94506148b984885f60306147b8565b93506148c884876040806147b8565b93506148d88486608060406147b8565b5f898152600a60205260409020819055935050505b50509193909250565b617fff19600182900b131561492b575f614914612167600184615b79565b90925090508015614925575061492b565b506148f6565b6136f0816149f5565b5f600182600181111561494957614949615be9565b1461495e57614959858585614f26565b611e23565b611e23858585614f53565b5f808361497a600160601b8561586c565b614984919061595e565b90505f61499082614f5f565b90935090508181146149c657826149a681615bfd565b935061271090506149b98261271f61586c565b6149c3919061595e565b91505b505092915050565b5f8181526009602052604081205465ffffffffffff1690819003612cfc57610a3b82614a10565b600280549082901b6203fffc166203fffc19909116176147b2565b5f614a196135d2565b9050614a2781600101614d4d565b600182900b5f908152600960205260408120805465ffffffffffff191665ffffffffffff841617905567ffff000000000000603084901b169050614a72816001603c1b6040806147b8565b9050614a86816001603c1b608060406147b8565b65ffffffffffff83165f908152600a602052604090205550919050565b5f9081527f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930260205260409020546001600160a01b031690565b5f80516020615d348339815191528180614afe57506001600160a01b03831615155b15614bbf575f614b0d85613555565b90506001600160a01b03841615801590614b395750836001600160a01b0316816001600160a01b031614155b8015614b4c5750614b4a81856125ff565b155b15614b755760405163a9fbf51f60e01b81526001600160a01b03851660048201526024016117c3565b8215614bbd5784866001600160a01b0316826001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45b505b5f93845260040160205250506040902080546001600160a01b0319166001600160a01b0392909216919091179055565b614bfa838383615352565b6118b7576001600160a01b038316614c2857604051637e27328960e01b8152600481018290526024016117c3565b60405163177e802f60e01b81526001600160a01b0383166004820152602481018290526044016117c3565b614c5d8282611e2c565b61177f5760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044016117c3565b8082111561177f57604051634df52d2560e11b815260040160405180910390fd5b6001600160a01b0381166136f05760405163a7f9319d60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16613b7557604051631afcd79f60e31b815260040160405180910390fd5b614d25614cd4565b5f80516020615d3483398151915280614d3e8482615c5f565b50600181016118268382615c5f565b6002546147b29065ffffffffffff8316603260306147b8565b5f8072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8310614da45772184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b830492506040015b6d04ee2d6d415b85acef81000000008310614dd0576d04ee2d6d415b85acef8100000000830492506020015b662386f26fc100008310614dee57662386f26fc10000830492506010015b6305f5e1008310614e06576305f5e100830492506008015b6127108310614e1a57612710830492506004015b60648310614e2c576064830492506002015b600a8310610a3b5760010192915050565b5f808211614e49575f80fd5b600160801b8210614e6757608091821c91614e649082615d1a565b90505b600160401b8210614e8557604091821c91614e829082615d1a565b90505b6401000000008210614ea457602091821c91614ea19082615d1a565b90505b620100008210614ec157601091821c91614ebe9082615d1a565b90505b6101008210614edd57600891821c91614eda9082615d1a565b90505b60108210614ef857600491821c91614ef59082615d1a565b90505b60048210614f1357600291821c91614f109082615d1a565b90505b60028210612cfc57610a3b600182615d1a565b5f81600181614f35868861586c565b614f3f91906158a2565b614f4991906158d4565b612fff919061595e565b5f81614f49848661586c565b5f80630235b88083107473d85bca016a2338b31715f8e13054c005f8b995d384111715614f8a575f80fd5b600160601b83105f81614fad5750600160601b6a52b7d2dcc80cd2e40000008502045b8115614fc457506714adf4b7320334b9607a1b8490045b6f037af932b2affa9738cc6c38ca527831811061500557614000841793506f037af932b2affa9738cc6c38ca5278316a52b7d2dcc80cd2e400000082020490505b6d010f7a088a76f267264caa114f0a811061504257612000841793506d010f7a088a76f267264caa114f0a6a52b7d2dcc80cd2e400000082020490505b6b95da74f87f839fc2e0dc5bd9811061507b57611000841793506b95da74f87f839fc2e0dc5bd96a52b7d2dcc80cd2e400000082020490505b6b06f55dedafd8491caed5a1b881106150b457610800841793506b06f55dedafd8491caed5a1b86a52b7d2dcc80cd2e400000082020490505b6b017fdd10ee11e624491b4cc181106150ed57610400841793506b017fdd10ee11e624491b4cc16a52b7d2dcc80cd2e400000082020490505b6ab23131bf0c30217b0a2c69811061512457610200841793506ab23131bf0c30217b0a2c696a52b7d2dcc80cd2e400000082020490505b6a79683edcb9280d797aded7811061515b57610100841793506a79683edcb9280d797aded76a52b7d2dcc80cd2e400000082020490505b6a64366e2f9919f0d9b0dc908110615191576080841793506a64366e2f9919f0d9b0dc906a52b7d2dcc80cd2e400000082020490505b6a5b0bcda5a78850646b0a8181106151c7576040841793506a5b0bcda5a78850646b0a816a52b7d2dcc80cd2e400000082020490505b6a56c840f992c70f959ae81081106151fd576020841793506a56c840f992c70f959ae8106a52b7d2dcc80cd2e400000082020490505b6a54b9cd178695194f9be0a08110615233576010841793506a54b9cd178695194f9be0a06a52b7d2dcc80cd2e400000082020490505b6a53b7458aff204b5e65d6818110615269576008841793506a53b7458aff204b5e65d6816a52b7d2dcc80cd2e400000082020490505b6a53372a2f38c240d689e400811061529f576004841793506a53372a2f38c240d689e4006a52b7d2dcc80cd2e400000082020490505b6a52f76617a04499e664000081106152d5576002841793506a52f76617a04499e66400006a52b7d2dcc80cd2e400000082020490505b6a52d79660f3dec355c00000811061530b576001841793506a52d79660f3dec355c000006a52b7d2dcc80cd2e400000082020490505b8161532357806a52b7d2dcc80cd2e400000086020492505b811561533f579219926a52d79660f3dec355c000008582020492505b50508281111561534d575f80fd5b915091565b5f6001600160a01b03831615801590612fff5750826001600160a01b0316846001600160a01b0316148061538b575061538b84846125ff565b80612fff5750826001600160a01b03166153a48361358c565b6001600160a01b031614949350505050565b6001600160e01b0319811681146136f0575f80fd5b5f602082840312156153db575f80fd5b8135611f98816153b6565b6001600160a01b03811681146136f0575f80fd5b5f805f806080858703121561540d575f80fd5b843593506020850135925060408501359150606085013561542d816153e6565b939692955090935050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611f986020830184615438565b5f8060408385031215615489575f80fd5b82358060010b8114615499575f80fd5b946020939093013593505050565b5f602082840312156154b7575f80fd5b5035919050565b5f80604083850312156154cf575f80fd5b8235615499816153e6565b5f805f606084860312156154ec575f80fd5b83356154f7816153e6565b92506020840135615507816153e6565b929592945050506040919091013590565b5f8060408385031215615529575f80fd5b82359150602083013561553b816153e6565b809150509250929050565b5f60208284031215615556575f80fd5b8135611f98816153e6565b5f8060408385031215615572575f80fd5b50508035926020909101359150565b634e487b7160e01b5f52604160045260245ffd5b6040516101e0810167ffffffffffffffff811182821017156155b9576155b9615581565b60405290565b5f8067ffffffffffffffff8411156155d9576155d9615581565b50604051601f19601f85018116603f0116810181811067ffffffffffffffff8211171561560857615608615581565b60405283815290508082840185101561561f575f80fd5b838360208301375f60208583010152509392505050565b5f82601f830112615645575f80fd5b611f98838335602085016155bf565b5f805f805f60a08688031215615668575f80fd5b8535615673816153e6565b9450602086013567ffffffffffffffff81111561568e575f80fd5b61569a88828901615636565b945050604086013567ffffffffffffffff8111156156b6575f80fd5b6156c288828901615636565b93505060608601356156d3816153e6565b915060808601356156e3816153e6565b809150509295509295909350565b5f60208284031215615701575f80fd5b8135805f0b8114611f98575f80fd5b80151581146136f0575f80fd5b5f806040838503121561572e575f80fd5b8235615739816153e6565b9150602083013561553b81615710565b5f806040838503121561575a575f80fd5b823561573981615710565b5f805f8060808587031215615778575f80fd5b8435615783816153e6565b93506020850135615793816153e6565b925060408501359150606085013567ffffffffffffffff8111156157b5575f80fd5b8501601f810187136157c5575f80fd5b6157d4878235602084016155bf565b91505092959194509250565b5f80604083850312156157f1575f80fd5b82356157fc816153e6565b9150602083013561553b816153e6565b634e487b7160e01b5f52601160045260245ffd5b5f600160ff1b82016158345761583461580c565b505f0390565b5f6020828403121561584a575f80fd5b8151611f9881615710565b5f60208284031215615865575f80fd5b5051919050565b8082028115828204841417610a3b57610a3b61580c565b8181035f8312801583831316838312821617156138175761381761580c565b80820180821115610a3b57610a3b61580c565b8082018281125f8312801582168215821617156149c6576149c661580c565b81810381811115610a3b57610a3b61580c565b600181811c908216806158fb57607f821691505b60208210810361591957634e487b7160e01b5f52602260045260245ffd5b50919050565b5f805f60608486031215615931575f80fd5b5050815160208301516040909301519094929350919050565b634e487b7160e01b5f52601260045260245ffd5b5f8261596c5761596c61594a565b500490565b5f60208284031215615981575f80fd5b6040516020810167ffffffffffffffff811182821017156159a4576159a4615581565b6040529151825250919050565b80516001600160801b0381168114612cfc575f80fd5b805164ffffffffff81168114612cfc575f80fd5b805161ffff81168114612cfc575f80fd5b8051612cfc816153e6565b5f6101e0828403128015615a09575f80fd5b50615a12615595565b615a1c8484615971565b8152615a2a602084016159b1565b6020820152615a3b604084016159b1565b6040820152615a4c606084016159b1565b6060820152615a5d608084016159b1565b6080820152615a6e60a084016159b1565b60a0820152615a7f60c084016159c7565b60c0820152615a9060e084016159db565b60e0820152615aa261010084016159ec565b610100820152615ab561012084016159ec565b610120820152615ac861014084016159ec565b610140820152615adb61016084016159ec565b610160820152615aee61018084016159b1565b610180820152615b016101a084016159b1565b6101a0820152615b146101c084016159b1565b6101c08201529392505050565b5f6001600160801b03831680615b3957615b3961594a565b806001600160801b0384160491505092915050565b5f81518060208401855e5f93019283525090919050565b5f612fff615b738386615b4e565b84615b4e565b600182810b9082900b03617fff198112617fff82131715610a3b57610a3b61580c565b6001600160a01b03858116825284166020820152604081018390526080606082018190525f906132ea90830184615438565b5f60208284031215615bde575f80fd5b8151611f98816153b6565b634e487b7160e01b5f52602160045260245ffd5b5f6001600160ff1b018201615c1457615c1461580c565b5060010190565b601f8211156118b757805f5260205f20601f840160051c81016020851015615c405750805b601f840160051c820191505b81811015612fe7575f8155600101615c4c565b815167ffffffffffffffff811115615c7957615c79615581565b615c8d81615c8784546158e7565b84615c1b565b6020601f821160018114615cbf575f8315615ca85750848201515b5f19600385901b1c1916600184901b178455612fe7565b5f84815260208120601f198516915b82811015615cee5787850151825560209485019460019092019101615cce565b5084821015615d0b57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b60ff8181168382160190811115610a3b57610a3b61580c56fe80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930002dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a264697066735822122026359106180a43d56cef53de9f6ae9a7c76abb882ce90514c3424b046875b4d364736f6c634300081a0033000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd2400000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106103c9575f3560e01c806370f3c4b111610200578063b71348d11161011f578063dc4c90d3116100b4578063eb02c30111610084578063eb02c301146109e8578063ee65a03c146109fb578063efc5824014610a03578063f499301814610a16578063f9d45fd214610a29575f80fd5b8063dc4c90d314610987578063df9cbd3a146109ae578063e985e9c5146109cd578063e9a0e8fa146109e0575f80fd5b8063d032c4e5116100ef578063d032c4e514610908578063d296d1f11461091b578063d547741f14610961578063db006a7514610974575f80fd5b8063b71348d1146108c7578063b88d4fde146108da578063c64dc8ca146108ed578063c87b56dd146108f5575f80fd5b806395e79d6111610195578063a22cb46511610165578063a22cb46514610825578063a9cc2e3b14610838578063b2016bd4146108a2578063b67b730b146108b4575f80fd5b806395e79d611461076e578063960a8b9214610776578063a0ab910e14610795578063a217fddf1461081e575f80fd5b8063861b4cfe116101d0578063861b4cfe1461073857806391d148541461074b578063939c0a0c1461075e57806395d89b4114610766575f80fd5b806370f3c4b1146106fa57806375413fdd146107025780637f20a8c61461070a57806384c1999b14610725575f80fd5b80632a033873116102ec578063581bc9c911610281578063673835fd11610251578063673835fd146106a55780636cf1dbed146106ad5780636dbe4bb9146106c057806370a08231146106e7575f80fd5b8063581bc9c91461065c578063623d3a13146106825780636352211e1461068a57806363d36fa41461069d575f80fd5b80633cd9b53c116102bc5780633cd9b53c1461061b5780633dee1f44146106235780633edf0d4e1461063657806342842e0e14610649575f80fd5b80632a033873146105da5780632f2ff15d146105e257806336568abe146105f557806339d1fc8214610608575f80fd5b8063143d557c11610362578063248a9ca311610332578063248a9ca31461057a57806324b333921461058d578063256f3eb4146105b45780632630c12f146105c7575f80fd5b8063143d557c146104f65780631a0dde1c1461051357806320df43591461053257806323b872dd14610567575f80fd5b806306fdde031161039d57806306fdde03146104845780630723d57114610499578063081812fc146104ce578063095ea7b3146104e1575f80fd5b8062799a5e146103cd57806301ffc9a714610411578063032d227614610434578063067f4ddd14610467575b5f80fd5b6103f47f00000000000000000000000050562fe7e870420f5aae480b7f94eb4ace2fcd7081565b6040516001600160a01b0390911681526020015b60405180910390f35b61042461041f3660046153cb565b610a31565b6040519015158152602001610408565b6104476104423660046153fa565b610a41565b604080519485526020850193909352918301526060820152608001610408565b61046f6113a1565b60405163ffffffff9091168152602001610408565b61048c6113af565b6040516104089190615466565b6104ac6104a7366004615478565b611450565b6040805182518152602080840151908201529181015190820152606001610408565b6103f46104dc3660046154a7565b611760565b6104f46104ef3660046154be565b611774565b005b6104fe611783565b60408051928352602083019190915201610408565b61051b611795565b60405165ffffffffffff9091168152602001610408565b6105597fbf233dd2aafeb4d50879c4aa5c81e96d92f6e6945c906a58f9f2d1c1631b4b2681565b604051908152602001610408565b6104f46105753660046154da565b61179e565b6105596105883660046154a7565b61182c565b61051b61059b3660046154a7565b60096020525f908152604090205465ffffffffffff1681565b6104f46105c23660046154a7565b61184c565b6001546103f4906001600160a01b031681565b61055961185f565b6104f46105f0366004615518565b611868565b6104f4610603366004615518565b611884565b6104f4610616366004615546565b6118bc565b6104246118cf565b6104f4610631366004615561565b6118df565b6104f46106443660046154a7565b6118f3565b6104f46106573660046154da565b611906565b6104fe61066a3660046154a7565b600a6020525f90815260409020805460019091015482565b6104fe611920565b6103f46106983660046154a7565b61192a565b6104fe611934565b61055961193e565b6104f46106bb366004615654565b6119d0565b6103f47f000000000000000000000000085780639cc2cacd35e474e71f4d000e2405d8f681565b6105596106f5366004615546565b611ccc565b610424611d24565b6104fe611d31565b610712611d3b565b60405160019190910b8152602001610408565b6104f4610733366004615561565b611d44565b6105596107463660046154a7565b611d58565b610424610759366004615518565b611e2c565b6104fe611e62565b61048c611e6c565b610559611eaa565b6105596107843660046156f1565b60086020525f908152604090205481565b6107e36107a33660046154a7565b60066020525f9081526040902054600181900b9065ffffffffffff62010000820416906001600160601b03600160401b8204811691600160a01b90041684565b6040805160019590950b855265ffffffffffff90931660208501526001600160601b0391821692840192909252166060820152608001610408565b6105595f81565b6104f461083336600461571d565b611eb3565b60ca5461086d906001600160801b03811690600160801b81046001600160501b031690600160d01b900465ffffffffffff1683565b604080516001600160801b0390941684526001600160501b03909216602084015265ffffffffffff1690820152606001610408565b5f546103f4906001600160a01b031681565b6104f46108c2366004615561565b611ebe565b6104f46108d5366004615749565b611ed2565b6104f46108e8366004615765565b611f0e565b610559611f25565b61048c6109033660046154a7565b611f2e565b6104f46109163660046154a7565b611f9f565b61092e610929366004615561565b611fb2565b60405161040891908151815260208083015190820152604080830151908201526060918201519181019190915260800190565b6104f461096f366004615518565b6122cb565b6105596109823660046154a7565b6122e7565b6103f47f000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd2481565b6105596109bc3660046154a7565b60076020525f908152604090205481565b6104246109db3660046157e0565b6125ff565b6104fe61264b565b6104fe6109f63660046154a7565b612655565b61055961272b565b6104f4610a11366004615561565b612757565b6104ac610a243660046154a7565b61276b565b610559612a92565b5f610a3b82612ab7565b92915050565b5f808080337f000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd246001600160a01b031614610a8e57604051630a7c22bf60e11b815260040160405180910390fd5b86158015610a9a575085155b15610ab857604051633d38350560e01b815260040160405180910390fd5b8615801590610ae05750610acf633b9aca00615820565b87138015610ae05750633b9aca0087125b15610afe576040516347017a4d60e01b815260040160405180910390fd5b8515801590610b265750610b15633b9aca00615820565b86138015610b265750633b9aca0086125b15610b445760405163ba63dfbf60e01b815260040160405180910390fd5b5f86138015610bdc575060025460011680610bdc57507f00000000000000000000000050562fe7e870420f5aae480b7f94eb4ace2fcd706001600160a01b03166349aa2e816040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bb6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bda919061583a565b155b15610bfa57604051636264b44f60e11b815260040160405180910390fd5b610c546040518061016001604052805f81526020015f65ffffffffffff1681526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b60015f9054906101000a90046001600160a01b03166001600160a01b031663a51ff4a26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610ca4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cc89190615855565b610140820152610cd6612adb565b610100830152610120820152610cea612b03565b60e083015260c08201525f899003610d1257610d0586612cb5565b63ffffffff169850610e5e565b856001600160a01b0316610d258a61192a565b6001600160a01b031614158015610d4457505f881280610d4457505f87135b15610d62576040516315e005e960e01b815260040160405180910390fd5b5f610d6c8a612d01565b9050610d7781612e85565b805160010b825260208082015165ffffffffffff16908301526060808201516001600160601b0390811691840191909152604080830151909116908301525f891280610dc257505f88135b15610e5c575f610ddc83604001518460c001516001612fee565b90505f610df384606001518560e001516001613007565b90505f610dfe613018565b50610140860151909150610e12848361586c565b610e1c919061586c565b670de0b6b3a7640000610e2f818561586c565b610e39919061586c565b1115610e585760405163d374189360e01b815260040160405180910390fd5b5050505b505b5f80891315610ec857610e708961303b565b9050610e7c818a615883565b9850610e8e898360c001516001613007565b60808301819052604083018051610ea69083906158a2565b905250608082015161010083018051610ec09083906158a2565b905250610f9a565b5f891215610f9a57600160ff1b8903610f1257610eef82604001518360c001516001612fee565b610ef890615820565b98508160400151610f0890615820565b6080830152610f67565b610f29610f1e8a615820565b8360c001515f613007565b610f3290615820565b60808301819052604083015190610f4890615820565b1115610f6757604051631daef16360e01b815260040160405180910390fd5b608082015160408301805182019052610100830180519091019052610f8b8961303b565b9050610f97818a6158b5565b98505b5f881315610feb57610fb1888360e001515f612fee565b60a08301819052606083018051610fc99083906158a2565b90525060a082015161012083018051610fe39083906158a2565b9052506110a0565b5f8812156110a057600160ff1b88036110345761101182606001518360e001515f613007565b61101a90615820565b9750816060015161102a90615820565b60a083015261105a565b61104b61104089615820565b8360e001515f612fee565b61105490615820565b60a08301525b8160a0015161106890615820565b8260600181815161107991906158d4565b90525060a082015161108a90615820565b826101200181815161109c91906158d4565b9052505b5f6110b583604001518460c001516001612fee565b90505f6110cc84606001518560e001516001613007565b90505f806110d86130a5565b61014088015191935091506110ed858361586c565b6110f7919061586c565b670de0b6b3a764000061110a818661586c565b611114919061586c565b1115611133576040516309c89bf560e41b815260040160405180910390fd5b610140860151611143858461586c565b61114d919061586c565b670de0b6b3a7640000611160818661586c565b61116a919061586c565b10156111895760405163e91ee88760e01b815260040160405180910390fd5b505050506111a18260400151836060015160016130c8565b65ffffffffffff166020840152825260408201516001600160601b0310156111dc57604051631f21544b60e11b815260040160405180910390fd5b60608201516001600160601b03101561120857604051631f21544b60e11b815260040160405180910390fd5b6040518060800160405280835f015160010b8152602001836020015165ffffffffffff16815260200183604001516001600160601b0316815260200183606001516001600160601b031681525060065f8c81526020019081526020015f205f820151815f015f6101000a81548161ffff021916908360010b61ffff1602179055506020820151815f0160026101000a81548165ffffffffffff021916908365ffffffffffff1602179055506040820151815f0160086101000a8154816001600160601b0302191690836001600160601b031602179055506060820151815f0160146101000a8154816001600160601b0302191690836001600160601b031602179055509050506113228261012001518361010001516131ed565b7f87c6d2a0cd0c74f592aa5180672ba8d1f3646cb6e00d7622a7cbb4aa7aeb93b88a835f01518460400151856060015186610140015160405161138a95949392919094855260019390930b602085015260408401919091526060830152608082015260a00190565b60405180910390a198999798969795505050505050565b5f6113aa613214565b905090565b5f80516020615d3483398151915280546060919081906113ce906158e7565b80601f01602080910402602001604051908101604052809291908181526020018280546113fa906158e7565b80156114455780601f1061141c57610100808354040283529160200191611445565b820191905f5260205f20905b81548152906001019060200180831161142857829003601f168201915b505050505091505090565b61147160405180606001604052805f81526020015f81526020015f81525090565b337f000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd246001600160a01b0316146114ba57604051630a7c22bf60e11b815260040160405180910390fd5b5f806114c4612b03565b915091505f60015f9054906101000a90046001600160a01b03166001600160a01b03166398d5fdca6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611519573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061153d919061591f565b50600188810b5f9081526009602090815260408083205465ffffffffffff16808452600a90925282209092015492945090925061158761157f83836080613222565b876001612fee565b90505f6115a161159984608080613222565b876001613007565b90505f806115ad613230565b915091505f6115ba613018565b509050876115c8868561586c565b6115d2919061586c565b670de0b6b3a76400006115e5818761586c565b6115ef919061586c565b101561160e57604051632a866e9760e21b815260040160405180910390fd5b87611619868361586c565b611623919061586c565b670de0b6b3a7640000611636818761586c565b611640919061586c565b1061165e5760405163056c59b760e51b815260040160405180910390fd5b61166b85858a8686613252565b60208c018190528c10156116815760208b018c90525b5f6116928c602001518b6001612fee565b905088670de0b6b3a76400008d602001516116ad919061586c565b6116b7919061595e565b808d52633b9aca00906116cb90859061586c565b6116d5919061595e565b60408d01528b516116e690876158d4565b8c604001511115611703578b516116fd90876158d4565b60408d01525b5f6117228d604001518e5f015161171a91906158a2565b8d6001613007565b90506117308f82848d6132f4565b5f8061173a612adb565b9150915061174c8483038483036131ed565b505050505050505050505050505092915050565b5f61176a82613555565b50610a3b8261358c565b61177f8282336135c5565b5050565b5f8061178d613230565b915091509091565b5f6113aa6135d2565b6001600160a01b0382166117cc57604051633250574960e11b81525f60048201526024015b60405180910390fd5b5f6117d88383336135e4565b9050836001600160a01b0316816001600160a01b031614611826576040516364283d7b60e01b81526001600160a01b03808616600483015260248201849052821660448201526064016117c3565b50505050565b5f9081525f80516020615d54833981519152602052604090206001015490565b5f611856816136e6565b61177f826136f3565b5f6113aa613764565b6118718261182c565b61187a816136e6565b6118268383613776565b6001600160a01b03811633146118ad5760405163334bd91960e11b815260040160405180910390fd5b6118b7828261381e565b505050565b5f6118c6816136e6565b61177f82613897565b5f6113aa600254600190811c1690565b5f6118e9816136e6565b6118b78383613901565b5f6118fd816136e6565b61177f8261397a565b6118b783838360405180602001604052805f815250611f0e565b5f8061178d6130a5565b5f610a3b82613555565b5f8061178d6139e2565b5f805f6119496139f5565b6040805160608101825260ca546001600160801b0381168252600160801b81046001600160501b03166020830152600160d01b900465ffffffffffff169181019190915291935091505f9061199d90613a17565b9150505f828211156119c1578260018303816119bb576119bb61594a565b046119c4565b60015b93909302949350505050565b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a008054600160401b810460ff16159067ffffffffffffffff165f81158015611a155750825b90505f8267ffffffffffffffff166001148015611a315750303b155b905081158015611a3f575080155b15611a5d5760405163f92ee8a960e01b815260040160405180910390fd5b845467ffffffffffffffff191660011785558315611a8757845460ff60401b1916600160401b1785555b611a8f613b6d565b611a97613b6d565b611aa18989613b77565b611aa9613b6d565b611ab38787613b89565b611abb613bbd565b611ac3613bdb565b611acb613bed565b611ad55f8b613776565b50611aea620f424066b1a2bc2ec50000613901565b611af6620f42406136f3565b60405163386497fd60e01b81526001600160a01b037f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48811660048301525f917f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e29091169063386497fd90602401602060405180830381865afa158015611b7e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ba29190615855565b6040516335ea6a7560e01b81526001600160a01b037f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48811660048301529192505f917f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e216906335ea6a75906024016101e060405180830381865afa158015611c2c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611c5091906159f7565b9050611c7882633b9aca008360800151611c6a9190615b21565b6001600160801b0316613c36565b50508315611cc057845460ff60401b19168555604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29060200160405180910390a15b50505050505050505050565b5f5f80516020615d348339815191526001600160a01b038316611d04576040516322718ad960e21b81525f60048201526024016117c3565b6001600160a01b039092165f908152600390920160205250604090205490565b5f6113aa60025460011690565b5f8061178d612adb565b5f6113aa613cd9565b5f611d4e816136e6565b6118b78383613cf2565b5f805f611d6484612655565b915091505f60015f9054906101000a90046001600160a01b03166001600160a01b03166398d5fdca6040518163ffffffff1660e01b8152600401606060405180830381865afa158015611db9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611ddd919061591f565b50509050825f03611df257505f949350505050565b611dfc838261586c565b670de0b6b3a7640000611e0f818561586c565b611e19919061586c565b611e23919061595e565b95945050505050565b5f9182525f80516020615d54833981519152602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f8061178d6139f5565b7f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930180546060915f80516020615d34833981519152916113ce906158e7565b5f6113aa613d68565b61177f338383613d7a565b5f611ec8816136e6565b6118b78383613e29565b7fbf233dd2aafeb4d50879c4aa5c81e96d92f6e6945c906a58f9f2d1c1631b4b26611efc816136e6565b611f0583613ea3565b6118b782613ee8565b611f1984848461179e565b61182684848484613f2a565b5f6113aa614049565b6060611f3982613555565b505f611f4f60408051602081019091525f815290565b90505f815111611f6d5760405180602001604052805f815250611f98565b80611f778461405b565b604051602001611f88929190615b65565b6040516020818303038152906040525b9392505050565b5f611fa9816136e6565b61177f826140eb565b611fd960405180608001604052805f81526020015f81526020015f81526020015f81525090565b337f000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd246001600160a01b03161461202257604051630a7c22bf60e11b815260040160405180910390fd5b612080604051806101a001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6080810184905260a08101839052612096613018565b60e083015260c082015260015460408051634c6afee560e11b815290516001600160a01b03909216916398d5fdca916004808201926060929091908290030181865afa1580156120e8573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061210c919061591f565b506101008301525061211c612b03565b610140830152610120820152612130612adb565b6101608301526101808201525f612145613cd9565b905060015b6080830151156122a057806121795761216f612167600184615b79565b60089061413d565b9092509050612292565b61218e82846101200151856101400151614198565b6060870181905260408701919091526020860191909152908452670de0b6b3a7640000906121bd90829061586c565b6121c7919061586c565b8360c0015184610100015185604001516121e1919061586c565b6121eb919061586c565b111561220d57633b9aca008360600151101561220857505f61214a565b6122a0565b5f805f8061221b868861420f565b9350935093509350838860200181815161223591906158a2565b9052508751839089906122499083906158a2565b9052506040880180518391906122609083906158a2565b9052506060880180518291906122779083906158a2565b905250612288612167600188615b79565b9096509450505050505b618000600183900b0161214a575b6122b48361018001518461016001516131ed565b6122c283610140015161448f565b50505092915050565b6122d48261182c565b6122dd816136e6565b611826838361381e565b5f337f000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd246001600160a01b03161461233157604051630a7c22bf60e11b815260040160405180910390fd5b600254600190811c161561235857604051637e7f033f60e11b815260040160405180910390fd5b5f80612362612b03565b915091505f80612370612adb565b915091505f60015f9054906101000a90046001600160a01b03166001600160a01b03166376cde5646040518163ffffffff1660e01b8152600401602060405180830381865afa1580156123c5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123e99190615855565b90505f6123f883876001612fee565b90505f61240785876001613007565b9050612413838361586c565b612425670de0b6b3a76400008361586c565b1061244357604051636fa8dc8960e01b815260040160405180910390fd5b50505f61244e613cd9565b905060015f61245e8a8884612fee565b90505b80156125e857816124845761247a612167600185615b79565b90935091506125da565b600183810b5f9081526009602090815260408083205465ffffffffffff16808452600a909252822090920154906124bd82608080613222565b90505f6124cc83826080613222565b9050876124db828e6001612fee565b6124e5919061586c565b670de0b6b3a76400006124fa848e6001613007565b612504919061586c565b1115612516575f955050505050612461565b505f633b9aca00612525613d68565b61252f908461586c565b612539919061595e565b9050848111156125465750835b5f88670de0b6b3a764000061255d848f6001613007565b612567919061586c565b612571919061595e565b90505f612580828f6001613007565b905061258e8982858d6132f4565b61259883886158d4565b9650818f6125a691906158a2565b9e506125b2818c6158d4565b9a506125be838d6158d4565b9b506125ce61216760018b615b79565b90995097505050505050505b618000600184900b01612461575b6125f286866131ed565b5050505050505050919050565b6001600160a01b039182165f9081527f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab00793056020908152604080832093909416825291909152205460ff1690565b5f8061178d613018565b5f8181526006602090815260409182902082516080810184529054600181900b825265ffffffffffff620100008204169282018390526001600160601b03600160401b82048116948301859052600160a01b909104166060820181905291156126f9575f806126cf836020015165ffffffffffff166144d2565b9250925050603c82866126e2919061586c565b901c9450603c6126f2828661586c565b901c935050505b5f806127036139e2565b9150915061271385826001612fee565b945061272184836001613007565b9350505050915091565b5f80612735612adb565b9150505f6127416139e2565b91505061275082826001612fee565b9250505090565b5f612761816136e6565b6118b7838361454f565b61278c60405180606001604052805f81526020015f81526020015f81525090565b337f000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd246001600160a01b0316146127d557604051630a7c22bf60e11b815260040160405180910390fd5b61282d6040518061018001604052805f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b6080810183905261283c613230565b60c083015260a082015260015460408051634c6afee560e11b815290516001600160a01b03909216916398d5fdca916004808201926060929091908290030181865afa15801561288e573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906128b2919061591f565b5060e0830152506128c1612b03565b6101208301526101008201526128d5612adb565b6101408301526101608201525f6128ea613018565b5090505f6128f6613cd9565b905060015b608084015115612a75578061292257612918612167600184615b79565b9092509050612a67565b61293782856101000151866101200151614198565b6060880181905260408801919091526020870191909152908552670de0b6b3a76400009061296690829061586c565b612970919061586c565b838560e001518660400151612985919061586c565b61298f919061586c565b1161299b57505f6128fb565b633b9aca00846060015110156129b257505f6128fb565b670de0b6b3a76400008085606001516129cb919061586c565b6129d5919061586c565b8460a001518560e0015186604001516129ee919061586c565b6129f8919061586c565b11612a75575f805f612a0a85886145c8565b9250925092508288602001818151612a2291906158a2565b905250875182908990612a369083906158a2565b905250604088018051829190612a4d9083906158a2565b905250612a5e612167600187615b79565b90955093505050505b618000600183900b016128fb575b612a898461016001518561014001516131ed565b50505050919050565b5f80612a9c612adb565b5090505f612aa86139e2565b50905061275082826001613007565b5f6001600160e01b03198216637965db0b60e01b1480610a3b5750610a3b82614704565b6005545f908190612aee81836080613222565b9250612afc81608080613222565b9150509091565b5f80612b0d6139e2565b6040805160608101825260ca546001600160801b0381168252600160801b81046001600160501b03166020830152600160d01b900465ffffffffffff16918101829052919450919250905f90612b6390426158d4565b90508015612caf575f80612b7684613a17565b915091507f00000000000000000000000050562fe7e870420f5aae480b7f94eb4ace2fcd706001600160a01b03166370d00a586040518163ffffffff1660e01b8152600401602060405180830381865afa158015612bd6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612bfa919061583a565b15612ca2575f612c08612adb565b9150505f612c1882896001612fee565b90505f612c31670de0b6b3a76400006301e1338061586c565b86612c3c868561586c565b612c46919061586c565b612c50919061595e565b9050633b9aca00612c5f613764565b612c69908361586c565b612c73919061595e565b9050612c7f81836158d4565b612c89838b61586c565b612c93919061595e565b9850612c9e89614753565b5050505b612cac8282613c36565b50505b50509091565b5f612cbe613214565b9050612ccc81600101614796565b612cd95f428160286147b8565b63ffffffff82165f81815260076020526040902091909155612cfc9083906147cc565b919050565b604080516080810182525f808252602082018190529181018290526060810191909152505f8181526006602090815260409182902082516080810184529054600181900b825265ffffffffffff620100008204169282018390526001600160601b03600160401b8204811694830194909452600160a01b9004909216606083015215612cfc575f805f612d9f846020015165ffffffffffff1661482d565b925092509250603c8285604001516001600160601b0316612dc0919061586c565b6001600160601b03911c811660408601526060850151603c91612de59184911661586c565b6001600160601b03911c81166060860190815263ffffffff90941660208087019182525f88815260069091526040908190208751815493519289015197518516600160a01b026001600160a01b0398909516600160401b029790971667ffffffffffffffff65ffffffffffff93909316620100000267ffffffffffffffff1990941661ffff90981697909717929092171694909417179092555050919050565b806020015165ffffffffffff165f03612e9b5750565b60208082015165ffffffffffff165f908152600a909152604081206001015490612ec782608080613222565b60408401519091505f906001600160601b0316612ee684836080613222565b612ef091906158d4565b90505f84606001516001600160601b031683612f0c91906158d4565b9050612f1b84835f60806147b8565b9350612f2a84826080806147b8565b60208087015165ffffffffffff165f908152600a90915260409020600101819055935080158015612f5a57505f83115b15612fe75760208581015165ffffffffffff165f908152600a9091526040812054617fff60309190911c61ffff1690811161ffff1902179050612fc3600882600881901c5f90810b815260209290925260409091208054600160ff9093169290921b9091189055565b5f612fcc613cd9565b90508160010b8160010b03612fe457612fe4816148f6565b50505b5050505050565b5f612fff84600160601b8585614934565b949350505050565b5f612fff8484600160601b85614934565b6003545f90819061302c81605a603c613222565b9250612afc816096601e613222565b5f8082131561307b575f61304d61193e565b9050633b9aca008111156130625750633b9aca005b633b9aca00613071828561586c565b611f98919061595e565b633b9aca00613088614049565b61309184615820565b61309b919061586c565b610a3b919061595e565b6002545f9081906130b9816062603c613222565b9250612afc81609e603c613222565b5f8083156131e5578280156130e05750633b9aca0084125b156130fe5760405163ba63dfbf60e01b815260040160405180910390fd5b6131088585614969565b9150613113826149ce565b65ffffffffffff81165f908152600a60205260408120600101549192508661313d83836080613222565b61314791906158a2565b90505f8661315784608080613222565b61316191906158a2565b905061317083835f60806147b8565b925061317f83826080806147b8565b65ffffffffffff85165f908152600a6020526040902060010181905592508681036131c657600885811c5f90810b8152602091909152604090208054600160ff88161b1890555b6131ce613cd9565b60010b8513156131e1576131e1856149f5565b5050505b935093915050565b6005546131fd81845f60806147b8565b905061320c81836080806147b8565b600555505050565b6002545f906113aa90601260205b6001901b5f190191901c1690565b6003545f9081906132438183603c613222565b9250612afc81603c601e613222565b5f633b9aca0061326283826158a2565b61327485670de0b6b3a764000061586c565b61327e919061586c565b613288919061595e565b61329a670de0b6b3a76400008061586c565b6132a491906158d4565b866132af868661586c565b6132b9919061586c565b670de0b6b3a76400006132cc818961586c565b6132d6919061586c565b6132e091906158d4565b6132ea919061595e565b9695505050505050565b600184900b5f9081526009602052604090205465ffffffffffff1661331885614a10565b50600885811c5f90810b8152602091909152604090208054600160ff88161b18905565ffffffffffff81165f908152600a6020526040812060018101549054909161336583826080613222565b90505f61337484608080613222565b90505f61338189846158d4565b90505f61338e89846158d4565b90505f846133a06001603c1b8561586c565b6133aa919061595e565b90505f846133bc6001603c1b8561586c565b6133c6919061595e565b90506133d587836040806147b8565b96506133e58782608060406147b8565b9650600160ff1b831561341c575f6133fe86865f6130c8565b90925090506134188965ffffffffffff83165f60306147b8565b9850505b600160ff1b8103613494577f5fe96f4d1f13c468b9090d9e0bfa3b28cf26e4fe6439122f08ddbf605998e8a98e617fff1987878f604051613487959493929190600195860b81529390940b602084015260408301919091526060820152608081019190915260a00190565b60405180910390a16134fa565b7f5fe96f4d1f13c468b9090d9e0bfa3b28cf26e4fe6439122f08ddbf605998e8a98e8287878f6040516134f1959493929190600195860b81529390940b602084015260408301919091526060820152608081019190915260a00190565b60405180910390a15b5f613503613cd9565b90508e60010b8160010b14801561351d57508e60010b8214155b1561352b5761352b816148f6565b50505065ffffffffffff9097165f908152600a602052604090209490945550505050505050505050565b5f8061356083614aa3565b90506001600160a01b038116610a3b57604051637e27328960e01b8152600481018490526024016117c3565b5f9081527f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930460205260409020546001600160a01b031690565b6118b78383836001614adc565b6002545f906113aa9060326030613222565b5f5f80516020615d34833981519152816135fd85614aa3565b90506001600160a01b0384161561361957613619818587614bef565b6001600160a01b03811615613655576136345f865f80614adc565b6001600160a01b0381165f908152600383016020526040902080545f190190555b6001600160a01b03861615613685576001600160a01b0386165f9081526003830160205260409020805460010190555b5f85815260028301602052604080822080546001600160a01b0319166001600160a01b038a811691821790925591518893918516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a495945050505050565b6136f08133614c53565b50565b61370181633b9aca00614c8c565b60c9545f61371282605a601e613222565b90506137228284605a601e6147b8565b60c95560408051828152602081018590527fdaf49fa2ee916dacec50caa3c51a56add055165efaf1f17d25725fcd2c99193591015b60405180910390a1505050565b60c9545f906113aa9060786020613222565b5f5f80516020615d5483398151915261378f8484611e2c565b61380e575f848152602082815260408083206001600160a01b03871684529091529020805460ff191660011790556137c43390565b6001600160a01b0316836001600160a01b0316857f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a46001915050610a3b565b5f915050610a3b565b5092915050565b5f5f80516020615d548339815191526138378484611e2c565b1561380e575f848152602082815260408083206001600160a01b0387168085529252808320805460ff1916905551339287917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a46001915050610a3b565b6138a081614cad565b600180546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527ff3920b145a63851522088bd18b14d6bb919fbd12ac87f12498d6001c727ba070910160405180910390a15050565b61390f82633b9aca00614c8c565b61392181670de0b6b3a7640000614c8c565b60c95461393181845f601e6147b8565b90506139418183601e603c6147b8565b60c95560408051848152602081018490527f8874dc26eed942ffa0cacd0a09a6a0e782d014442e67ed2c7d3bcf61b759f6379101613757565b6139888163ffffffff614c8c565b60c9545f6139998260786020613222565b90506139a98284607860206147b8565b60c95560408051828152602081018590527fe6bbe7a165b8fa6949fe8e2bb60416d7af3b8149e381b428196d08c2a166b6359101613757565b6004545f908190612aee81836080613222565b60c9545f908190613a088183601e613222565b9250612afc81601e603c613222565b805160405163386497fd60e01b81526001600160a01b037f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48811660048301525f9283926001600160801b03909116917f00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2169063386497fd90602401602060405180830381865afa158015613aad573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190613ad19190615855565b92505f846040015165ffffffffffff1642613aec91906158d4565b9050610708811015613b0d5784602001516001600160501b03169250613b66565b613b17818361586c565b670de0b6b3a7640000613b2a84876158d4565b613b38906301e1338061586c565b613b42919061586c565b613b4c919061595e565b9250825f03613b665784602001516001600160501b031692505b5050915091565b613b75614cd4565b565b613b7f614cd4565b61177f8282614d1d565b613b91614cd4565b613b9a82614cad565b5f80546001600160a01b0319166001600160a01b03841617905561177f81613897565b613bc5614cd4565b613bcf6001614d4d565b613b75617fff196149f5565b613be3614cd4565b613b756001614796565b613bf5614cd4565b613c02600160601b61448f565b613c0f600160601b614753565b613c296706f05b59d3b20000670be52ee321c36db6613cf2565b613b75630bebc2006140eb565b6040805160608101825260ca80546001600160801b0386168084526001600160501b038616602085018190524265ffffffffffff8116868801819052600160d01b026001600160d01b03600160801b939093026001600160d01b0319909516909317939093171617909155915190917f4bb06cac844a363088e8f86dfbc70a781d8369fdbd4caa71228facb72d50dfc99161375791868252602082015260400190565b60028054617fff911c61ffff1690811161ffff19021790565b613cfc8282614c8c565b613d0e81670de0b6b3a7640000614c8c565b600254613d1f81846062603c6147b8565b9050613d2f8183609e603c6147b8565b60025560408051848152602081018490527f9f4d9f603359ea7747a1caa931ec105693f4fa63d739ca60d729ca98a683bff09101613757565b6002545f906113aa9060da601e613222565b5f80516020615d348339815191526001600160a01b038316613dba57604051630b61174360e31b81526001600160a01b03841660048201526024016117c3565b6001600160a01b038481165f818152600584016020908152604080832094881680845294825291829020805460ff191687151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a350505050565b613e3b82670de0b6b3a7640000614c8c565b613e4981633b9aca00614c8c565b600354613e5a8184605a603c6147b8565b9050613e6a81836096601e6147b8565b60035560408051848152602081018490527f7adbf035b2e2ae03a957c0cd561744f4010902e1001c2d41086c06f54504b7169101613757565b60025460011916811760025560405181151581527f0c62bbdfbcbe8bf3480c55ec19a4923a65eb876e49568f084595873b64cf8386906020015b60405180910390a150565b60025460021916600182901b1760025560405181151581527fe92fbb024677220febae1048128887af04da8455f22497316b00bb175be6b3ed90602001613edd565b6001600160a01b0383163b1561182657604051630a85bd0160e11b81526001600160a01b0384169063150b7a0290613f6c903390889087908790600401615b9c565b6020604051808303815f875af1925050508015613fa6575060408051601f3d908101601f19168201909252613fa391810190615bce565b60015b61400d573d808015613fd3576040519150601f19603f3d011682016040523d82523d5f602084013e613fd8565b606091505b5080515f0361400557604051633250574960e11b81526001600160a01b03851660048201526024016117c3565b805181602001fd5b6001600160e01b03198116630a85bd0160e11b14612fe757604051633250574960e11b81526001600160a01b03851660048201526024016117c3565b60c9545f906113aa90605a601e613222565b60605f61406783614d66565b60010190505f8167ffffffffffffffff81111561408657614086615581565b6040519080825280601f01601f1916602001820160405280156140b0576020820181803683370190505b5090508181016020015b5f19016f181899199a1a9b1b9c1cb0b131b232b360811b600a86061a8153600a85049450846140ba57509392505050565b6140f981633b9aca00614c8c565b60025461410a908260da601e6147b8565b6002556040518181527fa81c6ce7b85dedd389acede97c4c68e7ccd76ae970023b8af6a32d3d5b75e8ae90602001613edd565b600881901c5f81810b8152602084905260408120549091600160ff851690811b80015f190192831680151593908461417a578260ff16870361418b565b61418381614e3d565b830360ff1687035b9550505050509250929050565b600183810b5f9081526009602090815260408083205465ffffffffffff16808452600a90925282209092015490918291829182916141d881846080613222565b95506141e681608080613222565b94506141f486896001612fee565b935061420285886001613007565b9250505093509350935093565b5f805f805f8560a00151866040015161422891906158a2565b905085606001519450856080015185111561424557856080015194505b61010086015161425d670de0b6b3a76400008761586c565b614267919061595e565b93505f80876060015187036142825787602001519150614296565b614293878961014001516001612fee565b91505b8583116142ea578295508760a001519350670de0b6b3a7640000886101000151846142c1919061586c565b6142cb919061595e565b96506142de878961014001516001612fee565b8851909250905061436b565b633b9aca008860e00151876142ff919061586c565b614309919061595e565b94505f61431687876158a2565b90508381111561432f57508261432c87826158d4565b95505b8860400151811061435557604089015161434990826158d4565b89519095509150614369565b614366818a61012001516001613007565b91505b505b838860a00181815161437d91906158d4565b9052508751811480156143935750876020015182105b1561442a575f6143b9838a602001516143ac91906158d4565b8a61014001516001613007565b9050886020015192508189610160018181516143d591906158d4565b905250610180890180518491906143ed9083906158d4565b905250610180890151614404600160601b8361586c565b61440e919061595e565b896101400181815161442091906158a2565b9052506144599050565b80886101600181815161443d91906158d4565b905250610180880180518391906144559083906158d4565b9052505b868860800181815161446b91906158d4565b915081815250506144838982848b61010001516132f4565b50505092959194509250565b60045461449f90825f60806147b8565b6004556040518181527f0eb47678af0fcacabbadc23b52144abfc1b9341bfb37b6ede42d22bb243defda90602001613edd565b5f6001603c1b805b5f848152600a6020526040812054906144f582826030613222565b9050603c61450583604080613222565b61450f908661586c565b901c9350603c6145228360806040613222565b61452c908561586c565b901c9250805f0361453e575050614547565b94506144da9050565b929390929150565b61456182670de0b6b3a7640000614c8c565b61456f81633b9aca00614c8c565b60035461457f81845f603c6147b8565b905061458f8183603c601e6147b8565b60035560408051848152602081018490527f15658fc22e6d738d694640c7ec144edc24a5217d8e1b1cb6a17973b1f1c928759101613757565b5f805f6145ec846040015185606001518660e001518760a001518860c00151613252565b9250828460800151101561460257836080015192505b5f614614848661012001516001612fee565b60e086015190915061462e670de0b6b3a76400008661586c565b614638919061595e565b9250633b9aca008560c001518461464f919061586c565b614659919061595e565b915082856040015161466b91906158d4565b8211156146855782856040015161468291906158d4565b91505b5f6146a061469384866158a2565b8761010001516001613007565b90506146b28782848960e001516132f4565b8086610140018181516146c591906158d4565b905250610160860180518391906146dd9083906158d4565b9052506080860180518691906146f49083906158d4565b9150818152505050509250925092565b5f6001600160e01b031982166380ac58cd60e01b148061473457506001600160e01b03198216635b5e139f60e01b145b80610a3b57506301ffc9a760e01b6001600160e01b0319831614610a3b565b60045461476390826080806147b8565b6004556040518181527fae4d80815d6017051882e2605756a6374b276db7e0552860fa6b7c320a20be0190602001613edd565b6002546147b29063ffffffff808416906012906020906147b816565b60025550565b6001901b5f1901811b1992909216911b1790565b6001600160a01b0382166147f557604051633250574960e11b81525f60048201526024016117c3565b5f61480183835f6135e4565b90506001600160a01b038116156118b7576040516339e3563760e11b81525f60048201526024016117c3565b5f818152600a6020526040812054819081908161484c82826030613222565b905061485a82604080613222565b93506148698260806040613222565b9250805f0361487a578594506148ed565b5f806148858361482d565b91985092509050603c614898838861586c565b901c9550603c6148a8828761586c565b901c94506148b984885f60306147b8565b93506148c884876040806147b8565b93506148d88486608060406147b8565b5f898152600a60205260409020819055935050505b50509193909250565b617fff19600182900b131561492b575f614914612167600184615b79565b90925090508015614925575061492b565b506148f6565b6136f0816149f5565b5f600182600181111561494957614949615be9565b1461495e57614959858585614f26565b611e23565b611e23858585614f53565b5f808361497a600160601b8561586c565b614984919061595e565b90505f61499082614f5f565b90935090508181146149c657826149a681615bfd565b935061271090506149b98261271f61586c565b6149c3919061595e565b91505b505092915050565b5f8181526009602052604081205465ffffffffffff1690819003612cfc57610a3b82614a10565b600280549082901b6203fffc166203fffc19909116176147b2565b5f614a196135d2565b9050614a2781600101614d4d565b600182900b5f908152600960205260408120805465ffffffffffff191665ffffffffffff841617905567ffff000000000000603084901b169050614a72816001603c1b6040806147b8565b9050614a86816001603c1b608060406147b8565b65ffffffffffff83165f908152600a602052604090205550919050565b5f9081527f80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930260205260409020546001600160a01b031690565b5f80516020615d348339815191528180614afe57506001600160a01b03831615155b15614bbf575f614b0d85613555565b90506001600160a01b03841615801590614b395750836001600160a01b0316816001600160a01b031614155b8015614b4c5750614b4a81856125ff565b155b15614b755760405163a9fbf51f60e01b81526001600160a01b03851660048201526024016117c3565b8215614bbd5784866001600160a01b0316826001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45b505b5f93845260040160205250506040902080546001600160a01b0319166001600160a01b0392909216919091179055565b614bfa838383615352565b6118b7576001600160a01b038316614c2857604051637e27328960e01b8152600481018290526024016117c3565b60405163177e802f60e01b81526001600160a01b0383166004820152602481018290526044016117c3565b614c5d8282611e2c565b61177f5760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044016117c3565b8082111561177f57604051634df52d2560e11b815260040160405180910390fd5b6001600160a01b0381166136f05760405163a7f9319d60e01b815260040160405180910390fd5b7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054600160401b900460ff16613b7557604051631afcd79f60e31b815260040160405180910390fd5b614d25614cd4565b5f80516020615d3483398151915280614d3e8482615c5f565b50600181016118268382615c5f565b6002546147b29065ffffffffffff8316603260306147b8565b5f8072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8310614da45772184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b830492506040015b6d04ee2d6d415b85acef81000000008310614dd0576d04ee2d6d415b85acef8100000000830492506020015b662386f26fc100008310614dee57662386f26fc10000830492506010015b6305f5e1008310614e06576305f5e100830492506008015b6127108310614e1a57612710830492506004015b60648310614e2c576064830492506002015b600a8310610a3b5760010192915050565b5f808211614e49575f80fd5b600160801b8210614e6757608091821c91614e649082615d1a565b90505b600160401b8210614e8557604091821c91614e829082615d1a565b90505b6401000000008210614ea457602091821c91614ea19082615d1a565b90505b620100008210614ec157601091821c91614ebe9082615d1a565b90505b6101008210614edd57600891821c91614eda9082615d1a565b90505b60108210614ef857600491821c91614ef59082615d1a565b90505b60048210614f1357600291821c91614f109082615d1a565b90505b60028210612cfc57610a3b600182615d1a565b5f81600181614f35868861586c565b614f3f91906158a2565b614f4991906158d4565b612fff919061595e565b5f81614f49848661586c565b5f80630235b88083107473d85bca016a2338b31715f8e13054c005f8b995d384111715614f8a575f80fd5b600160601b83105f81614fad5750600160601b6a52b7d2dcc80cd2e40000008502045b8115614fc457506714adf4b7320334b9607a1b8490045b6f037af932b2affa9738cc6c38ca527831811061500557614000841793506f037af932b2affa9738cc6c38ca5278316a52b7d2dcc80cd2e400000082020490505b6d010f7a088a76f267264caa114f0a811061504257612000841793506d010f7a088a76f267264caa114f0a6a52b7d2dcc80cd2e400000082020490505b6b95da74f87f839fc2e0dc5bd9811061507b57611000841793506b95da74f87f839fc2e0dc5bd96a52b7d2dcc80cd2e400000082020490505b6b06f55dedafd8491caed5a1b881106150b457610800841793506b06f55dedafd8491caed5a1b86a52b7d2dcc80cd2e400000082020490505b6b017fdd10ee11e624491b4cc181106150ed57610400841793506b017fdd10ee11e624491b4cc16a52b7d2dcc80cd2e400000082020490505b6ab23131bf0c30217b0a2c69811061512457610200841793506ab23131bf0c30217b0a2c696a52b7d2dcc80cd2e400000082020490505b6a79683edcb9280d797aded7811061515b57610100841793506a79683edcb9280d797aded76a52b7d2dcc80cd2e400000082020490505b6a64366e2f9919f0d9b0dc908110615191576080841793506a64366e2f9919f0d9b0dc906a52b7d2dcc80cd2e400000082020490505b6a5b0bcda5a78850646b0a8181106151c7576040841793506a5b0bcda5a78850646b0a816a52b7d2dcc80cd2e400000082020490505b6a56c840f992c70f959ae81081106151fd576020841793506a56c840f992c70f959ae8106a52b7d2dcc80cd2e400000082020490505b6a54b9cd178695194f9be0a08110615233576010841793506a54b9cd178695194f9be0a06a52b7d2dcc80cd2e400000082020490505b6a53b7458aff204b5e65d6818110615269576008841793506a53b7458aff204b5e65d6816a52b7d2dcc80cd2e400000082020490505b6a53372a2f38c240d689e400811061529f576004841793506a53372a2f38c240d689e4006a52b7d2dcc80cd2e400000082020490505b6a52f76617a04499e664000081106152d5576002841793506a52f76617a04499e66400006a52b7d2dcc80cd2e400000082020490505b6a52d79660f3dec355c00000811061530b576001841793506a52d79660f3dec355c000006a52b7d2dcc80cd2e400000082020490505b8161532357806a52b7d2dcc80cd2e400000086020492505b811561533f579219926a52d79660f3dec355c000008582020492505b50508281111561534d575f80fd5b915091565b5f6001600160a01b03831615801590612fff5750826001600160a01b0316846001600160a01b0316148061538b575061538b84846125ff565b80612fff5750826001600160a01b03166153a48361358c565b6001600160a01b031614949350505050565b6001600160e01b0319811681146136f0575f80fd5b5f602082840312156153db575f80fd5b8135611f98816153b6565b6001600160a01b03811681146136f0575f80fd5b5f805f806080858703121561540d575f80fd5b843593506020850135925060408501359150606085013561542d816153e6565b939692955090935050565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b602081525f611f986020830184615438565b5f8060408385031215615489575f80fd5b82358060010b8114615499575f80fd5b946020939093013593505050565b5f602082840312156154b7575f80fd5b5035919050565b5f80604083850312156154cf575f80fd5b8235615499816153e6565b5f805f606084860312156154ec575f80fd5b83356154f7816153e6565b92506020840135615507816153e6565b929592945050506040919091013590565b5f8060408385031215615529575f80fd5b82359150602083013561553b816153e6565b809150509250929050565b5f60208284031215615556575f80fd5b8135611f98816153e6565b5f8060408385031215615572575f80fd5b50508035926020909101359150565b634e487b7160e01b5f52604160045260245ffd5b6040516101e0810167ffffffffffffffff811182821017156155b9576155b9615581565b60405290565b5f8067ffffffffffffffff8411156155d9576155d9615581565b50604051601f19601f85018116603f0116810181811067ffffffffffffffff8211171561560857615608615581565b60405283815290508082840185101561561f575f80fd5b838360208301375f60208583010152509392505050565b5f82601f830112615645575f80fd5b611f98838335602085016155bf565b5f805f805f60a08688031215615668575f80fd5b8535615673816153e6565b9450602086013567ffffffffffffffff81111561568e575f80fd5b61569a88828901615636565b945050604086013567ffffffffffffffff8111156156b6575f80fd5b6156c288828901615636565b93505060608601356156d3816153e6565b915060808601356156e3816153e6565b809150509295509295909350565b5f60208284031215615701575f80fd5b8135805f0b8114611f98575f80fd5b80151581146136f0575f80fd5b5f806040838503121561572e575f80fd5b8235615739816153e6565b9150602083013561553b81615710565b5f806040838503121561575a575f80fd5b823561573981615710565b5f805f8060808587031215615778575f80fd5b8435615783816153e6565b93506020850135615793816153e6565b925060408501359150606085013567ffffffffffffffff8111156157b5575f80fd5b8501601f810187136157c5575f80fd5b6157d4878235602084016155bf565b91505092959194509250565b5f80604083850312156157f1575f80fd5b82356157fc816153e6565b9150602083013561553b816153e6565b634e487b7160e01b5f52601160045260245ffd5b5f600160ff1b82016158345761583461580c565b505f0390565b5f6020828403121561584a575f80fd5b8151611f9881615710565b5f60208284031215615865575f80fd5b5051919050565b8082028115828204841417610a3b57610a3b61580c565b8181035f8312801583831316838312821617156138175761381761580c565b80820180821115610a3b57610a3b61580c565b8082018281125f8312801582168215821617156149c6576149c661580c565b81810381811115610a3b57610a3b61580c565b600181811c908216806158fb57607f821691505b60208210810361591957634e487b7160e01b5f52602260045260245ffd5b50919050565b5f805f60608486031215615931575f80fd5b5050815160208301516040909301519094929350919050565b634e487b7160e01b5f52601260045260245ffd5b5f8261596c5761596c61594a565b500490565b5f60208284031215615981575f80fd5b6040516020810167ffffffffffffffff811182821017156159a4576159a4615581565b6040529151825250919050565b80516001600160801b0381168114612cfc575f80fd5b805164ffffffffff81168114612cfc575f80fd5b805161ffff81168114612cfc575f80fd5b8051612cfc816153e6565b5f6101e0828403128015615a09575f80fd5b50615a12615595565b615a1c8484615971565b8152615a2a602084016159b1565b6020820152615a3b604084016159b1565b6040820152615a4c606084016159b1565b6060820152615a5d608084016159b1565b6080820152615a6e60a084016159b1565b60a0820152615a7f60c084016159c7565b60c0820152615a9060e084016159db565b60e0820152615aa261010084016159ec565b610100820152615ab561012084016159ec565b610120820152615ac861014084016159ec565b610140820152615adb61016084016159ec565b610160820152615aee61018084016159b1565b610180820152615b016101a084016159b1565b6101a0820152615b146101c084016159b1565b6101c08201529392505050565b5f6001600160801b03831680615b3957615b3961594a565b806001600160801b0384160491505092915050565b5f81518060208401855e5f93019283525090919050565b5f612fff615b738386615b4e565b84615b4e565b600182810b9082900b03617fff198112617fff82131715610a3b57610a3b61580c565b6001600160a01b03858116825284166020820152604081018390526080606082018190525f906132ea90830184615438565b5f60208284031215615bde575f80fd5b8151611f98816153b6565b634e487b7160e01b5f52602160045260245ffd5b5f6001600160ff1b018201615c1457615c1461580c565b5060010190565b601f8211156118b757805f5260205f20601f840160051c81016020851015615c405750805b601f840160051c820191505b81811015612fe7575f8155600101615c4c565b815167ffffffffffffffff811115615c7957615c79615581565b615c8d81615c8784546158e7565b84615c1b565b6020601f821160018114615cbf575f8315615ca85750848201515b5f19600385901b1c1916600184901b178455612fe7565b5f84815260208120601f198516915b82811015615cee5787850151825560209485019460019092019101615cce565b5084821015615d0b57868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b60ff8181168382160190811115610a3b57610a3b61580c56fe80bb2b638cc20bc4d0a60d66940f3ab4a00c1d7b313497ca82fb0b4ab007930002dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800a264697066735822122026359106180a43d56cef53de9f6ae9a7c76abb882ce90514c3424b046875b4d364736f6c634300081a0033

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

000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd2400000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48

-----Decoded View---------------
Arg [0] : _poolManager (address): 0x250893CA4Ba5d05626C785e8da758026928FCD24
Arg [1] : _lendingPool (address): 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2
Arg [2] : _baseAsset (address): 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48

-----Encoded View---------------
3 Constructor Arguments found :
Arg [0] : 000000000000000000000000250893ca4ba5d05626c785e8da758026928fcd24
Arg [1] : 00000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e2
Arg [2] : 000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48


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

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