ETH Price: $2,439.23 (-1.94%)

Contract

0xe5aCBf87a4403C954186e5234B6D237333540735
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
0x60a06040188680612023-12-26 6:24:35286 days ago1703571875IN
 Create: RangeProtocolVault
0 ETH0.0484508213.86018122

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RangeProtocolVault

Compiler Version
v0.8.4+commit.c7e474f2

Optimization Enabled:
Yes with 100 runs

Other Settings:
default evmVersion
File 1 of 43 : RangeProtocolVault.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IPoolAddressesProvider} from "@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol";
import {RangeProtocolVaultStorage} from "./RangeProtocolVaultStorage.sol";
import {IRangeProtocolVault} from "./interfaces/IRangeProtocolVault.sol";
import {OwnableUpgradeable} from "./access/OwnableUpgradeable.sol";
import {DataTypesLib} from "./libraries/DataTypesLib.sol";
import {LogicLib} from "./libraries/LogicLib.sol";
import {VaultErrors} from "./errors/VaultErrors.sol";

/**
 * @notice RangeProtocolVault is vault for AMM pools where a collateral token is paired with Aave's GHO token.
 * It has mint and burn functions for the users to provide liquidity in collateral token to the vault and has
 * functions removeLiquidity, addLiquidity and swap for the manager to manage liquidity. Upon vault deployment, the
 * manager calls updateTicks function to start the minting process by users at a specified tick range. Once the mint
 * has started, the liquidity provided by users directly go to the AMM pool. The manager can remove liquidity from
 * the AMM pool and for providing liquidity into a newer tick range, manager will perform swap to have tokens in ratio
 * accordingly to the newer tick range and call addLiquidity function to add to a newer tick range.
 */
contract RangeProtocolVault is
    Initializable,
    UUPSUpgradeable,
    ReentrancyGuardUpgradeable,
    OwnableUpgradeable,
    ERC20Upgradeable,
    PausableUpgradeable,
    RangeProtocolVaultStorage
{
    // @notice restricts the call by self. It used to restrict the allowed calls only from the LogicLib.
    modifier onlyVault() {
        if (msg.sender != address(this)) revert VaultErrors.OnlyVaultAllowed();
        _;
    }

    constructor() {
        _disableInitializers();
    }

    // @notice initialised the vault's initial sate.
    // @param _pool address of pool with which the vault interacts.
    // @param _tickSpacing tick spacing of the pool.
    // @param data additional data of the vault.
    function initialize(address _pool, int24 _tickSpacing, bytes memory data) external override initializer {
        (
            address manager,
            string memory _name,
            string memory _symbol,
            address _gho,
            address _poolAddressesProvider,
            address _collateralPriceOracleAddress,
            uint256 _collateralPriceOracleHeartbeat,
            address _ghoPriceOracleAddress,
            uint256 _ghoPriceOracleHeartbeat
        ) = abi.decode(data, (address, string, string, address, address, address, uint256, address, uint256));
        __UUPSUpgradeable_init();
        __ReentrancyGuard_init();
        __Ownable_init();
        __ERC20_init(_name, _symbol);
        __Pausable_init();
        _transferOwnership(manager);

        if (manager == address(0x0)) revert VaultErrors.ZeroManagerAddress();
        if (address(IUniswapV3Pool(_pool).token0()) != _gho) revert VaultErrors.TokenZeroIsNotGHO();

        state.pool = IUniswapV3Pool(_pool);
        IERC20Upgradeable token0 = IERC20Upgradeable(state.pool.token0());
        IERC20Upgradeable token1 = IERC20Upgradeable(state.pool.token1());
        state.token0 = token0;
        state.token1 = token1;
        state.tickSpacing = _tickSpacing;
        state.factory = msg.sender;
        uint8 decimals0 = IERC20MetadataUpgradeable(address(token0)).decimals();
        uint8 decimals1 = IERC20MetadataUpgradeable(address(token1)).decimals();
        state.decimals0 = decimals0;
        state.decimals1 = decimals1;
        state.poolAddressesProvider = IPoolAddressesProvider(_poolAddressesProvider);
        state.collateralPriceOracle = DataTypesLib.PriceOracle(
            AggregatorV3Interface(_collateralPriceOracleAddress),
            _collateralPriceOracleHeartbeat
        );
        state.ghoPriceOracle = DataTypesLib.PriceOracle(
            AggregatorV3Interface(_ghoPriceOracleAddress),
            _ghoPriceOracleHeartbeat
        );

        state.vaultDecimals = address(token0) == _gho
            ? state.vaultDecimals = decimals1
            : state.vaultDecimals = decimals0;

        // Managing fee is 0.1% and performance fee is 10% at the time vault initialization.
        LogicLib.updateFees(state, 10, 1000);
    }

    // @notice pauses the mint and burn functions. It can only be called by the vault manager.
    function pause() external onlyManager {
        _pause();
    }

    // @notice unpauses the mint and burn functions. It can only be called by the vault manager.
    function unpause() external onlyManager {
        _unpause();
    }

    // @notice mints shares to the provided address. Only the vault itself is allowed to call this function. The LogicLib
    // used by the vault calls to mint shares to an address.
    // @param to the address to mint shares to.
    // @param shares the amount of shares to mint.
    function mintShares(address to, uint256 shares) external override onlyVault {
        _mint(to, shares);
    }

    // @notice burns shares from the provided address. Only the vault itself is allowed to call this function. The LogicLib
    // used by the vault calls to burn shares from an address.
    // @notice from the address to burn shares from.
    // @notice shares the amount of shares to burn.
    function burnShares(address from, uint256 shares) external override onlyVault {
        _burn(from, shares);
    }

    // @notice uniswapV3 mint callback implementation. Calls uniswapV3MintCallback on the LogicLib to execute logic.
    // @param amount0Owed amount in token0 to transfer.
    // @param amount1Owed amount in token1 to transfer.
    function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata) external override {
        LogicLib.uniswapV3MintCallback(state, amount0Owed, amount1Owed);
    }

    // @notice uniswapV3 swap callback implementation. Calls uniswapV3SwapCallback on the LogicLib to execute logic.
    // @param amount0Delta amount0 added (+) or to be taken (-) from the vault.
    // @param amount1Delta amount1 added (+) or to be taken (-) from the vault.
    function uniswapV3SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata) external override {
        LogicLib.uniswapV3SwapCallback(state, amount0Delta, amount1Delta);
    }

    // @notice called by the user with collateral amount to provide liquidity in collateral amount. Calls mint function
    // on the LogicLib to execute logic.
    // @param amount the amount of collateral to provide.
    // @param minShares the minimum shares to mint.
    // @return shares the amount of shares minted.
    function mint(
        uint256 amount,
        uint256 minShares
    ) external override nonReentrant whenNotPaused returns (uint256 shares) {
        return LogicLib.mint(state, amount, minShares);
    }

    // @notice called by the user with share amount to burn their vault shares redeem their share of the asset. Calls
    // burn function on the LogicLib to execute logic.
    // @param burnAmount the amount of vault shares to burn.
    // @return amount the amount of assets in collateral token received by the user.
    function burn(
        uint256 burnAmount,
        uint256 minAmount
    ) external override nonReentrant whenNotPaused returns (uint256 amount) {
        return LogicLib.burn(state, burnAmount, minAmount);
    }

    // @notice called by manager to remove liquidity from the pool. Calls removeLiquidity function on the LogcLib.
    function removeLiquidity(uint256[2] calldata minAmounts) external override onlyManager {
        LogicLib.removeLiquidity(state, minAmounts);
    }

    // @notice called by manager to perform swap from token0 to token1 and vice-versa. Calls swap function on the LogicLib.
    // @param zeroForOne swap direction (true -> x to y) or (false -> y to x)
    // @param swapAmount amount to swap (+ve -> exact in, -ve exact out)
    // @param sqrtPriceLimitX96 the limit pool price can move when filling the order.
    // @param amount0 amount0 added (+) or to be taken (-) from the vault.
    // @param amount1 amount1 added (+) or to be taken (-) from the vault.
    function swap(
        bool zeroForOne,
        int256 swapAmount,
        uint160 sqrtPriceLimitX96,
        uint256 minAmountIn
    ) external override onlyManager returns (int256 amount0, int256 amount1) {
        return LogicLib.swap(state, zeroForOne, swapAmount, sqrtPriceLimitX96, minAmountIn);
    }

    // @notice called by manager to provide liquidity to pool into a newer tick range. Calls addLiquidity function on
    // the LogicLib.
    // @param newLowerTick lower tick of the position.
    // @param newUpperTick upper tick of the position.
    // @param amount0 amount in token0 to add.
    // @param amount1 amount in token1 to add.
    // @return remainingAmount0 amount in token0 left passive in the vault.
    // @return remainingAmount1 amount in token1 left passive in the vault.
    function addLiquidity(
        int24 newLowerTick,
        int24 newUpperTick,
        uint256 amount0,
        uint256 amount1,
        uint256[2] calldata maxAmounts
    ) external override onlyManager returns (uint256 remainingAmount0, uint256 remainingAmount1) {
        return LogicLib.addLiquidity(state, newLowerTick, newUpperTick, amount0, amount1, maxAmounts);
    }

    // @notice called by manager to transfer the unclaimed fee from pool to the vault. Calls pullFeeFromPool function on
    // the LogicLib.
    function pullFeeFromPool() external onlyManager {
        LogicLib.pullFeeFromPool(state);
    }

    // @notice called by manager to collect fee from the vault. Calls collectManager function on the LogicLib.
    function collectManager() external override onlyManager {
        LogicLib.collectManager(state, manager());
    }

    // @notice called by the manager to update the fees. Calls updateFees function on the LogicLib.
    // @param newManagingFee new managing fee percentage out of 10_000.
    // @param newPerformanceFee new performance fee percentage out of 10_000.
    function updateFees(uint16 newManagingFee, uint16 newPerformanceFee) external override onlyManager {
        LogicLib.updateFees(state, newManagingFee, newPerformanceFee);
    }

    /**
     * @notice returns current unclaimed fees from the pool. Calls getCurrentFees on the LogicLib.
     * @return fee0 fee in token0
     * @return fee1 fee in token1
     */
    function getCurrentFees() external view override returns (uint256 fee0, uint256 fee1) {
        return LogicLib.getCurrentFees(state);
    }

    /**
     * @notice returns user vaults based on the provided index. Calls getUserVaults on LogicLib.
     * @param fromIdx the starting index to fetch users.
     * @param toIdx the ending index to fetch users.
     * @return UserVaultInfo
     */
    function getUserVaults(
        uint256 fromIdx,
        uint256 toIdx
    ) external view override returns (DataTypesLib.UserVaultInfo[] memory) {
        return LogicLib.getUserVaults(state, fromIdx, toIdx);
    }

    // @notice supplied collateral to Aave. Called by manager only.
    // @param supplyAmount amount of collateral to supply.
    function supplyCollateral(uint256 supplyAmount) external override onlyManager {
        LogicLib.supplyCollateral(state, supplyAmount);
    }

    // @notice withdraws collateral from Aave. Called by manager only.
    // @param withdrawAmount amount of collateral to withdraw.
    function withdrawCollateral(uint256 withdrawAmount) external override onlyManager {
        LogicLib.withdrawCollateral(state, withdrawAmount);
    }

    // @notice borrows GHO token from Aave. Called by manager only.
    // @param mint amount of GHO to mint.
    function mintGHO(uint256 mintAmount) external override onlyManager {
        LogicLib.mintGHO(state, mintAmount);
    }

    // @notice payback GHO debt to Aave. Called by manager only.
    // @param burnAmount amount of GHO debt to payback.
    function burnGHO(uint256 burnAmount) external override onlyManager {
        LogicLib.burnGHO(state, burnAmount);
    }

    // @notice a multicall function to repeg the pool through the number of actions supplying/withdrawing collateral,
    // minting/burning of gho and performing swap on the uni pool.
    function repegPool(bytes[] memory calldatas) external override onlyManager returns (bytes[] memory returndatas) {
        returndatas = new bytes[](calldatas.length);
        for (uint256 i = 0; i < calldatas.length; i++) {
            (bool success, bytes memory returndata) = address(this).delegatecall(calldatas[i]);
            if (!success) {
                if (returndata.length > 0) {
                    assembly {
                        revert(add(32, returndata), mload(returndata))
                    }
                }
                revert VaultErrors.PoolRepegFailed();
            }
            returndatas[i] = returndata;
        }

        emit PoolRepegged();
    }

    // @notice updates the hearbeat duration of collateral and gho price oracles.
    // @param collateralOracleHBDuration heartbeat duration for collateral price oracle.
    // @param ghoOracleHBDuration heartbeat duration for gho price oracle.
    function updatePriceOracleHeartbeatsDuration(
        uint256 collateralOracleHBDuration,
        uint256 ghoOracleHBDuration
    ) external override onlyManager {
        LogicLib.updatePriceOracleHeartbeatsDuration(state, collateralOracleHBDuration, ghoOracleHBDuration);
    }

    /**
     * @notice returns Aave position data.
     * @return totalCollateralBase total collateral supplied.
     * @return totalDebtBase total debt borrowed.
     * @return availableBorrowsBase available amount to borrow.
     * @return currentLiquidationThreshold current threshold for liquidation to trigger.
     * @return ltv Loan-to-value ratio of the position.
     * @return healthFactor current health factor of the position.
     */
    function getAavePositionData()
        external
        view
        returns (
            uint256 totalCollateralBase,
            uint256 totalDebtBase,
            uint256 availableBorrowsBase,
            uint256 currentLiquidationThreshold,
            uint256 ltv,
            uint256 healthFactor
        )
    {
        return LogicLib.getAavePositionData(state);
    }

    // @notice returns decimals of the vault token.
    // @return decimals of vault shares.
    function decimals() public view override returns (uint8) {
        return state.vaultDecimals;
    }

    // @notice returns position id of the vault in pool.
    // @return positionId the id of the position in pool.
    function getPositionID() public view override returns (bytes32 positionID) {
        return LogicLib.getPositionID(state);
    }

    // @notice returns underlying balance in collateral token based on the shares amount passed.
    // @param shares amount of vault to calculate the redeemable amount against.
    // @return amount the amount of asset in collateral token redeemable against the provided amount of collateral.
    function getUnderlyingBalanceByShare(uint256 shares) external view override returns (uint256 amount) {
        return LogicLib.getUnderlyingBalanceByShare(state, shares);
    }

    // @notice returns vault asset's balance in collateral token.
    // @return amount the amount of vault holding converted to collateral token.
    function getBalanceInCollateralToken() public view override returns (uint256 amount) {
        return LogicLib.getBalanceInCollateralToken(state);
    }

    function getUnderlyingBalancesFromPool() external view override returns (uint256, uint256) {
        (uint160 sqrtRatioX96, int24 tick, , , , , ) = state.pool.slot0();
        return LogicLib.getUnderlyingBalancesFromPool(state, sqrtRatioX96, tick);
    }

    function getUnderlyingBalancesFromAave() external view override returns (uint256, uint256) {
        return LogicLib.getUnderlyingBalancesFromAave(state);
    }

    // @notice restricts upgrading of vault to factory only.
    function _authorizeUpgrade(address) internal override {
        if (msg.sender != state.factory) revert VaultErrors.OnlyFactoryAllowed();
    }

    // @notice transfer hook to transfer the exposure from sender to recipient. Calls _beforeTokenTransfer on the LogicLib.
    // @param from the sender of vault shares.
    // @param to recipient of vault shares.
    // @param amount amount of vault shares to transfer.
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal override {
        super._beforeTokenTransfer(from, to, amount);
        LogicLib._beforeTokenTransfer(state, from, to, amount);
    }
}

File 2 of 43 : IPool.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

import {IPoolAddressesProvider} from './IPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';

/**
 * @title IPool
 * @author Aave
 * @notice Defines the basic interface for an Aave Pool.
 */
interface IPool {
  /**
   * @dev Emitted on mintUnbacked()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address initiating the supply
   * @param onBehalfOf The beneficiary of the supplied assets, receiving the aTokens
   * @param amount The amount of supplied assets
   * @param referralCode The referral code used
   */
  event MintUnbacked(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted on backUnbacked()
   * @param reserve The address of the underlying asset of the reserve
   * @param backer The address paying for the backing
   * @param amount The amount added as backing
   * @param fee The amount paid in fees
   */
  event BackUnbacked(address indexed reserve, address indexed backer, uint256 amount, uint256 fee);

  /**
   * @dev Emitted on supply()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address initiating the supply
   * @param onBehalfOf The beneficiary of the supply, receiving the aTokens
   * @param amount The amount supplied
   * @param referralCode The referral code used
   */
  event Supply(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted on withdraw()
   * @param reserve The address of the underlying asset being withdrawn
   * @param user The address initiating the withdrawal, owner of aTokens
   * @param to The address that will receive the underlying
   * @param amount The amount to be withdrawn
   */
  event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);

  /**
   * @dev Emitted on borrow() and flashLoan() when debt needs to be opened
   * @param reserve The address of the underlying asset being borrowed
   * @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
   * initiator of the transaction on flashLoan()
   * @param onBehalfOf The address that will be getting the debt
   * @param amount The amount borrowed out
   * @param interestRateMode The rate mode: 1 for Stable, 2 for Variable
   * @param borrowRate The numeric rate at which the user has borrowed, expressed in ray
   * @param referralCode The referral code used
   */
  event Borrow(
    address indexed reserve,
    address user,
    address indexed onBehalfOf,
    uint256 amount,
    DataTypes.InterestRateMode interestRateMode,
    uint256 borrowRate,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted on repay()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The beneficiary of the repayment, getting his debt reduced
   * @param repayer The address of the user initiating the repay(), providing the funds
   * @param amount The amount repaid
   * @param useATokens True if the repayment is done using aTokens, `false` if done with underlying asset directly
   */
  event Repay(
    address indexed reserve,
    address indexed user,
    address indexed repayer,
    uint256 amount,
    bool useATokens
  );

  /**
   * @dev Emitted on swapBorrowRateMode()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user swapping his rate mode
   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable
   */
  event SwapBorrowRateMode(
    address indexed reserve,
    address indexed user,
    DataTypes.InterestRateMode interestRateMode
  );

  /**
   * @dev Emitted on borrow(), repay() and liquidationCall() when using isolated assets
   * @param asset The address of the underlying asset of the reserve
   * @param totalDebt The total isolation mode debt for the reserve
   */
  event IsolationModeTotalDebtUpdated(address indexed asset, uint256 totalDebt);

  /**
   * @dev Emitted when the user selects a certain asset category for eMode
   * @param user The address of the user
   * @param categoryId The category id
   */
  event UserEModeSet(address indexed user, uint8 categoryId);

  /**
   * @dev Emitted on setUserUseReserveAsCollateral()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user enabling the usage as collateral
   */
  event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);

  /**
   * @dev Emitted on setUserUseReserveAsCollateral()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user enabling the usage as collateral
   */
  event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);

  /**
   * @dev Emitted on rebalanceStableBorrowRate()
   * @param reserve The address of the underlying asset of the reserve
   * @param user The address of the user for which the rebalance has been executed
   */
  event RebalanceStableBorrowRate(address indexed reserve, address indexed user);

  /**
   * @dev Emitted on flashLoan()
   * @param target The address of the flash loan receiver contract
   * @param initiator The address initiating the flash loan
   * @param asset The address of the asset being flash borrowed
   * @param amount The amount flash borrowed
   * @param interestRateMode The flashloan mode: 0 for regular flashloan, 1 for Stable debt, 2 for Variable debt
   * @param premium The fee flash borrowed
   * @param referralCode The referral code used
   */
  event FlashLoan(
    address indexed target,
    address initiator,
    address indexed asset,
    uint256 amount,
    DataTypes.InterestRateMode interestRateMode,
    uint256 premium,
    uint16 indexed referralCode
  );

  /**
   * @dev Emitted when a borrower is liquidated.
   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
   * @param user The address of the borrower getting liquidated
   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
   * @param liquidatedCollateralAmount The amount of collateral received by the liquidator
   * @param liquidator The address of the liquidator
   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
   * to receive the underlying collateral asset directly
   */
  event LiquidationCall(
    address indexed collateralAsset,
    address indexed debtAsset,
    address indexed user,
    uint256 debtToCover,
    uint256 liquidatedCollateralAmount,
    address liquidator,
    bool receiveAToken
  );

  /**
   * @dev Emitted when the state of a reserve is updated.
   * @param reserve The address of the underlying asset of the reserve
   * @param liquidityRate The next liquidity rate
   * @param stableBorrowRate The next stable borrow rate
   * @param variableBorrowRate The next variable borrow rate
   * @param liquidityIndex The next liquidity index
   * @param variableBorrowIndex The next variable borrow index
   */
  event ReserveDataUpdated(
    address indexed reserve,
    uint256 liquidityRate,
    uint256 stableBorrowRate,
    uint256 variableBorrowRate,
    uint256 liquidityIndex,
    uint256 variableBorrowIndex
  );

  /**
   * @dev Emitted when the protocol treasury receives minted aTokens from the accrued interest.
   * @param reserve The address of the reserve
   * @param amountMinted The amount minted to the treasury
   */
  event MintedToTreasury(address indexed reserve, uint256 amountMinted);

  /**
   * @notice Mints an `amount` of aTokens to the `onBehalfOf`
   * @param asset The address of the underlying asset to mint
   * @param amount The amount to mint
   * @param onBehalfOf The address that will receive the aTokens
   * @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 mintUnbacked(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode
  ) external;

  /**
   * @notice Back the current unbacked underlying with `amount` and pay `fee`.
   * @param asset The address of the underlying asset to back
   * @param amount The amount to back
   * @param fee The amount paid in fees
   * @return The backed amount
   */
  function backUnbacked(address asset, uint256 amount, uint256 fee) external 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 Supply with transfer approval of asset to be supplied done via permit function
   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713
   * @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 deadline The deadline timestamp that the permit is valid
   * @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
   * @param permitV The V parameter of ERC712 permit sig
   * @param permitR The R parameter of ERC712 permit sig
   * @param permitS The S parameter of ERC712 permit sig
   */
  function supplyWithPermit(
    address asset,
    uint256 amount,
    address onBehalfOf,
    uint16 referralCode,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) 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);

  /**
   * @notice Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
   * already supplied enough collateral, or he was given enough allowance by a credit delegator on the
   * corresponding debt token (StableDebtToken or VariableDebtToken)
   * - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
   *   and 100 stable/variable debt tokens, depending on the `interestRateMode`
   * @param asset The address of the underlying asset to borrow
   * @param amount The amount to be borrowed
   * @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
   * @param referralCode The 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
   * @param onBehalfOf The address of the user who will receive the debt. Should be the address of the borrower itself
   * calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
   * if he has been given credit delegation allowance
   */
  function borrow(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    uint16 referralCode,
    address onBehalfOf
  ) external;

  /**
   * @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
   * - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
   * @param onBehalfOf The address of the user who will get his debt reduced/removed. Should be the address of the
   * user calling the function if he wants to reduce/remove his own debt, or the address of any other
   * other borrower whose debt should be removed
   * @return The final amount repaid
   */
  function repay(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf
  ) external returns (uint256);

  /**
   * @notice Repay with transfer approval of asset to be repaid done via permit function
   * see: https://eips.ethereum.org/EIPS/eip-2612 and https://eips.ethereum.org/EIPS/eip-713
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
   * @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
   * user calling the function if he wants to reduce/remove his own debt, or the address of any other
   * other borrower whose debt should be removed
   * @param deadline The deadline timestamp that the permit is valid
   * @param permitV The V parameter of ERC712 permit sig
   * @param permitR The R parameter of ERC712 permit sig
   * @param permitS The S parameter of ERC712 permit sig
   * @return The final amount repaid
   */
  function repayWithPermit(
    address asset,
    uint256 amount,
    uint256 interestRateMode,
    address onBehalfOf,
    uint256 deadline,
    uint8 permitV,
    bytes32 permitR,
    bytes32 permitS
  ) external returns (uint256);

  /**
   * @notice Repays a borrowed `amount` on a specific reserve using the reserve aTokens, burning the
   * equivalent debt tokens
   * - E.g. User repays 100 USDC using 100 aUSDC, burning 100 variable/stable debt tokens
   * @dev  Passing uint256.max as amount will clean up any residual aToken dust balance, if the user aToken
   * balance is not enough to cover the whole debt
   * @param asset The address of the borrowed underlying asset previously borrowed
   * @param amount The amount to repay
   * - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
   * @param interestRateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
   * @return The final amount repaid
   */
  function repayWithATokens(
    address asset,
    uint256 amount,
    uint256 interestRateMode
  ) external returns (uint256);

  /**
   * @notice Allows a borrower to swap his debt between stable and variable mode, or vice versa
   * @param asset The address of the underlying asset borrowed
   * @param interestRateMode The current interest rate mode of the position being swapped: 1 for Stable, 2 for Variable
   */
  function swapBorrowRateMode(address asset, uint256 interestRateMode) external;

  /**
   * @notice Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
   * - Users can be rebalanced if the following conditions are satisfied:
   *     1. Usage ratio is above 95%
   *     2. the current supply APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too
   *        much has been borrowed at a stable rate and suppliers are not earning enough
   * @param asset The address of the underlying asset borrowed
   * @param user The address of the user to be rebalanced
   */
  function rebalanceStableBorrowRate(address asset, address user) external;

  /**
   * @notice Allows suppliers to enable/disable a specific supplied asset as collateral
   * @param asset The address of the underlying asset supplied
   * @param useAsCollateral True if the user wants to use the supply as collateral, false otherwise
   */
  function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;

  /**
   * @notice Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
   * - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
   *   a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
   * @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
   * @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
   * @param user The address of the borrower getting liquidated
   * @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
   * @param receiveAToken True if the liquidators wants to receive the collateral aTokens, `false` if he wants
   * to receive the underlying collateral asset directly
   */
  function liquidationCall(
    address collateralAsset,
    address debtAsset,
    address user,
    uint256 debtToCover,
    bool receiveAToken
  ) external;

  /**
   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
   * as long as the amount taken plus a fee is returned.
   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
   * into consideration. For further details please visit https://docs.aave.com/developers/
   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanReceiver interface
   * @param assets The addresses of the assets being flash-borrowed
   * @param amounts The amounts of the assets being flash-borrowed
   * @param interestRateModes Types of the debt to open if the flash loan is not returned:
   *   0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
   *   1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
   *   2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
   * @param onBehalfOf The address  that will receive the debt in the case of using on `modes` 1 or 2
   * @param params Variadic packed params to pass to the receiver as extra information
   * @param referralCode The 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 flashLoan(
    address receiverAddress,
    address[] calldata assets,
    uint256[] calldata amounts,
    uint256[] calldata interestRateModes,
    address onBehalfOf,
    bytes calldata params,
    uint16 referralCode
  ) external;

  /**
   * @notice Allows smartcontracts to access the liquidity of the pool within one transaction,
   * as long as the amount taken plus a fee is returned.
   * @dev IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept
   * into consideration. For further details please visit https://docs.aave.com/developers/
   * @param receiverAddress The address of the contract receiving the funds, implementing IFlashLoanSimpleReceiver interface
   * @param asset The address of the asset being flash-borrowed
   * @param amount The amount of the asset being flash-borrowed
   * @param params Variadic packed params to pass to the receiver as extra information
   * @param referralCode The 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 flashLoanSimple(
    address receiverAddress,
    address asset,
    uint256 amount,
    bytes calldata params,
    uint16 referralCode
  ) external;

  /**
   * @notice Returns the user account data across all the reserves
   * @param user The address of the user
   * @return totalCollateralBase The total collateral of the user in the base currency used by the price feed
   * @return totalDebtBase The total debt of the user in the base currency used by the price feed
   * @return availableBorrowsBase The borrowing power left of the user in the base currency used by the price feed
   * @return currentLiquidationThreshold The liquidation threshold of the user
   * @return ltv The loan to value of The user
   * @return healthFactor The current health factor of the user
   */
  function getUserAccountData(
    address user
  )
    external
    view
    returns (
      uint256 totalCollateralBase,
      uint256 totalDebtBase,
      uint256 availableBorrowsBase,
      uint256 currentLiquidationThreshold,
      uint256 ltv,
      uint256 healthFactor
    );

  /**
   * @notice Initializes a reserve, activating it, assigning an aToken and debt tokens and an
   * interest rate strategy
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   * @param aTokenAddress The address of the aToken that will be assigned to the reserve
   * @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve
   * @param variableDebtAddress The address of the VariableDebtToken that will be assigned to the reserve
   * @param interestRateStrategyAddress The address of the interest rate strategy contract
   */
  function initReserve(
    address asset,
    address aTokenAddress,
    address stableDebtAddress,
    address variableDebtAddress,
    address interestRateStrategyAddress
  ) external;

  /**
   * @notice Drop a reserve
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   */
  function dropReserve(address asset) external;

  /**
   * @notice Updates the address of the interest rate strategy contract
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   * @param rateStrategyAddress The address of the interest rate strategy contract
   */
  function setReserveInterestRateStrategyAddress(
    address asset,
    address rateStrategyAddress
  ) external;

  /**
   * @notice Sets the configuration bitmap of the reserve as a whole
   * @dev Only callable by the PoolConfigurator contract
   * @param asset The address of the underlying asset of the reserve
   * @param configuration The new configuration bitmap
   */
  function setConfiguration(
    address asset,
    DataTypes.ReserveConfigurationMap calldata configuration
  ) external;

  /**
   * @notice Returns the configuration of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The configuration of the reserve
   */
  function getConfiguration(
    address asset
  ) external view returns (DataTypes.ReserveConfigurationMap memory);

  /**
   * @notice Returns the configuration of the user across all the reserves
   * @param user The user address
   * @return The configuration of the user
   */
  function getUserConfiguration(
    address user
  ) external view returns (DataTypes.UserConfigurationMap memory);

  /**
   * @notice Returns the normalized income of the reserve
   * @param asset The address of the underlying asset of the reserve
   * @return The reserve's normalized income
   */
  function getReserveNormalizedIncome(address asset) external view returns (uint256);

  /**
   * @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 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 (DataTypes.ReserveData memory);

  /**
   * @notice Validates and finalizes an aToken transfer
   * @dev Only callable by the overlying aToken of the `asset`
   * @param asset The address of the underlying asset of the aToken
   * @param from The user from which the aTokens are transferred
   * @param to The user receiving the aTokens
   * @param amount The amount being transferred/withdrawn
   * @param balanceFromBefore The aToken balance of the `from` user before the transfer
   * @param balanceToBefore The aToken balance of the `to` user before the transfer
   */
  function finalizeTransfer(
    address asset,
    address from,
    address to,
    uint256 amount,
    uint256 balanceFromBefore,
    uint256 balanceToBefore
  ) external;

  /**
   * @notice Returns the list of the underlying assets of all the initialized reserves
   * @dev It does not include dropped reserves
   * @return The addresses of the underlying assets of the initialized reserves
   */
  function getReservesList() external view returns (address[] memory);

  /**
   * @notice Returns the address of the underlying asset of a reserve by the reserve id as stored in the DataTypes.ReserveData struct
   * @param id The id of the reserve as stored in the DataTypes.ReserveData struct
   * @return The address of the reserve associated with id
   */
  function getReserveAddressById(uint16 id) external view returns (address);

  /**
   * @notice Returns the PoolAddressesProvider connected to this contract
   * @return The address of the PoolAddressesProvider
   */
  function ADDRESSES_PROVIDER() external view returns (IPoolAddressesProvider);

  /**
   * @notice Updates the protocol fee on the bridging
   * @param bridgeProtocolFee The part of the premium sent to the protocol treasury
   */
  function updateBridgeProtocolFee(uint256 bridgeProtocolFee) external;

  /**
   * @notice Updates flash loan premiums. Flash loan premium consists of two parts:
   * - A part is sent to aToken holders as extra, one time accumulated interest
   * - A part is collected by the protocol treasury
   * @dev The total premium is calculated on the total borrowed amount
   * @dev The premium to protocol is calculated on the total premium, being a percentage of `flashLoanPremiumTotal`
   * @dev Only callable by the PoolConfigurator contract
   * @param flashLoanPremiumTotal The total premium, expressed in bps
   * @param flashLoanPremiumToProtocol The part of the premium sent to the protocol treasury, expressed in bps
   */
  function updateFlashloanPremiums(
    uint128 flashLoanPremiumTotal,
    uint128 flashLoanPremiumToProtocol
  ) external;

  /**
   * @notice Configures a new category for the eMode.
   * @dev In eMode, the protocol allows very high borrowing power to borrow assets of the same category.
   * The category 0 is reserved as it's the default for volatile assets
   * @param id The id of the category
   * @param config The configuration of the category
   */
  function configureEModeCategory(uint8 id, DataTypes.EModeCategory memory config) external;

  /**
   * @notice Returns the data of an eMode category
   * @param id The id of the category
   * @return The configuration data of the category
   */
  function getEModeCategoryData(uint8 id) external view returns (DataTypes.EModeCategory memory);

  /**
   * @notice Allows a user to use the protocol in eMode
   * @param categoryId The id of the category
   */
  function setUserEMode(uint8 categoryId) external;

  /**
   * @notice Returns the eMode the user is using
   * @param user The address of the user
   * @return The eMode id
   */
  function getUserEMode(address user) external view returns (uint256);

  /**
   * @notice Resets the isolation mode total debt of the given asset to zero
   * @dev It requires the given asset has zero debt ceiling
   * @param asset The address of the underlying asset to reset the isolationModeTotalDebt
   */
  function resetIsolationModeTotalDebt(address asset) external;

  /**
   * @notice Returns the percentage of available liquidity that can be borrowed at once at stable rate
   * @return The percentage of available liquidity to borrow, expressed in bps
   */
  function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() external view returns (uint256);

  /**
   * @notice Returns the total fee on flash loans
   * @return The total fee on flashloans
   */
  function FLASHLOAN_PREMIUM_TOTAL() external view returns (uint128);

  /**
   * @notice Returns the part of the bridge fees sent to protocol
   * @return The bridge fee sent to the protocol treasury
   */
  function BRIDGE_PROTOCOL_FEE() external view returns (uint256);

  /**
   * @notice Returns the part of the flashloan fees sent to protocol
   * @return The flashloan fee sent to the protocol treasury
   */
  function FLASHLOAN_PREMIUM_TO_PROTOCOL() external view returns (uint128);

  /**
   * @notice Returns the maximum number of reserves supported to be listed in this Pool
   * @return The maximum number of reserves supported
   */
  function MAX_NUMBER_RESERVES() external view returns (uint16);

  /**
   * @notice Mints the assets accrued through the reserve factor to the treasury in the form of aTokens
   * @param assets The list of reserves for which the minting needs to be executed
   */
  function mintToTreasury(address[] calldata assets) external;

  /**
   * @notice Rescue and transfer tokens locked in this contract
   * @param token The address of the token
   * @param to The address of the recipient
   * @param amount The amount of token to transfer
   */
  function rescueTokens(address token, address to, uint256 amount) external;

  /**
   * @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
   * @dev Deprecated: Use the `supply` function instead
   * @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 deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external;
}

File 3 of 43 : IPoolAddressesProvider.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

/**
 * @title IPoolAddressesProvider
 * @author Aave
 * @notice Defines the basic interface for a Pool Addresses Provider.
 */
interface IPoolAddressesProvider {
  /**
   * @dev Emitted when the market identifier is updated.
   * @param oldMarketId The old id of the market
   * @param newMarketId The new id of the market
   */
  event MarketIdSet(string indexed oldMarketId, string indexed newMarketId);

  /**
   * @dev Emitted when the pool is updated.
   * @param oldAddress The old address of the Pool
   * @param newAddress The new address of the Pool
   */
  event PoolUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the pool configurator is updated.
   * @param oldAddress The old address of the PoolConfigurator
   * @param newAddress The new address of the PoolConfigurator
   */
  event PoolConfiguratorUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the price oracle is updated.
   * @param oldAddress The old address of the PriceOracle
   * @param newAddress The new address of the PriceOracle
   */
  event PriceOracleUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the ACL manager is updated.
   * @param oldAddress The old address of the ACLManager
   * @param newAddress The new address of the ACLManager
   */
  event ACLManagerUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the ACL admin is updated.
   * @param oldAddress The old address of the ACLAdmin
   * @param newAddress The new address of the ACLAdmin
   */
  event ACLAdminUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the price oracle sentinel is updated.
   * @param oldAddress The old address of the PriceOracleSentinel
   * @param newAddress The new address of the PriceOracleSentinel
   */
  event PriceOracleSentinelUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the pool data provider is updated.
   * @param oldAddress The old address of the PoolDataProvider
   * @param newAddress The new address of the PoolDataProvider
   */
  event PoolDataProviderUpdated(address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when a new proxy is created.
   * @param id The identifier of the proxy
   * @param proxyAddress The address of the created proxy contract
   * @param implementationAddress The address of the implementation contract
   */
  event ProxyCreated(
    bytes32 indexed id,
    address indexed proxyAddress,
    address indexed implementationAddress
  );

  /**
   * @dev Emitted when a new non-proxied contract address is registered.
   * @param id The identifier of the contract
   * @param oldAddress The address of the old contract
   * @param newAddress The address of the new contract
   */
  event AddressSet(bytes32 indexed id, address indexed oldAddress, address indexed newAddress);

  /**
   * @dev Emitted when the implementation of the proxy registered with id is updated
   * @param id The identifier of the contract
   * @param proxyAddress The address of the proxy contract
   * @param oldImplementationAddress The address of the old implementation contract
   * @param newImplementationAddress The address of the new implementation contract
   */
  event AddressSetAsProxy(
    bytes32 indexed id,
    address indexed proxyAddress,
    address oldImplementationAddress,
    address indexed newImplementationAddress
  );

  /**
   * @notice Returns the id of the Aave market to which this contract points to.
   * @return The market id
   */
  function getMarketId() external view returns (string memory);

  /**
   * @notice Associates an id with a specific PoolAddressesProvider.
   * @dev This can be used to create an onchain registry of PoolAddressesProviders to
   * identify and validate multiple Aave markets.
   * @param newMarketId The market id
   */
  function setMarketId(string calldata newMarketId) external;

  /**
   * @notice Returns an address by its identifier.
   * @dev The returned address might be an EOA or a contract, potentially proxied
   * @dev It returns ZERO if there is no registered address with the given id
   * @param id The id
   * @return The address of the registered for the specified id
   */
  function getAddress(bytes32 id) external view returns (address);

  /**
   * @notice General function to update the implementation of a proxy registered with
   * certain `id`. If there is no proxy registered, it will instantiate one and
   * set as implementation the `newImplementationAddress`.
   * @dev IMPORTANT Use this function carefully, only for ids that don't have an explicit
   * setter function, in order to avoid unexpected consequences
   * @param id The id
   * @param newImplementationAddress The address of the new implementation
   */
  function setAddressAsProxy(bytes32 id, address newImplementationAddress) external;

  /**
   * @notice Sets an address for an id replacing the address saved in the addresses map.
   * @dev IMPORTANT Use this function carefully, as it will do a hard replacement
   * @param id The id
   * @param newAddress The address to set
   */
  function setAddress(bytes32 id, address newAddress) external;

  /**
   * @notice Returns the address of the Pool proxy.
   * @return The Pool proxy address
   */
  function getPool() external view returns (address);

  /**
   * @notice Updates the implementation of the Pool, or creates a proxy
   * setting the new `pool` implementation when the function is called for the first time.
   * @param newPoolImpl The new Pool implementation
   */
  function setPoolImpl(address newPoolImpl) external;

  /**
   * @notice Returns the address of the PoolConfigurator proxy.
   * @return The PoolConfigurator proxy address
   */
  function getPoolConfigurator() external view returns (address);

  /**
   * @notice Updates the implementation of the PoolConfigurator, or creates a proxy
   * setting the new `PoolConfigurator` implementation when the function is called for the first time.
   * @param newPoolConfiguratorImpl The new PoolConfigurator implementation
   */
  function setPoolConfiguratorImpl(address newPoolConfiguratorImpl) external;

  /**
   * @notice Returns the address of the price oracle.
   * @return The address of the PriceOracle
   */
  function getPriceOracle() external view returns (address);

  /**
   * @notice Updates the address of the price oracle.
   * @param newPriceOracle The address of the new PriceOracle
   */
  function setPriceOracle(address newPriceOracle) external;

  /**
   * @notice Returns the address of the ACL manager.
   * @return The address of the ACLManager
   */
  function getACLManager() external view returns (address);

  /**
   * @notice Updates the address of the ACL manager.
   * @param newAclManager The address of the new ACLManager
   */
  function setACLManager(address newAclManager) external;

  /**
   * @notice Returns the address of the ACL admin.
   * @return The address of the ACL admin
   */
  function getACLAdmin() external view returns (address);

  /**
   * @notice Updates the address of the ACL admin.
   * @param newAclAdmin The address of the new ACL admin
   */
  function setACLAdmin(address newAclAdmin) external;

  /**
   * @notice Returns the address of the price oracle sentinel.
   * @return The address of the PriceOracleSentinel
   */
  function getPriceOracleSentinel() external view returns (address);

  /**
   * @notice Updates the address of the price oracle sentinel.
   * @param newPriceOracleSentinel The address of the new PriceOracleSentinel
   */
  function setPriceOracleSentinel(address newPriceOracleSentinel) external;

  /**
   * @notice Returns the address of the data provider.
   * @return The address of the DataProvider
   */
  function getPoolDataProvider() external view returns (address);

  /**
   * @notice Updates the address of the data provider.
   * @param newDataProvider The address of the new DataProvider
   */
  function setPoolDataProvider(address newDataProvider) external;
}

File 4 of 43 : IPriceOracle.sol
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;

/**
 * @title IPriceOracle
 * @author Aave
 * @notice Defines the basic interface for a Price oracle.
 */
interface IPriceOracle {
  /**
   * @notice Returns the asset price in the base currency
   * @param asset The address of the asset
   * @return The price of the asset
   */
  function getAssetPrice(address asset) external view returns (uint256);

  /**
   * @notice Set the price of the asset
   * @param asset The address of the asset
   * @param price The price of the asset
   */
  function setAssetPrice(address asset, uint256 price) external;
}

File 5 of 43 : DataTypes.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

library DataTypes {
  struct ReserveData {
    //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;
    //the current stable borrow rate. Expressed in ray
    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;
    //stableDebtToken address
    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;
  }

  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: stable rate borrowing enabled
    //bit 60: asset is paused
    //bit 61: borrowing in isolation mode is enabled
    //bit 62-63: reserved
    //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 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-255 unused

    uint256 data;
  }

  struct UserConfigurationMap {
    /**
     * @dev Bitmap of the users collaterals and borrows. It is divided in pairs of bits, one pair per asset.
     * The first bit indicates if an asset is used as collateral by the user, the second whether an
     * asset is borrowed by the user.
     */
    uint256 data;
  }

  struct EModeCategory {
    // each eMode category has a custom ltv and liquidation threshold
    uint16 ltv;
    uint16 liquidationThreshold;
    uint16 liquidationBonus;
    // each eMode category may or may not have a custom oracle to override the individual assets price oracles
    address priceSource;
    string label;
  }

  enum InterestRateMode {NONE, STABLE, VARIABLE}

  struct ReserveCache {
    uint256 currScaledVariableDebt;
    uint256 nextScaledVariableDebt;
    uint256 currPrincipalStableDebt;
    uint256 currAvgStableBorrowRate;
    uint256 currTotalStableDebt;
    uint256 nextAvgStableBorrowRate;
    uint256 nextTotalStableDebt;
    uint256 currLiquidityIndex;
    uint256 nextLiquidityIndex;
    uint256 currVariableBorrowIndex;
    uint256 nextVariableBorrowIndex;
    uint256 currLiquidityRate;
    uint256 currVariableBorrowRate;
    uint256 reserveFactor;
    ReserveConfigurationMap reserveConfiguration;
    address aTokenAddress;
    address stableDebtTokenAddress;
    address variableDebtTokenAddress;
    uint40 reserveLastUpdateTimestamp;
    uint40 stableDebtLastUpdateTimestamp;
  }

  struct ExecuteLiquidationCallParams {
    uint256 reservesCount;
    uint256 debtToCover;
    address collateralAsset;
    address debtAsset;
    address user;
    bool receiveAToken;
    address priceOracle;
    uint8 userEModeCategory;
    address priceOracleSentinel;
  }

  struct ExecuteSupplyParams {
    address asset;
    uint256 amount;
    address onBehalfOf;
    uint16 referralCode;
  }

  struct ExecuteBorrowParams {
    address asset;
    address user;
    address onBehalfOf;
    uint256 amount;
    InterestRateMode interestRateMode;
    uint16 referralCode;
    bool releaseUnderlying;
    uint256 maxStableRateBorrowSizePercent;
    uint256 reservesCount;
    address oracle;
    uint8 userEModeCategory;
    address priceOracleSentinel;
  }

  struct ExecuteRepayParams {
    address asset;
    uint256 amount;
    InterestRateMode interestRateMode;
    address onBehalfOf;
    bool useATokens;
  }

  struct ExecuteWithdrawParams {
    address asset;
    uint256 amount;
    address to;
    uint256 reservesCount;
    address oracle;
    uint8 userEModeCategory;
  }

  struct ExecuteSetUserEModeParams {
    uint256 reservesCount;
    address oracle;
    uint8 categoryId;
  }

  struct FinalizeTransferParams {
    address asset;
    address from;
    address to;
    uint256 amount;
    uint256 balanceFromBefore;
    uint256 balanceToBefore;
    uint256 reservesCount;
    address oracle;
    uint8 fromEModeCategory;
  }

  struct FlashloanParams {
    address receiverAddress;
    address[] assets;
    uint256[] amounts;
    uint256[] interestRateModes;
    address onBehalfOf;
    bytes params;
    uint16 referralCode;
    uint256 flashLoanPremiumToProtocol;
    uint256 flashLoanPremiumTotal;
    uint256 maxStableRateBorrowSizePercent;
    uint256 reservesCount;
    address addressesProvider;
    uint8 userEModeCategory;
    bool isAuthorizedFlashBorrower;
  }

  struct FlashloanSimpleParams {
    address receiverAddress;
    address asset;
    uint256 amount;
    bytes params;
    uint16 referralCode;
    uint256 flashLoanPremiumToProtocol;
    uint256 flashLoanPremiumTotal;
  }

  struct FlashLoanRepaymentParams {
    uint256 amount;
    uint256 totalPremium;
    uint256 flashLoanPremiumToProtocol;
    address asset;
    address receiverAddress;
    uint16 referralCode;
  }

  struct CalculateUserAccountDataParams {
    UserConfigurationMap userConfig;
    uint256 reservesCount;
    address user;
    address oracle;
    uint8 userEModeCategory;
  }

  struct ValidateBorrowParams {
    ReserveCache reserveCache;
    UserConfigurationMap userConfig;
    address asset;
    address userAddress;
    uint256 amount;
    InterestRateMode interestRateMode;
    uint256 maxStableLoanPercent;
    uint256 reservesCount;
    address oracle;
    uint8 userEModeCategory;
    address priceOracleSentinel;
    bool isolationModeActive;
    address isolationModeCollateralAddress;
    uint256 isolationModeDebtCeiling;
  }

  struct ValidateLiquidationCallParams {
    ReserveCache debtReserveCache;
    uint256 totalDebt;
    uint256 healthFactor;
    address priceOracleSentinel;
  }

  struct CalculateInterestRatesParams {
    uint256 unbacked;
    uint256 liquidityAdded;
    uint256 liquidityTaken;
    uint256 totalStableDebt;
    uint256 totalVariableDebt;
    uint256 averageStableBorrowRate;
    uint256 reserveFactor;
    address reserve;
    address aToken;
  }

  struct InitReserveParams {
    address asset;
    address aTokenAddress;
    address stableDebtAddress;
    address variableDebtAddress;
    address interestRateStrategyAddress;
    uint16 reservesCount;
    uint16 maxNumberReserves;
  }
}

File 6 of 43 : AggregatorV3Interface.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}

File 7 of 43 : draft-IERC1822Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)

pragma solidity ^0.8.0;

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

File 8 of 43 : IBeaconUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.0;

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

File 9 of 43 : ERC1967UpgradeUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)

pragma solidity ^0.8.2;

import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";

/**
 * @dev This abstract contract provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
 *
 * _Available since v4.1._
 *
 * @custom:oz-upgrades-unsafe-allow delegatecall
 */
abstract contract ERC1967UpgradeUpgradeable is Initializable {
    function __ERC1967Upgrade_init() internal onlyInitializing {
    }

    function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
    }
    // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
    bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Returns the current implementation address.
     */
    function _getImplementation() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
        StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Perform implementation upgrade
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeTo(address newImplementation) internal {
        _setImplementation(newImplementation);
        emit Upgraded(newImplementation);
    }

    /**
     * @dev Perform implementation upgrade with additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCall(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        _upgradeTo(newImplementation);
        if (data.length > 0 || forceCall) {
            _functionDelegateCall(newImplementation, data);
        }
    }

    /**
     * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
     *
     * Emits an {Upgraded} event.
     */
    function _upgradeToAndCallUUPS(
        address newImplementation,
        bytes memory data,
        bool forceCall
    ) internal {
        // Upgrades from old implementations will perform a rollback test. This test requires the new
        // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
        // this special case will break upgrade paths from old UUPS implementation to new ones.
        if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
            _setImplementation(newImplementation);
        } else {
            try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
                require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
            } catch {
                revert("ERC1967Upgrade: new implementation is not UUPS");
            }
            _upgradeToAndCall(newImplementation, data, forceCall);
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
     * validated in the constructor.
     */
    bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

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

    /**
     * @dev Returns the current admin.
     */
    function _getAdmin() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the EIP1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        require(newAdmin != address(0), "ERC1967: new admin is the zero address");
        StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
    }

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

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
     */
    bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

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

    /**
     * @dev Returns the current beacon.
     */
    function _getBeacon() internal view returns (address) {
        return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the EIP1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
        require(
            AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
            "ERC1967: beacon implementation is not a contract"
        );
        StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
    }

    /**
     * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
     * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
     *
     * Emits a {BeaconUpgraded} event.
     */
    function _upgradeBeaconToAndCall(
        address newBeacon,
        bytes memory data,
        bool forceCall
    ) internal {
        _setBeacon(newBeacon);
        emit BeaconUpgraded(newBeacon);
        if (data.length > 0 || forceCall) {
            _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
        require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
    }

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

File 10 of 43 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.1) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

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

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

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

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

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

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

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

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

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

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

File 11 of 43 : UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.0;

import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * _Available since v4.1._
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
    address private immutable __self = address(this);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        require(address(this) != __self, "Function must be called through delegatecall");
        require(_getImplementation() == __self, "Function must be called through active proxy");
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
        _;
    }

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

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     */
    function upgradeTo(address newImplementation) external virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data, true);
    }

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

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

File 12 of 43 : PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

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

File 13 of 43 : ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

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

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

    uint256 private _status;

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

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _status = _NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

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

File 14 of 43 : ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    mapping(address => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

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

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

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

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

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

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

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

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

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

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

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

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

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

File 15 of 43 : draft-IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

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

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

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

File 16 of 43 : IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

File 17 of 43 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 18 of 43 : SafeERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";
import "../extensions/draft-IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";

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

    function safeTransfer(
        IERC20Upgradeable token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20Upgradeable token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

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

    function safeIncreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20Upgradeable token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    function safePermit(
        IERC20PermitUpgradeable token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

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

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

File 19 of 43 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

File 20 of 43 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../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;
    }

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

File 21 of 43 : SafeCastUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCastUpgradeable {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 22 of 43 : StorageSlotUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)

pragma solidity ^0.8.0;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

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

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

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

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

File 23 of 43 : IUniswapV3MintCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
    function uniswapV3MintCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external;
}

File 24 of 43 : IUniswapV3SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

File 25 of 43 : IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}

File 26 of 43 : IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

File 27 of 43 : IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

File 28 of 43 : IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

File 29 of 43 : IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

File 30 of 43 : IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

File 31 of 43 : IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

File 32 of 43 : FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

File 33 of 43 : OwnableUpgradeable.sol
// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.4;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an manager) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the manager account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyManager`, which can be applied to your functions to restrict their use to
 * the manager.
 */
contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _manager;

    event OwnershipTransferred(address indexed previousManager, address indexed newManager);

    /**
     * @dev Initializes the contract setting the deployer as the initial manager.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the manager.
     */
    modifier onlyManager() {
        _checkManager();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the manager.
     */
    function _checkManager() internal view virtual {
        require(manager() == _msgSender(), "Ownable: caller is not the manager");
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newManager`).
     * Can only be called by the current manager.
     */
    function transferOwnership(address newManager) public virtual onlyManager {
        require(newManager != address(0), "Ownable: new manager is the zero address");
        _transferOwnership(newManager);
    }

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

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

File 34 of 43 : VaultErrors.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

library VaultErrors {
    error NotAllowedToUpdateTicks();
    error InvalidManagingFee();
    error InvalidPerformanceFee();
    error OnlyPoolAllowed();
    error InvalidCollateralAmount();
    error InvalidBurnAmount();
    error TicksOutOfRange();
    error InvalidTicksSpacing();
    error OnlyFactoryAllowed();
    error LiquidityAlreadyAdded();
    error OnlyVaultAllowed();
    error PriceNotWithinThreshold();
    error PoolRepegFailed();
    error DebtGreaterThanAssets();
    error OraclePriceIsOutdated(address oracle);
    error ZeroManagerAddress();
    error TokenZeroIsNotGHO();
    error SlippageExceedThreshold();
    error InsufficientBalanceForShares();
}

File 35 of 43 : IPriceOracleExtended.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {IPriceOracle} from "@aave/core-v3/contracts/interfaces/IPriceOracle.sol";

interface IPriceOracleExtended is IPriceOracle {
    function BASE_CURRENCY_UNIT() external view returns (uint256);
}

File 36 of 43 : IRangeProtocolVault.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IUniswapV3MintCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import {DataTypesLib} from "../libraries/DataTypesLib.sol";
import {IRangeProtocolVaultGetters} from "./IRangeProtocolVaultGetters.sol";

interface IRangeProtocolVault is
    IERC20Upgradeable,
    IUniswapV3MintCallback,
    IUniswapV3SwapCallback,
    IRangeProtocolVaultGetters
{
    event Minted(address indexed receiver, uint256 shares, uint256 amount);
    event Burned(address indexed receiver, uint256 burnAmount, uint256 amount);
    event LiquidityAdded(
        uint256 liquidityMinted,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0In,
        uint256 amount1In
    );
    event LiquidityRemoved(
        uint256 liquidityRemoved,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Out,
        uint256 amount1Out
    );
    event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
    event FeesUpdated(uint16 managingFee, uint16 performanceFee);
    event InThePositionStatusSet(bool inThePosition);
    event Swapped(bool zeroForOne, int256 amount0, int256 amount1);
    event TicksSet(int24 lowerTick, int24 upperTick);
    event CollateralSupplied(address token, uint256 amount);
    event CollateralWithdrawn(address token, uint256 amount);
    event GHOMinted(uint256 amount);
    event GHOBurned(uint256 amount);
    event PoolRepegged();
    event OraclesHeartbeatUpdated(uint256 collateralOracleHearbeat, uint256 ghoOracleHeartbreat);

    // @notice intializes the vault.
    function initialize(address _pool, int24 _tickSpacing, bytes memory data) external;

    // @notice mints vault shares to users by accepting the liquidity in collateral token.
    function mint(uint256 amount, uint256 minShares) external returns (uint256 shares);

    // @notice burns vault shares from user and returns then their share in collateral token.
    function burn(uint256 burnAmount, uint256 minAmount) external returns (uint256 amount);

    // @notice mints shares to users. Only callable by the vault contract through library.
    function mintShares(address to, uint256 shares) external;

    // @notice burns shares from users. Only callable by the vault contract through library.
    function burnShares(address from, uint256 shares) external;

    // @notice removes liquidity from the vault. Only callable by vault manager.
    function removeLiquidity(uint256[2] calldata minAmounts) external;

    // @notice swaps token0 to token1 and vice-versa within the vault. Only callable by vault manager.
    function swap(
        bool zeroForOne,
        int256 swapAmount,
        uint160 sqrtPriceLimitX96,
        uint256 minAmountIn
    ) external returns (int256 amount0, int256 amount1);

    // @notice adds liquidity to newer tick range. Only callable by vault manager.
    function addLiquidity(
        int24 newLowerTick,
        int24 newUpperTick,
        uint256 amount0,
        uint256 amount1,
        uint256[2] calldata maxAmounts
    ) external returns (uint256 remainingAmount0, uint256 remainingAmount1);

    // @notice collects manager fee by manager. Only callable by vault manager.
    function collectManager() external;

    // @notice updates fees percentages. Only callable by the vault manager.
    function updateFees(uint16 newManagingFee, uint16 newPerformanceFee) external;

    // @notice supplies collateral to Aave in collateral token.
    function supplyCollateral(uint256 supplyAmount) external;

    // @notice withdraws collateral from Aave in collateral token.
    function withdrawCollateral(uint256 withdrawAmount) external;

    // @notice borrows GHO token from Aave.
    function mintGHO(uint256 mintAmount) external;

    // @notice payback the debt in GHO token to Aave.
    function burnGHO(uint256 burnAmount) external;

    // @notice multicall function to repeg the AMM pool.
    function repegPool(bytes[] memory calldatas) external returns (bytes[] memory returndatas);

    // @notice updates the hearbeat duration of collateral and gho price oracles.
    function updatePriceOracleHeartbeatsDuration(
        uint256 collateralOracleHBDuration,
        uint256 ghoOracleHBDuration
    ) external;
}

File 37 of 43 : IRangeProtocolVaultGetters.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {DataTypesLib} from "../libraries/DataTypesLib.sol";

interface IRangeProtocolVaultGetters {
    // @return address of range protocol factory.
    function factory() external view returns (address);

    // @return address of AMM pool for which vault is created.
    function pool() external view returns (IUniswapV3Pool);

    // @return address of token0.
    function token0() external view returns (IERC20Upgradeable);

    // @return address of token1.
    function token1() external view returns (IERC20Upgradeable);

    // @return lower tick of the vault position.
    function lowerTick() external view returns (int24);

    // @return upper tick of the vault position.
    function upperTick() external view returns (int24);

    // @return space between two ticks.
    function tickSpacing() external view returns (int24);

    // @return true if the vault has an opened position in the AMM pool.
    function inThePosition() external view returns (bool);

    // @return returns managing fee percentage out of 10_000.
    function managingFee() external view returns (uint16);

    // @return returns performance fee percentage out of 10_000.
    function performanceFee() external view returns (uint16);

    // @return returns manager balance in token.
    function managerBalance() external view returns (uint256);

    // @return returns user's vault exposure in token0 and token1.
    function userVaults(address user) external view returns (DataTypesLib.UserVault memory);

    // @return returns total count of the user.
    function userCount() external view returns (uint256);

    // @return returns address of the user at {index} position in the users array.
    function users(uint256 index) external view returns (address);

    // @return address of the pool addresses provider.
    function poolAddressesProvider() external view returns (address);

    // @return address of gho token.
    function gho() external view returns (address);

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

    // @notice returns collateral deposited to Aave in collateral token and debt owed in gho.
    function getUnderlyingBalancesFromAave() external view returns (uint256, uint256);

    // @notice returns the underlying balance of vault in collateral token.
    function getBalanceInCollateralToken() external view returns (uint256 amount);

    // @notice returns gho and collateral balances from uni pool.
    function getUnderlyingBalancesFromPool() external view returns (uint256, uint256);

    // @notice returns the underlying balance based on the amount of {shares}.
    function getUnderlyingBalanceByShare(uint256 shares) external view returns (uint256 amount);

    // @notice returns currently unclaimed fee in the contract.
    function getCurrentFees() external view returns (uint256 fee0, uint256 fee1);

    // @notice returns current position id of the contract.
    function getPositionID() external view returns (bytes32 positionID);

    // @notice returns users vaults based on the passed indexes.
    function getUserVaults(uint256 fromIdx, uint256 toIdx) external view returns (DataTypesLib.UserVaultInfo[] memory);
}

File 38 of 43 : DataTypesLib.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IPoolAddressesProvider} from "@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol";

library DataTypesLib {
    struct UserVault {
        bool exists;
        uint256 token;
    }

    struct UserVaultInfo {
        address user;
        uint256 token;
    }

    struct PriceOracle {
        AggregatorV3Interface priceFeed;
        uint256 heartbeatDuration;
    }

    struct State {
        address factory;
        IUniswapV3Pool pool;
        IERC20Upgradeable token0;
        IERC20Upgradeable token1;
        int24 lowerTick;
        int24 upperTick;
        int24 tickSpacing;
        bool inThePosition;
        uint8 decimals0;
        uint8 decimals1;
        uint8 vaultDecimals;
        uint16 managingFee;
        uint16 performanceFee;
        uint256 managerBalance;
        IPoolAddressesProvider poolAddressesProvider;
        PriceOracle collateralPriceOracle;
        PriceOracle ghoPriceOracle;
        mapping(address => UserVault) vaults;
        address[] users;
    }
}

File 39 of 43 : LogicLib.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IERC20MetadataUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import {SafeCastUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import {IPool} from "@aave/core-v3/contracts/interfaces/IPool.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {LiquidityAmounts} from "../uniswap/LiquidityAmounts.sol";
import {FullMath} from "../uniswap/FullMath.sol";
import {TickMath} from "../uniswap/TickMath.sol";
import {DataTypesLib} from "./DataTypesLib.sol";
import {IRangeProtocolVault} from "../interfaces/IRangeProtocolVault.sol";
import {IPriceOracleExtended} from "../interfaces/IPriceOracleExtended.sol";
import {VaultErrors} from "../errors/VaultErrors.sol";

/**
 * @notice LogicLib library contains the implementation logic of vault. It accepts DataTypesLib.State struct to
 * access vault state.
 */
library LogicLib {
    using SafeERC20Upgradeable for IERC20Upgradeable;
    using TickMath for int24;

    /// Performance fee cannot be set more than 20% of the fee earned from uniswap v3 pool.
    uint16 public constant MAX_PERFORMANCE_FEE_BPS = 2000;

    /// Managing fee cannot be set more than 1% of the total fee earned.
    uint16 public constant MAX_MANAGING_FEE_BPS = 100;

    event Minted(address indexed receiver, uint256 shares, uint256 amount);
    event Burned(address indexed receiver, uint256 burnAmount, uint256 amount);
    event LiquidityAdded(
        uint256 liquidityMinted,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0In,
        uint256 amount1In
    );
    event LiquidityRemoved(
        uint256 liquidityRemoved,
        int24 tickLower,
        int24 tickUpper,
        uint256 amount0Out,
        uint256 amount1Out
    );
    event FeesEarned(uint256 feesEarned0, uint256 feesEarned1);
    event FeesUpdated(uint16 managingFee, uint16 performanceFee);
    event InThePositionStatusSet(bool inThePosition);
    event Swapped(bool zeroForOne, int256 amount0, int256 amount1);
    event TicksSet(int24 lowerTick, int24 upperTick);
    event CollateralSupplied(address token, uint256 amount);
    event CollateralWithdrawn(address token, uint256 amount);
    event GHOMinted(uint256 amount);
    event GHOBurned(uint256 amount);
    event OraclesHeartbeatUpdated(uint256 collateralOracleHearbeat, uint256 ghoOracleHeartbreat);

    // @notice uniswapV3 mint callback implementation.
    // @param amount0Owed amount in token0 to transfer.
    // @param amount1Owed amount in token1 to transfer.
    function uniswapV3MintCallback(
        DataTypesLib.State storage state,
        uint256 amount0Owed,
        uint256 amount1Owed
    ) external {
        if (msg.sender != address(state.pool)) revert VaultErrors.OnlyPoolAllowed();
        if (amount0Owed > 0) state.token0.safeTransfer(msg.sender, amount0Owed);
        if (amount1Owed > 0) state.token1.safeTransfer(msg.sender, amount1Owed);
    }

    // @notice uniswapV3 swap callback implementation.
    // @param amount0Delta amount0 added (+) or to be taken (-) from the vault.
    // @param amount1Delta amount1 added (+) or to be taken (-) from the vault.
    function uniswapV3SwapCallback(
        DataTypesLib.State storage state,
        int256 amount0Delta,
        int256 amount1Delta
    ) external {
        if (msg.sender != address(state.pool)) revert VaultErrors.OnlyPoolAllowed();
        if (amount0Delta > 0) state.token0.safeTransfer(msg.sender, uint256(amount0Delta));
        else if (amount1Delta > 0) state.token1.safeTransfer(msg.sender, uint256(amount1Delta));
    }

    // @notice called by the user with collateral amount to provide liquidity in collateral amount. The mint must fail
    // if the gho price is not within threshold of 0.5%.
    // @param amount the amount of collateral to provide.
    // @param minShares the minimum shares to mint.
    // @return shares the amount of shares minted.
    function mint(
        DataTypesLib.State storage state,
        uint256 amount,
        uint256 minShares
    ) external returns (uint256 shares) {
        if (amount == 0) revert VaultErrors.InvalidCollateralAmount();
        _validatePriceThreshold(state);
        IRangeProtocolVault vault = IRangeProtocolVault(address(this));
        uint256 totalSupply = vault.totalSupply();
        if (totalSupply != 0) {
            uint256 totalAmount = getBalanceInCollateralToken(state);
            // rounding up the shares to prevent the inflation attack.
            shares = FullMath.mulDivRoundingUp(amount, totalSupply, totalAmount);
        } else {
            shares = amount;
        }

        if (shares < minShares) revert VaultErrors.InsufficientBalanceForShares();
        vault.mintShares(msg.sender, shares);
        if (!state.vaults[msg.sender].exists) {
            state.vaults[msg.sender].exists = true;
            state.users.push(msg.sender);
        }
        state.vaults[msg.sender].token += amount;
        IERC20Upgradeable(vault.collateralToken()).safeTransferFrom(msg.sender, address(this), amount);
        emit Minted(msg.sender, shares, amount);
    }

    // @notice called by the user with share amount to burn their vault shares redeem their share of the asset. The burn
    // must fail if the gho price is not within threshold of 0.5%.
    // @param burnAmount the amount of vault shares to burn.
    // @return shares the amount of assets in collateral token received by the user.
    function burn(
        DataTypesLib.State storage state,
        uint256 shares,
        uint256 minAmount
    ) external returns (uint256 amount) {
        if (shares == 0) revert VaultErrors.InvalidBurnAmount();
        _validatePriceThreshold(state);
        IRangeProtocolVault vault = IRangeProtocolVault(address(this));
        uint256 totalSupply = vault.totalSupply();
        uint256 balanceBefore = vault.balanceOf(msg.sender);
        vault.burnShares(msg.sender, shares);

        uint256 underlyingAmountInCollateralToken = getBalanceInCollateralToken(state);
        amount = FullMath.mulDiv(underlyingAmountInCollateralToken, shares, totalSupply);

        if (amount < minAmount) revert VaultErrors.SlippageExceedThreshold();

        _applyManagingFee(state, amount);
        amount = _netManagingFees(state, amount);
        state.vaults[msg.sender].token = (state.vaults[msg.sender].token * (balanceBefore - shares)) / balanceBefore;

        IERC20Upgradeable(vault.collateralToken()).safeTransfer(msg.sender, amount);
        emit Burned(msg.sender, shares, amount);
    }

    // @notice called by manager to remove liquidity from the pool.
    function removeLiquidity(DataTypesLib.State storage state, uint256[2] calldata minAmounts) external {
        (uint128 liquidity, , , , ) = state.pool.positions(getPositionID(state));
        if (liquidity != 0) {
            (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) = _withdraw(state, liquidity);
            if (amount0 < minAmounts[0] || amount1 < minAmounts[1]) revert VaultErrors.SlippageExceedThreshold();

            emit LiquidityRemoved(liquidity, state.lowerTick, state.upperTick, amount0, amount1);

            _applyPerformanceFee(state, fee0, fee1);
            (fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
            emit FeesEarned(fee0, fee1);
        }

        state.lowerTick = state.upperTick;
        state.inThePosition = false;
        emit InThePositionStatusSet(false);
    }

    // @notice called by manager to perform swap from token0 to token1 and vice-versa.
    // @param zeroForOne swap direction (true -> x to y) or (false -> y to x)
    // @param swapAmount amount to swap (+ve -> exact in, -ve exact out)
    // @param sqrtPriceLimitX96 the limit pool price can move when filling the order.
    // @param amount0 amount0 added (+) or to be taken (-) from the vault.
    // @param amount1 amount1 added (+) or to be taken (-) from the vault.
    function swap(
        DataTypesLib.State storage state,
        bool zeroForOne,
        int256 swapAmount,
        uint160 sqrtPriceLimitX96,
        uint256 minAmountIn
    ) external returns (int256 amount0, int256 amount1) {
        (amount0, amount1) = state.pool.swap(address(this), zeroForOne, swapAmount, sqrtPriceLimitX96, "");

        if ((zeroForOne && uint256(-amount1) < minAmountIn) || (!zeroForOne && uint256(-amount0) < minAmountIn))
            revert VaultErrors.SlippageExceedThreshold();

        emit Swapped(zeroForOne, amount0, amount1);
    }

    // @notice called by manager to provide liquidity to pool into a newer tick range.
    // @param newLowerTick lower tick of the position.
    // @param newUpperTick upper tick of the position.
    // @param amount0 amount in token0 to add.
    // @param amount1 amount in token1 to add.
    // @param maxAmounts min amounts to add for slippage protection.
    // @return remainingAmount0 amount in token0 left passive in the vault.
    // @return remainingAmount1 amount in token1 left passive in the vault.
    function addLiquidity(
        DataTypesLib.State storage state,
        int24 newLowerTick,
        int24 newUpperTick,
        uint256 amount0,
        uint256 amount1,
        uint256[2] calldata maxAmounts
    ) external returns (uint256 remainingAmount0, uint256 remainingAmount1) {
        if (state.inThePosition) revert VaultErrors.LiquidityAlreadyAdded();
        _validateTicks(newLowerTick, newUpperTick, state.tickSpacing);
        (uint160 sqrtRatioX96, , , , , , ) = state.pool.slot0();
        uint128 baseLiquidity = LiquidityAmounts.getLiquidityForAmounts(
            sqrtRatioX96,
            newLowerTick.getSqrtRatioAtTick(),
            newUpperTick.getSqrtRatioAtTick(),
            amount0,
            amount1
        );
        if (baseLiquidity > 0) {
            (uint256 amountDeposited0, uint256 amountDeposited1) = state.pool.mint(
                address(this),
                newLowerTick,
                newUpperTick,
                baseLiquidity,
                ""
            );
            if (amountDeposited0 > maxAmounts[0] || amountDeposited1 > maxAmounts[1])
                revert VaultErrors.SlippageExceedThreshold();

            emit LiquidityAdded(baseLiquidity, newLowerTick, newUpperTick, amountDeposited0, amountDeposited1);

            remainingAmount0 = amount0 - amountDeposited0;
            remainingAmount1 = amount1 - amountDeposited1;
            state.lowerTick = newLowerTick;
            state.upperTick = newUpperTick;
            emit TicksSet(newLowerTick, newUpperTick);

            state.inThePosition = true;
            emit InThePositionStatusSet(true);
        }
    }

    // @notice called by manager to transfer the unclaimed fee from pool to the vault.
    function pullFeeFromPool(DataTypesLib.State storage state) public {
        (, , uint256 fee0, uint256 fee1) = _withdraw(state, 0);
        _applyPerformanceFee(state, fee0, fee1);
        (fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
        emit FeesEarned(fee0, fee1);
    }

    // @notice called by manager to collect fee from the vault.
    function collectManager(DataTypesLib.State storage state, address manager) external {
        uint256 balance = state.managerBalance;
        state.managerBalance = 0;

        if (balance != 0) state.token1.safeTransfer(manager, balance);
    }

    // @notice called by the manager to update the fees.
    // @param newManagingFee new managing fee percentage out of 10_000.
    // @param newPerformanceFee new performance fee percentage out of 10_000.
    function updateFees(DataTypesLib.State storage state, uint16 newManagingFee, uint16 newPerformanceFee) external {
        if (newManagingFee > MAX_MANAGING_FEE_BPS) revert VaultErrors.InvalidManagingFee();
        if (newPerformanceFee > MAX_PERFORMANCE_FEE_BPS) revert VaultErrors.InvalidPerformanceFee();

        // only pull existing fee if the vault already has a position opened in the pool.
        if (state.inThePosition) pullFeeFromPool(state);
        state.managingFee = newManagingFee;
        state.performanceFee = newPerformanceFee;
        emit FeesUpdated(newManagingFee, newPerformanceFee);
    }

    // @notice updates the hearbeat duration of collateral and gho price oracles.
    // @param collateralOracleHBDuration heartbeat duration for collateral price oracle.
    // @param ghoOracleHBDuration heartbeat duration for gho price oracle.
    function updatePriceOracleHeartbeatsDuration(
        DataTypesLib.State storage state,
        uint256 collateralOracleHBDuration,
        uint256 ghoOracleHBDuration
    ) external {
        state.collateralPriceOracle.heartbeatDuration = collateralOracleHBDuration;
        state.ghoPriceOracle.heartbeatDuration = ghoOracleHBDuration;

        emit OraclesHeartbeatUpdated(collateralOracleHBDuration, ghoOracleHBDuration);
    }

    // @notice supplied collateral to Aave. Called by manager only.
    // @param supplyAmount amount of collateral to supply.
    function supplyCollateral(DataTypesLib.State storage state, uint256 supplyAmount) external {
        IPool aavePool = IPool(state.poolAddressesProvider.getPool());
        IERC20Upgradeable collateralToken = IERC20Upgradeable(IRangeProtocolVault(address(this)).collateralToken());
        collateralToken.safeApprove(address(aavePool), 0);
        collateralToken.safeApprove(address(aavePool), supplyAmount);
        aavePool.supply(address(collateralToken), supplyAmount, address(this), 0);
        emit CollateralSupplied(address(collateralToken), supplyAmount);
    }

    // @notice withdraws collateral from Aave. Called by manager only.
    // @param withdrawAmount amount of collateral to withdraw.
    function withdrawCollateral(DataTypesLib.State storage state, uint256 withdrawAmount) external {
        address collateralToken = IRangeProtocolVault(address(this)).collateralToken();
        IPool(state.poolAddressesProvider.getPool()).withdraw(collateralToken, withdrawAmount, address(this));
        emit CollateralWithdrawn(collateralToken, withdrawAmount);
    }

    // @notice borrows GHO token from Aave. Called by manager only.
    // @param mint amount of GHO to mint.
    function mintGHO(DataTypesLib.State storage state, uint256 mintAmount) external {
        uint256 interestRateMode = 2; // open debt at a variable rate
        IPool(state.poolAddressesProvider.getPool()).borrow(
            IRangeProtocolVault(address(this)).gho(),
            mintAmount,
            interestRateMode,
            0,
            address(this)
        );
        emit GHOMinted(mintAmount);
    }

    // @notice payback GHO debt to Aave. Called by manager only.
    // @param burnAmount amount of GHO debt to payback.
    function burnGHO(DataTypesLib.State storage state, uint256 burnAmount) external {
        IPool aavePool = IPool(state.poolAddressesProvider.getPool());
        IERC20Upgradeable gho = IERC20Upgradeable(IRangeProtocolVault(address(this)).gho());
        gho.safeApprove(address(aavePool), burnAmount);
        uint256 interestRateMode = 2; // remove debt opened at a variable rate.
        aavePool.repay(address(gho), burnAmount, interestRateMode, address(this));
        emit GHOBurned(burnAmount);
    }

    /**
     * @notice returns current unclaimed fees from the pool. Calls getCurrentFees on the LogicLib.
     * @return fee0 fee in token0
     * @return fee1 fee in token1
     */
    function getCurrentFees(DataTypesLib.State storage state) external view returns (uint256 fee0, uint256 fee1) {
        (
            uint128 liquidity,
            uint256 feeGrowthInside0Last,
            uint256 feeGrowthInside1Last,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        ) = state.pool.positions(getPositionID(state));
        (, int24 tick, , , , , ) = state.pool.slot0();
        fee0 = _feesEarned(state, true, feeGrowthInside0Last, tick, liquidity) + uint256(tokensOwed0);
        fee1 = _feesEarned(state, false, feeGrowthInside1Last, tick, liquidity) + uint256(tokensOwed1);
        (fee0, fee1) = _netPerformanceFees(state, fee0, fee1);
    }

    /**
     * @notice returns user vaults based on the provided index. Calls getUserVaults on LogicLib.
     * @param fromIdx the starting index to fetch users.
     * @param toIdx the ending index to fetch users.
     * @return UserVaultInfo
     */
    function getUserVaults(
        DataTypesLib.State storage state,
        uint256 fromIdx,
        uint256 toIdx
    ) external view returns (DataTypesLib.UserVaultInfo[] memory) {
        if (fromIdx == 0 && toIdx == 0) {
            toIdx = state.users.length;
        }
        DataTypesLib.UserVaultInfo[] memory usersVaultInfo = new DataTypesLib.UserVaultInfo[](toIdx - fromIdx);
        uint256 count;
        for (uint256 i = fromIdx; i < toIdx; i++) {
            DataTypesLib.UserVault memory userVault = state.vaults[state.users[i]];
            usersVaultInfo[count++] = DataTypesLib.UserVaultInfo({user: state.users[i], token: userVault.token});
        }
        return usersVaultInfo;
    }

    // @notice returns position id of the vault in pool.
    // @return positionId the id of the position in pool.
    function getPositionID(DataTypesLib.State storage state) public view returns (bytes32 positionID) {
        return keccak256(abi.encodePacked(address(this), state.lowerTick, state.upperTick));
    }

    struct LocalVars {
        uint256 amount0FromPool;
        uint256 amount1FromPool;
        uint256 amount0FromAave;
        uint256 amount1FromAave;
        int256 token0Balance;
        int256 token1Balance;
    }

    // @notice returns vault asset's balance in collateral token. It gets balances from the following three places.
    // Gets token0 and token1 balance from the AMM pool. Converts gho token amount to collateral token.
    // Gets collateral deposited to Aave and gho borrowed. Subtracts borrowed gho amount converted to collateral from
    // collateral amount.
    // Gets collateral and gho amounts sitting passive in the contract.
    // If the gho debt in Aave is greater than gho balance in AMM pool + gho balance passive in the contract then deficit
    // in gho is converted to collateral token and subtracted from the collateral amount to account for the gho deficit.
    // Additionally, to avoid underflow the managerBalance is only subtracted from the vault balance if it is less than the
    // vault balance.
    // @return amount the amount of vault holding converted to collateral token.
    function getBalanceInCollateralToken(DataTypesLib.State storage state) public view returns (uint256 amount) {
        (uint160 sqrtRatioX96, int24 tick, , , , , ) = state.pool.slot0();
        LocalVars memory vars;
        (vars.amount0FromPool, vars.amount1FromPool) = getUnderlyingBalancesFromPool(state, sqrtRatioX96, tick);
        (vars.amount0FromAave, vars.amount1FromAave) = getUnderlyingBalancesFromAave(state);

        // We token0 is always going to be GHO since the GHO will only be created with USDC, DAI and LUSD tokens and
        // these tokens' addresses' uint256 representation on Ethereum mainnet is greater than GHO's address representation.
        vars.token0Balance =
            int256(vars.amount0FromPool + state.token0.balanceOf(address(this))) -
            int256(vars.amount0FromAave);

        vars.token1Balance = int256(
            vars.amount1FromPool + state.token1.balanceOf(address(this)) + vars.amount1FromAave
        );

        (, int256 collateralPrice, , , ) = state.collateralPriceOracle.priceFeed.latestRoundData();
        (, int256 ghoPrice, , , ) = state.ghoPriceOracle.priceFeed.latestRoundData();

        int256 amountSigned = vars.token1Balance +
            ((vars.token0Balance * ghoPrice * int256(10 ** state.decimals1)) /
                collateralPrice /
                int256(10 ** state.decimals0));

        if (amountSigned < 0) revert VaultErrors.DebtGreaterThanAssets();
        amount = uint256(amountSigned);

        // if the underlying asset amount is greater than manager balance then subtract it from the underlying balance.
        if (amount > state.managerBalance) amount -= state.managerBalance;
    }

    // @notice returns underlying balance in collateral token based on the shares amount passed.
    // @param shares amount of vault to calculate the redeemable amount against.
    // @return amount the amount of asset in collateral token redeemable against the provided amount of collateral.
    function getUnderlyingBalanceByShare(
        DataTypesLib.State storage state,
        uint256 shares
    ) external view returns (uint256 amount) {
        uint256 _totalSupply = IRangeProtocolVault(address(this)).totalSupply();
        if (_totalSupply != 0) {
            uint256 totalUnderlyingBalanceInCollateralToken = getBalanceInCollateralToken(state);
            amount = (shares * totalUnderlyingBalanceInCollateralToken) / _totalSupply;
            amount = _netManagingFees(state, amount);
        }
    }

    // @notice returns amount0 and amount1 from the AMM pool.
    // @param amount0 the amount in token0 from AMM pool.
    // @param amount1 the amount in token1 from AMM pool.
    function getUnderlyingBalancesFromPool(
        DataTypesLib.State storage state,
        uint160 sqrtRatioX96,
        int24 tick
    ) public view returns (uint256 amount0, uint256 amount1) {
        (
            uint128 liquidity,
            uint256 feeGrowthInside0Last,
            uint256 feeGrowthInside1Last,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        ) = state.pool.positions(getPositionID(state));
        if (liquidity != 0) {
            (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
                sqrtRatioX96,
                state.lowerTick.getSqrtRatioAtTick(),
                state.upperTick.getSqrtRatioAtTick(),
                liquidity
            );
            uint256 fee0 = _feesEarned(state, true, feeGrowthInside0Last, tick, liquidity) + uint256(tokensOwed0);
            uint256 fee1 = _feesEarned(state, false, feeGrowthInside1Last, tick, liquidity) + uint256(tokensOwed1);
            (fee0, fee1) = _netPerformanceFees(state, fee0, fee1);

            amount0 += fee0;
            amount1 += fee1;
        }
    }

    // @notice returns the supplied collateral and borrowed from Aave.
    // @param amount0 collateral supplied to Aave if token0 is collateral token else gho amount borrowed.
    // @param amount1 collateral supplied to Aave if token1 is collateral token else gho amount borrowed.
    function getUnderlyingBalancesFromAave(
        DataTypesLib.State storage state
    ) public view returns (uint256 amount0, uint256 amount1) {
        (uint256 totalCollateralBase, uint256 totalDebtBase, , , , ) = getAavePositionData(state);

        uint256 BASE_CURRENCY_UNIT = IPriceOracleExtended(state.poolAddressesProvider.getPriceOracle())
            .BASE_CURRENCY_UNIT();

        (, int256 collateralPrice, , , ) = state.collateralPriceOracle.priceFeed.latestRoundData();
        amount0 = (totalDebtBase * 10 ** state.decimals0) / BASE_CURRENCY_UNIT;
        amount1 =
            (totalCollateralBase * 10 ** state.decimals1 * 10 ** state.collateralPriceOracle.priceFeed.decimals()) /
            uint256(collateralPrice) /
            BASE_CURRENCY_UNIT;
    }

    // @notice transfer hook to transfer the exposure from sender to recipient.
    // @param from the sender of vault shares.
    // @param to recipient of vault shares.
    // @param amount amount of vault shares to transfer.
    function _beforeTokenTransfer(DataTypesLib.State storage state, address from, address to, uint256 amount) external {
        IRangeProtocolVault vault = IRangeProtocolVault(address(this));
        if (from == address(0x0) || to == address(0x0)) return;
        if (!state.vaults[to].exists) {
            state.vaults[to].exists = true;
            state.users.push(to);
        }
        uint256 senderBalance = vault.balanceOf(from);
        uint256 tokenAmount = state.vaults[from].token -
            (state.vaults[from].token * (senderBalance - amount)) /
            senderBalance;

        state.vaults[from].token -= tokenAmount;
        state.vaults[to].token += tokenAmount;
    }

    /**
     * @notice returns Aave position data.
     * @return totalCollateralBase total collateral supplied.
     * @return totalDebtBase total debt borrowed.
     * @return availableBorrowsBase available amount to borrow.
     * @return currentLiquidationThreshold current threshold for liquidation to trigger.
     * @return ltv Loan-to-value ratio of the position.
     * @return healthFactor current health factor of the position.
     */
    function getAavePositionData(
        DataTypesLib.State storage state
    )
        public
        view
        returns (
            uint256 totalCollateralBase,
            uint256 totalDebtBase,
            uint256 availableBorrowsBase,
            uint256 currentLiquidationThreshold,
            uint256 ltv,
            uint256 healthFactor
        )
    {
        return IPool(state.poolAddressesProvider.getPool()).getUserAccountData(address(this));
    }

    // @notice validated the lower and upper ticks.
    function _validateTicks(int24 _lowerTick, int24 _upperTick, int24 tickSpacing) private pure {
        if (_lowerTick < TickMath.MIN_TICK || _upperTick > TickMath.MAX_TICK) revert VaultErrors.TicksOutOfRange();
        if (_lowerTick >= _upperTick || _lowerTick % tickSpacing != 0 || _upperTick % tickSpacing != 0)
            revert VaultErrors.InvalidTicksSpacing();
    }

    // @notice internal function that withdraws liquidity from the AMM pool.
    // @param liquidity the amount liquidity to withdraw from the AMM pool.
    // @return burn0 amount of token0 received from burning liquidity.
    // @return burn1 amount of token1 received from burning liquidity.
    // @return fee0 amount of fee in token0 collected.
    // @return fee1 amount of fee in token1 collected.
    function _withdraw(
        DataTypesLib.State storage state,
        uint128 liquidity
    ) internal returns (uint256 burn0, uint256 burn1, uint256 fee0, uint256 fee1) {
        int24 _lowerTick = state.lowerTick;
        int24 _upperTick = state.upperTick;
        uint256 preBalance0 = state.token0.balanceOf(address(this));
        uint256 preBalance1 = state.token1.balanceOf(address(this));
        (burn0, burn1) = state.pool.burn(_lowerTick, _upperTick, liquidity);
        state.pool.collect(address(this), _lowerTick, _upperTick, type(uint128).max, type(uint128).max);
        fee0 = state.token0.balanceOf(address(this)) - preBalance0 - burn0;
        fee1 = state.token1.balanceOf(address(this)) - preBalance1 - burn1;
    }

    // @notice returns the amount of fee earned based on the feeGrowth factor.
    function _feesEarned(
        DataTypesLib.State storage state,
        bool isZero,
        uint256 feeGrowthInsideLast,
        int24 tick,
        uint128 liquidity
    ) private view returns (uint256 fee) {
        uint256 feeGrowthOutsideLower;
        uint256 feeGrowthOutsideUpper;
        uint256 feeGrowthGlobal;
        if (isZero) {
            feeGrowthGlobal = state.pool.feeGrowthGlobal0X128();
            (, , feeGrowthOutsideLower, , , , , ) = state.pool.ticks(state.lowerTick);
            (, , feeGrowthOutsideUpper, , , , , ) = state.pool.ticks(state.upperTick);
        } else {
            feeGrowthGlobal = state.pool.feeGrowthGlobal1X128();
            (, , , feeGrowthOutsideLower, , , , ) = state.pool.ticks(state.lowerTick);
            (, , , feeGrowthOutsideUpper, , , , ) = state.pool.ticks(state.upperTick);
        }

        unchecked {
            uint256 feeGrowthBelow;
            if (tick >= state.lowerTick) {
                feeGrowthBelow = feeGrowthOutsideLower;
            } else {
                feeGrowthBelow = feeGrowthGlobal - feeGrowthOutsideLower;
            }

            uint256 feeGrowthAbove;
            if (tick < state.upperTick) {
                feeGrowthAbove = feeGrowthOutsideUpper;
            } else {
                feeGrowthAbove = feeGrowthGlobal - feeGrowthOutsideUpper;
            }
            uint256 feeGrowthInside = feeGrowthGlobal - feeGrowthBelow - feeGrowthAbove;

            fee = FullMath.mulDiv(
                liquidity,
                feeGrowthInside - feeGrowthInsideLast,
                0x100000000000000000000000000000000
            );
        }
    }

    // @notice returns if the current of price of gho against collateral token from AMM does not deviate more than 0.5%
    // from gho price against collateral token from Chainlink price oracle.
    function _validatePriceThreshold(DataTypesLib.State storage state) private view {
        // revert if price from any of the price oracles is stalled.
        _validatePriceOraclesStaleness(state);
        (uint160 sqrtRatioX96, , , , , , ) = state.pool.slot0();
        uint256 priceFromUniswap = FullMath.mulDiv(
            uint256(sqrtRatioX96) * uint256(sqrtRatioX96),
            10 ** state.decimals0,
            1 << 192
        );

        (, int256 collateralPrice, , , ) = state.collateralPriceOracle.priceFeed.latestRoundData();
        (, int256 ghoPrice, , , ) = state.ghoPriceOracle.priceFeed.latestRoundData();

        uint256 priceFromOracle = (10 ** state.decimals1 *
            uint256(ghoPrice) *
            state.collateralPriceOracle.priceFeed.decimals()) /
            state.ghoPriceOracle.priceFeed.decimals() /
            uint256(collateralPrice);

        uint256 priceRatio = (priceFromUniswap * 10_000) / priceFromOracle;
        // price from uni pool must deviate by 0.5% with the price from Chainlink oracle.
        if (priceRatio < 9_950 || priceRatio > 10_050) revert VaultErrors.PriceNotWithinThreshold();
    }

    // @notice checks the staleness of price oracles from Chainlink. If the last updated answer is older than the
    // heartbeat of the price oracle then the call to this function is reverted.
    function _validatePriceOraclesStaleness(DataTypesLib.State storage state) private view {
        AggregatorV3Interface collateralPriceFeed = state.collateralPriceOracle.priceFeed;
        AggregatorV3Interface ghoPriceFeed = state.ghoPriceOracle.priceFeed;

        (, , , uint256 collateralPriceUpdatedAt, ) = collateralPriceFeed.latestRoundData();
        (, , , uint256 ghoPriceUpdatedAt, ) = ghoPriceFeed.latestRoundData();

        if (block.timestamp - collateralPriceUpdatedAt > state.collateralPriceOracle.heartbeatDuration)
            revert VaultErrors.OraclePriceIsOutdated(address(collateralPriceFeed));

        if (block.timestamp - ghoPriceUpdatedAt > state.ghoPriceOracle.heartbeatDuration)
            revert VaultErrors.OraclePriceIsOutdated(address(ghoPriceFeed));
    }

    // @notice applies managing fee to the amount.
    // @param amount the amount to apply the managing fee.
    function _applyManagingFee(DataTypesLib.State storage state, uint256 amount) private {
        state.managerBalance += (amount * state.managingFee) / 10_000;
    }

    // @notice applies performance fee to the fee0 and fee1.
    // @param fee0 the amount of fee0 to apply the performance fee.
    // @param fee1 the amount of fee1 to apply the performance fee.
    function _applyPerformanceFee(DataTypesLib.State storage state, uint256 fee0, uint256 fee1) private {
        uint256 _performanceFee = state.performanceFee;
        state.managerBalance += (fee1 * _performanceFee) / 10_000;

        (, int256 collateralPrice, , , ) = state.collateralPriceOracle.priceFeed.latestRoundData();
        (, int256 ghoPrice, , , ) = state.ghoPriceOracle.priceFeed.latestRoundData();
        state.managerBalance +=
            (fee0 * 10 ** state.decimals1 * uint256(ghoPrice) * _performanceFee) /
            10 ** state.decimals0 /
            uint256(collateralPrice) /
            10_000;
    }

    // @notice deducts managing fee from the amount.
    // @param amount the amount to apply the managing fee.
    // @return amountAfterFee amount after deducting managing fee.
    function _netManagingFees(
        DataTypesLib.State storage state,
        uint256 amount
    ) private view returns (uint256 amountAfterFee) {
        uint256 deduct = (amount * state.managingFee) / 10_000;
        amountAfterFee = amount - deduct;
    }

    // @notice deducts performance fee from fee0 and fee1.
    // @param rawFee0 the amount of fee0 to apply the performance fee.
    // @param rawFee1 the amount of fee1 to apply the performance fee.
    // @param fee0AfterDeduction fee0 after performance fee deduction.
    // @param fee1AfterDeduction fee1 after performance fee deduction.
    function _netPerformanceFees(
        DataTypesLib.State storage state,
        uint256 rawFee0,
        uint256 rawFee1
    ) private view returns (uint256 fee0AfterDeduction, uint256 fee1AfterDeduction) {
        uint256 _performanceFee = state.performanceFee;
        uint256 deduct0 = (rawFee0 * _performanceFee) / 10_000;
        uint256 deduct1 = (rawFee1 * _performanceFee) / 10_000;
        fee0AfterDeduction = rawFee0 - deduct0;
        fee1AfterDeduction = rawFee1 - deduct1;
    }
}

File 40 of 43 : RangeProtocolVaultStorage.sol
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;

import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {DataTypesLib} from "./libraries/DataTypesLib.sol";
import {IRangeProtocolVault} from "./interfaces/IRangeProtocolVault.sol";

abstract contract RangeProtocolVaultStorage is IRangeProtocolVault {
    DataTypesLib.State internal state;

    function factory() external view override returns (address) {
        return state.factory;
    }

    function pool() external view override returns (IUniswapV3Pool) {
        return state.pool;
    }

    function token0() external view override returns (IERC20Upgradeable) {
        return state.token0;
    }

    function token1() external view override returns (IERC20Upgradeable) {
        return state.token1;
    }

    function lowerTick() external view override returns (int24) {
        return state.lowerTick;
    }

    function upperTick() external view override returns (int24) {
        return state.upperTick;
    }

    function tickSpacing() external view override returns (int24) {
        return state.tickSpacing;
    }

    function inThePosition() external view override returns (bool) {
        return state.inThePosition;
    }

    function managingFee() external view override returns (uint16) {
        return state.managingFee;
    }

    function performanceFee() external view override returns (uint16) {
        return state.performanceFee;
    }

    function managerBalance() external view override returns (uint256) {
        return state.managerBalance;
    }

    function userVaults(address user) external view override returns (DataTypesLib.UserVault memory) {
        return state.vaults[user];
    }

    function userCount() external view override returns (uint256) {
        return state.users.length;
    }

    function users(uint256 index) external view override returns (address) {
        return state.users[index];
    }

    function poolAddressesProvider() external view override returns (address) {
        return address(state.poolAddressesProvider);
    }

    function gho() external view override returns (address) {
        return address(state.token0);
    }

    function collateralToken() external view override returns (address) {
        return address(state.token1);
    }
}

File 41 of 43 : FullMath.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            // EDIT for 0.8 compatibility:
            // see: https://ethereum.stackexchange.com/questions/96642/unary-operator-cannot-be-applied-to-type-uint256
            uint256 twos = denominator & (~denominator + 1);

            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            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
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use 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.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = mulDiv(a, b, denominator);
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }
}

File 42 of 43 : LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;

import {FullMath} from "./FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x);
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96)
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        uint256 intermediate =
            FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
        return
            toUint128(
                FullMath.mulDiv(
                    amount0,
                    intermediate,
                    sqrtRatioBX96 - sqrtRatioAX96
                )
            );
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96)
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        return
            toUint128(
                FullMath.mulDiv(
                    amount1,
                    FixedPoint96.Q96,
                    sqrtRatioBX96 - sqrtRatioAX96
                )
            );
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96)
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            liquidity = getLiquidityForAmount0(
                sqrtRatioAX96,
                sqrtRatioBX96,
                amount0
            );
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            uint128 liquidity0 =
                getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
            uint128 liquidity1 =
                getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(
                sqrtRatioAX96,
                sqrtRatioBX96,
                amount1
            );
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount0
    function getAmount0ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0) {
        if (sqrtRatioAX96 > sqrtRatioBX96)
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return
            FullMath.mulDiv(
                uint256(liquidity) << FixedPoint96.RESOLUTION,
                sqrtRatioBX96 - sqrtRatioAX96,
                sqrtRatioBX96
            ) / sqrtRatioAX96;
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price
    /// @param sqrtRatioBX96 Another sqrt price
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount1
    function getAmount1ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96)
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return
            FullMath.mulDiv(
                liquidity,
                sqrtRatioBX96 - sqrtRatioAX96,
                FixedPoint96.Q96
            );
    }

    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
    /// pool prices and the prices at the tick boundaries
    function getAmountsForLiquidity(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96)
            (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            amount0 = getAmount0ForLiquidity(
                sqrtRatioAX96,
                sqrtRatioBX96,
                liquidity
            );
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            amount0 = getAmount0ForLiquidity(
                sqrtRatioX96,
                sqrtRatioBX96,
                liquidity
            );
            amount1 = getAmount1ForLiquidity(
                sqrtRatioAX96,
                sqrtRatioX96,
                liquidity
            );
        } else {
            amount1 = getAmount1ForLiquidity(
                sqrtRatioAX96,
                sqrtRatioBX96,
                liquidity
            );
        }
    }
}

File 43 of 43 : TickMath.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.4;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO =
        1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick)
        internal
        pure
        returns (uint160 sqrtPriceX96)
    {
        uint256 absTick =
            tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));

        // EDIT: 0.8 compatibility
        require(absTick <= uint256(int256(MAX_TICK)), "T");

        uint256 ratio =
            absTick & 0x1 != 0
                ? 0xfffcb933bd6fad37aa2d162d1a594001
                : 0x100000000000000000000000000000000;
        if (absTick & 0x2 != 0)
            ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
        if (absTick & 0x4 != 0)
            ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
        if (absTick & 0x8 != 0)
            ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
        if (absTick & 0x10 != 0)
            ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
        if (absTick & 0x20 != 0)
            ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
        if (absTick & 0x40 != 0)
            ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
        if (absTick & 0x80 != 0)
            ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
        if (absTick & 0x100 != 0)
            ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
        if (absTick & 0x200 != 0)
            ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
        if (absTick & 0x400 != 0)
            ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
        if (absTick & 0x800 != 0)
            ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
        if (absTick & 0x1000 != 0)
            ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
        if (absTick & 0x2000 != 0)
            ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
        if (absTick & 0x4000 != 0)
            ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
        if (absTick & 0x8000 != 0)
            ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
        if (absTick & 0x10000 != 0)
            ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
        if (absTick & 0x20000 != 0)
            ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
        if (absTick & 0x40000 != 0)
            ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0)
            ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

        if (tick > 0) ratio = type(uint256).max / ratio;

        // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
        // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
        // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
        sqrtPriceX96 = uint160(
            (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
        );
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96)
        internal
        pure
        returns (int24 tick)
    {
        // second inequality must be < because the price can never reach the price at the max tick
        require(
            sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
            "R"
        );
        uint256 ratio = uint256(sqrtPriceX96) << 32;

        uint256 r = ratio;
        uint256 msb = 0;

        assembly {
            let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(5, gt(r, 0xFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(4, gt(r, 0xFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(3, gt(r, 0xFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(2, gt(r, 0xF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(1, gt(r, 0x3))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := gt(r, 0x1)
            msb := or(msb, f)
        }

        if (msb >= 128) r = ratio >> (msb - 127);
        else r = ratio << (127 - msb);

        int256 log_2 = (int256(msb) - 128) << 64;

        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(63, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(62, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(61, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(60, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(59, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(58, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(57, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(56, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(55, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(54, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(53, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(52, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(51, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(50, f))
        }

        int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

        int24 tickLow =
            int24(
                (log_sqrt10001 - 3402992956809132418596140100660247210) >> 128
            );
        int24 tickHi =
            int24(
                (log_sqrt10001 + 291339464771989622907027621153398088495) >> 128
            );

        tick = tickLow == tickHi
            ? tickLow
            : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
            ? tickHi
            : tickLow;
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 100
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/libraries/LogicLib.sol": {
      "LogicLib": "0x0a0b5f2bccbf50f1ccf7477c8ad2362312480c51"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"OnlyFactoryAllowed","type":"error"},{"inputs":[],"name":"OnlyVaultAllowed","type":"error"},{"inputs":[],"name":"PoolRepegFailed","type":"error"},{"inputs":[],"name":"TokenZeroIsNotGHO","type":"error"},{"inputs":[],"name":"ZeroManagerAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"beacon","type":"address"}],"name":"BeaconUpgraded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"burnAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Burned","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CollateralSupplied","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"CollateralWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"feesEarned0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"feesEarned1","type":"uint256"}],"name":"FeesEarned","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"managingFee","type":"uint16"},{"indexed":false,"internalType":"uint16","name":"performanceFee","type":"uint16"}],"name":"FeesUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"GHOBurned","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"GHOMinted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"inThePosition","type":"bool"}],"name":"InThePositionStatusSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"liquidityMinted","type":"uint256"},{"indexed":false,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"}],"name":"LiquidityAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"liquidityRemoved","type":"uint256"},{"indexed":false,"internalType":"int24","name":"tickLower","type":"int24"},{"indexed":false,"internalType":"int24","name":"tickUpper","type":"int24"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"}],"name":"LiquidityRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"uint256","name":"shares","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Minted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"collateralOracleHearbeat","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ghoOracleHeartbreat","type":"uint256"}],"name":"OraclesHeartbeatUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousManager","type":"address"},{"indexed":true,"internalType":"address","name":"newManager","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[],"name":"PoolRepegged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"zeroForOne","type":"bool"},{"indexed":false,"internalType":"int256","name":"amount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"amount1","type":"int256"}],"name":"Swapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int24","name":"lowerTick","type":"int24"},{"indexed":false,"internalType":"int24","name":"upperTick","type":"int24"}],"name":"TicksSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[{"internalType":"int24","name":"newLowerTick","type":"int24"},{"internalType":"int24","name":"newUpperTick","type":"int24"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"uint256[2]","name":"maxAmounts","type":"uint256[2]"}],"name":"addLiquidity","outputs":[{"internalType":"uint256","name":"remainingAmount0","type":"uint256"},{"internalType":"uint256","name":"remainingAmount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"burnAmount","type":"uint256"},{"internalType":"uint256","name":"minAmount","type":"uint256"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"burnAmount","type":"uint256"}],"name":"burnGHO","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"burnShares","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collateralToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"collectManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAavePositionData","outputs":[{"internalType":"uint256","name":"totalCollateralBase","type":"uint256"},{"internalType":"uint256","name":"totalDebtBase","type":"uint256"},{"internalType":"uint256","name":"availableBorrowsBase","type":"uint256"},{"internalType":"uint256","name":"currentLiquidationThreshold","type":"uint256"},{"internalType":"uint256","name":"ltv","type":"uint256"},{"internalType":"uint256","name":"healthFactor","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBalanceInCollateralToken","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentFees","outputs":[{"internalType":"uint256","name":"fee0","type":"uint256"},{"internalType":"uint256","name":"fee1","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPositionID","outputs":[{"internalType":"bytes32","name":"positionID","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"getUnderlyingBalanceByShare","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUnderlyingBalancesFromAave","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUnderlyingBalancesFromPool","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"fromIdx","type":"uint256"},{"internalType":"uint256","name":"toIdx","type":"uint256"}],"name":"getUserVaults","outputs":[{"components":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"token","type":"uint256"}],"internalType":"struct DataTypesLib.UserVaultInfo[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"gho","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"inThePosition","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"int24","name":"_tickSpacing","type":"int24"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"lowerTick","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"managerBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"managingFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"minShares","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"mintAmount","type":"uint256"}],"name":"mintGHO","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"mintShares","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"performanceFee","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolAddressesProvider","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pullFeeFromPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[2]","name":"minAmounts","type":"uint256[2]"}],"name":"removeLiquidity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"calldatas","type":"bytes[]"}],"name":"repegPool","outputs":[{"internalType":"bytes[]","name":"returndatas","type":"bytes[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"supplyAmount","type":"uint256"}],"name":"supplyCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"swapAmount","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"uint256","name":"minAmountIn","type":"uint256"}],"name":"swap","outputs":[{"internalType":"int256","name":"amount0","type":"int256"},{"internalType":"int256","name":"amount1","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tickSpacing","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"contract IERC20Upgradeable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"contract IERC20Upgradeable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newManager","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"uniswapV3MintCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"newManagingFee","type":"uint16"},{"internalType":"uint16","name":"newPerformanceFee","type":"uint16"}],"name":"updateFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"collateralOracleHBDuration","type":"uint256"},{"internalType":"uint256","name":"ghoOracleHBDuration","type":"uint256"}],"name":"updatePriceOracleHeartbeatsDuration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"}],"name":"upgradeTo","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"upperTick","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"userCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"userVaults","outputs":[{"components":[{"internalType":"bool","name":"exists","type":"bool"},{"internalType":"uint256","name":"token","type":"uint256"}],"internalType":"struct DataTypesLib.UserVault","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"users","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"withdrawAmount","type":"uint256"}],"name":"withdrawCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a06040523060601b6080523480156200001857600080fd5b506200002362000029565b620000eb565b600054610100900460ff1615620000965760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff9081161015620000e9576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b60805160601c613dc86200012660003960008181610e1b01528181610e640152818161167c015281816116bc01526117aa0152613dc86000f3fe6080604052600436106103385760003560e01c806371908a03116101b2578063d0c93a7c116100ed578063e059c66011610090578063e059c66014610a72578063ee7a7c0414610a92578063eebc359a14610ab2578063f26f87ad14610ac7578063f2fde38b14610add578063f313179314610afd578063f3d2350e14610b12578063fa461e3314610b3257600080fd5b8063d0c93a7c146109bb578063d1af1ca9146103b8578063d21220a714610910578063d3487997146109db578063d7e458b5146109fb578063dd62ed3e14610a10578063de79e37414610a30578063df28408a14610a5d57600080fd5b80639cd643cc116101555780639cd643cc146108b0578063a457c2d7146108d0578063a9059cbb146108f0578063b2016bd414610910578063b390c0ab1461092f578063c45a01551461094f578063c4f2e7af1461096e578063c653089f1461098e57600080fd5b806371908a03146107cd578063727dd228146107e257806380e17d87146108115780638456cb591461083057806387788782146108455780639403c1ae1461086657806395d89b411461087b5780639b1344ac1461089057600080fd5b80633950935111610282578063528c198a11610225578063528c198a146106bb57806352d1902d146106db5780635c975abb146106f0578063601b48a4146107095780636112fe2e14610737578063628ec4db1461075757806363e968361461077757806370a082311461079757600080fd5b806339509351146105d55780633d048c27146105f55780633f4ba83a146106155780634043f5ca1461062a578063481c6a751461064a5780634a0997f4146106685780634f1ef2861461068857806351da5b171461069b57600080fd5b80631b2ef1ca116102ea5780631b2ef1ca1461044957806323b872dd146104695780632958d03114610489578063313ce5671461050e578063349e078f146105315780633659cfe614610573578063365b98b214610595578063367febea146105b557600080fd5b806306fdde031461033d57806307973ccf14610368578063095ea7b3146103885780630dfe1681146103b8578063122b6d55146103eb57806316f0115b1461041557806318160ddd14610434575b600080fd5b34801561034957600080fd5b50610352610b52565b60405161035f9190613a31565b60405180910390f35b34801561037457600080fd5b5061016b545b60405190815260200161035f565b34801561039457600080fd5b506103a86103a33660046134f1565b610be4565b604051901515815260200161035f565b3480156103c457600080fd5b50610161546001600160a01b03165b6040516001600160a01b03909116815260200161035f565b3480156103f757600080fd5b50610400610bfe565b6040805192835260208301919091520161035f565b34801561042157600080fd5b50610160546001600160a01b03166103d3565b34801561044057600080fd5b5060fd5461037a565b34801561045557600080fd5b5061037a6104643660046138ac565b610c92565b34801561047557600080fd5b506103a8610484366004613405565b610d43565b34801561049557600080fd5b506104f16104a43660046132c9565b6040805180820190915260008082526020820152506001600160a01b0316600090815261016a60209081526040918290208251808401909352805460ff1615158352600101549082015290565b60408051825115158152602092830151928101929092520161035f565b34801561051a57600080fd5b506101635460405160ff909116815260200161035f565b34801561053d57600080fd5b50610546610d69565b604080519687526020870195909552938501929092526060840152608083015260a082015260c00161035f565b34801561057f57600080fd5b5061059361058e3660046132c9565b610e10565b005b3480156105a157600080fd5b506103d36105b0366004613894565b610ee2565b3480156105c157600080fd5b506105936105d0366004613894565b610f24565b3480156105e157600080fd5b506103a86105f03660046134f1565b610f9b565b34801561060157600080fd5b50610593610610366004613492565b610fbd565b34801561062157600080fd5b50610593611617565b34801561063657600080fd5b5061016254600160e81b900460ff166103a8565b34801561065657600080fd5b5060c9546001600160a01b03166103d3565b34801561067457600080fd5b50610593610683366004613894565b611629565b610593610696366004613445565b611671565b3480156106a757600080fd5b506105936106b6366004613894565b61172b565b3480156106c757600080fd5b506105936106d63660046134f1565b611773565b3480156106e757600080fd5b5061037a61179d565b3480156106fc57600080fd5b5061012d5460ff166103a8565b34801561071557600080fd5b5061016354610100900461ffff165b60405161ffff909116815260200161035f565b34801561074357600080fd5b50610593610752366004613894565b61184b565b34801561076357600080fd5b5061037a610772366004613894565b611893565b34801561078357600080fd5b50610400610792366004613702565b611921565b3480156107a357600080fd5b5061037a6107b23660046132c9565b6001600160a01b0316600090815260fb602052604090205490565b3480156107d957600080fd5b506104006119cc565b3480156107ee57600080fd5b5061016254600160b81b900460020b5b60405160029190910b815260200161035f565b34801561081d57600080fd5b50610165546001600160a01b03166103d3565b34801561083c57600080fd5b50610593611a0a565b34801561085157600080fd5b50610163546301000000900461ffff16610724565b34801561087257600080fd5b50610593611a1a565b34801561088757600080fd5b50610352611aab565b34801561089c57600080fd5b5061016254600160a01b900460020b6107fe565b3480156108bc57600080fd5b506105936108cb366004613688565b611aba565b3480156108dc57600080fd5b506103a86108eb3660046134f1565b611afd565b3480156108fc57600080fd5b506103a861090b3660046134f1565b611b83565b34801561091c57600080fd5b50610162546001600160a01b03166103d3565b34801561093b57600080fd5b5061037a61094a3660046138ac565b611b91565b34801561095b57600080fd5b5061015f546001600160a01b03166103d3565b34801561097a57600080fd5b506105936109893660046138ac565b611be9565b34801561099a57600080fd5b506109ae6109a93660046138ac565b611c68565b60405161035f91906139d9565b3480156109c757600080fd5b5061016254600160d01b900460020b6107fe565b3480156109e757600080fd5b506105936109f6366004613780565b611d01565b348015610a0757600080fd5b50610593611d7a565b348015610a1c57600080fd5b5061037a610a2b3660046133cd565b611dbb565b348015610a3c57600080fd5b50610a50610a4b36600461351c565b611de6565b60405161035f9190613978565b348015610a6957600080fd5b5061037a611f7d565b348015610a7e57600080fd5b50610400610a8d3660046136a3565b61200a565b348015610a9e57600080fd5b50610593610aad3660046134f1565b6120ca565b348015610abe57600080fd5b5061037a6120f4565b348015610ad357600080fd5b506101645461037a565b348015610ae957600080fd5b50610593610af83660046132c9565b612130565b348015610b0957600080fd5b506104006121a8565b348015610b1e57600080fd5b50610593610b2d366004613867565b6122e4565b348015610b3e57600080fd5b50610593610b4d366004613780565b612337565b606060fe8054610b6190613c67565b80601f0160208091040260200160405190810160405280929190818152602001828054610b8d90613c67565b8015610bda5780601f10610baf57610100808354040283529160200191610bda565b820191906000526020600020905b815481529060010190602001808311610bbd57829003601f168201915b5050505050905090565b600033610bf281858561237e565b60019150505b92915050565b6040516001620adc9960e31b0319815261015f60048201526000908190730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063ffa91b38906024015b604080518083038186803b158015610c5257600080fd5b505af4158015610c66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c8a919061375d565b915091509091565b6000610c9c6124a2565b610ca46124fc565b60405163d1ee9bfd60e01b815261015f60048201526024810184905260448101839052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063d1ee9bfd906064015b60206040518083038186803b158015610cff57600080fd5b505af4158015610d13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d3791906136ea565b9050610bf86001606555565b600033610d5185828561254a565b610d5c8585856125be565b60019150505b9392505050565b600080600080600080730a0b5f2bccbf50f1ccf7477c8ad2362312480c5163feaadfd361015f6040518263ffffffff1660e01b8152600401610dad91815260200190565b60c06040518083038186803b158015610dc557600080fd5b505af4158015610dd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dfd91906138cd565b949b939a50919850965094509092509050565b306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161415610e625760405162461bcd60e51b8152600401610e5990613a44565b60405180910390fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316610e94612762565b6001600160a01b031614610eba5760405162461bcd60e51b8152600401610e5990613a90565b610ec38161277e565b60408051600080825260208201909252610edf918391906127aa565b50565b600061015f600c018281548110610f0957634e487b7160e01b600052603260045260246000fd5b6000918252602090912001546001600160a01b031692915050565b610f2c612929565b604051630decace760e01b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190630decace7906044015b60006040518083038186803b158015610f8057600080fd5b505af4158015610f94573d6000803e3d6000fd5b5050505050565b600033610bf2818585610fae8383611dbb565b610fb89190613c23565b61237e565b600054610100900460ff1615808015610fdd5750600054600160ff909116105b80610ff75750303b158015610ff7575060005460ff166001145b61105a5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610e59565b6000805460ff19166001179055801561107d576000805461ff0019166101001790555b60008060008060008060008060008a80602001905181019061109f9190613301565b9850985098509850985098509850985098506110b961298e565b6110c16129b5565b6110c96129e4565b6110d38888612a13565b6110db612a44565b6110e489612a73565b6001600160a01b03891661110b57604051636ba0d85d60e11b815260040160405180910390fd5b856001600160a01b03168d6001600160a01b0316630dfe16816040518163ffffffff1660e01b815260040160206040518083038186803b15801561114e57600080fd5b505afa158015611162573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061118691906132e5565b6001600160a01b0316146111ad5760405163e402fd1560e01b815260040160405180910390fd5b61016080546001600160a01b0319166001600160a01b038f1690811790915560408051630dfe168160e01b8152905160009291630dfe1681916004808301926020929190829003018186803b15801561120557600080fd5b505afa158015611219573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061123d91906132e5565b9050600061015f60010160009054906101000a90046001600160a01b03166001600160a01b031663d21220a76040518163ffffffff1660e01b815260040160206040518083038186803b15801561129357600080fd5b505afa1580156112a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cb91906132e5565b90508161015f60020160006101000a8154816001600160a01b0302191690836001600160a01b031602179055508061015f60030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055508d61015f600301601a6101000a81548162ffffff021916908360020b62ffffff1602179055503361015f60000160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506000826001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156113af57600080fd5b505afa1580156113c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e79190613916565b90506000826001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561142457600080fd5b505afa158015611438573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061145c9190613916565b610162805460ff808416600160f81b026001600160f81b03918716600160f01b02919091166001600160f01b039092169190911717905561016580546001600160a01b03808d166001600160a01b0319928316179092556040805180820182528c841680825260209182018d90526101668054851690911790556101678c905581518083019092528a841680835291018990526101688054909216179055610169879055909150848116908b161461152457610163805460ff191660ff841617905581611536565b610163805460ff191660ff8316179055805b610163805460ff191660ff92909216919091179055604051631262ee9360e01b815261015f6004820152600a60248201526103e86044820152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190631262ee939060640160006040518083038186803b1580156115a657600080fd5b505af41580156115ba573d6000803e3d6000fd5b50505050505050505050505050505050508015611611576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b61161f612929565b611627612ac5565b565b611631612929565b60405163aa14b15360e01b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063aa14b15390604401610f68565b306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614156116ba5760405162461bcd60e51b8152600401610e5990613a44565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166116ec612762565b6001600160a01b0316146117125760405162461bcd60e51b8152600401610e5990613a90565b61171b8261277e565b611727828260016127aa565b5050565b611733612929565b60405163388bfeed60e21b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063e22ffbb490604401610f68565b33301461179357604051631628c08760e31b815260040160405180910390fd5b6117278282612b18565b6000306001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016146118385760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c6044820152771b1959081d1a1c9bdd59da0819195b1959d85d1958d85b1b60421b6064820152608401610e59565b50600080516020613d2c83398151915290565b611853612929565b604051637fec8ad360e01b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190637fec8ad390604401610f68565b6040516356d9182d60e11b815261015f600482015260248101829052600090730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063adb2305a9060440160206040518083038186803b1580156118e957600080fd5b505af41580156118fd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf891906136ea565b60008061192c612929565b604051631b63a06d60e21b8152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190636d8e81b49061196f9061015f908b908b908b908b908b90600401613b41565b604080518083038186803b15801561198657600080fd5b505af415801561199a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119be919061375d565b915091509550959350505050565b60405163812c13f360e01b815261015f60048201526000908190730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063812c13f390602401610c3b565b611a12612929565b611627612bd3565b611a22612929565b730a0b5f2bccbf50f1ccf7477c8ad2362312480c5163a4dc445d61015f611a5160c9546001600160a01b031690565b6040516001600160e01b031960e085901b16815260048101929092526001600160a01b031660248201526044015b60006040518083038186803b158015611a9757600080fd5b505af4158015611611573d6000803e3d6000fd5b606060ff8054610b6190613c67565b611ac2612929565b60405163c8ce5eb760e01b8152730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063c8ce5eb790610f689061015f908590600401613b27565b60003381611b0b8286611dbb565b905083811015611b6b5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610e59565b611b78828686840361237e565b506001949350505050565b600033610bf28185856125be565b6000611b9b6124a2565b611ba36124fc565b6040516293442f60e11b815261015f60048201526024810184905260448101839052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190630126885e90606401610ce7565b611bf1612929565b6040516331038ee160e21b815261015f60048201526024810183905260448101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063c40e3b84906064015b60006040518083038186803b158015611c4c57600080fd5b505af4158015611c60573d6000803e3d6000fd5b505050505050565b604051637db1f66560e11b815261015f60048201526024810183905260448101829052606090730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063fb63ecca9060640160006040518083038186803b158015611cc557600080fd5b505af4158015611cd9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610d6291908101906135cc565b604051635692f48560e01b815261015f60048201526024810185905260448101849052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190635692f485906064015b60006040518083038186803b158015611d5c57600080fd5b505af4158015611d70573d6000803e3d6000fd5b5050505050505050565b611d82612929565b604051637436b83560e01b815261015f6004820152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190637436b83590602401611a7f565b6001600160a01b03918216600090815260fc6020908152604080832093909416825291909152205490565b6060611df0612929565b81516001600160401b03811115611e1757634e487b7160e01b600052604160045260246000fd5b604051908082528060200260200182016040528015611e4a57816020015b6060815260200190600190039081611e355790505b50905060005b8251811015611f4e57600080306001600160a01b0316858481518110611e8657634e487b7160e01b600052603260045260246000fd5b6020026020010151604051611e9b919061395c565b600060405180830381855af49150503d8060008114611ed6576040519150601f19603f3d011682016040523d82523d6000602084013e611edb565b606091505b509150915081611f0d57805115611ef457805181602001fd5b604051637c83e73360e11b815260040160405180910390fd5b80848481518110611f2e57634e487b7160e01b600052603260045260246000fd5b602002602001018190525050508080611f4690613ca2565b915050611e50565b506040517ff1441a081a033a01c1623ac6a2ca24f2cc88f9b4a47b112e006f4838f9c4e52e90600090a1919050565b604051633081559960e11b815261015f6004820152600090730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190636102ab32906024015b60206040518083038186803b158015611fcd57600080fd5b505af4158015611fe1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061200591906136ea565b905090565b600080612015612929565b60405163646bd58560e01b815261015f60048201528615156024820152604481018690526001600160a01b038516606482015260848101849052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063646bd5859060a401604080518083038186803b15801561208557600080fd5b505af4158015612099573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120bd919061375d565b9150915094509492505050565b3330146120ea57604051631628c08760e31b815260040160405180910390fd5b6117278282612c11565b60405163fea8519360e01b815261015f6004820152600090730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063fea8519390602401611fb5565b612138612929565b6001600160a01b03811661219f5760405162461bcd60e51b815260206004820152602860248201527f4f776e61626c653a206e6577206d616e6167657220697320746865207a65726f604482015267206164647265737360c01b6064820152608401610e59565b610edf81612a73565b6101605460408051633850c7bd60e01b815290516000928392839283926001600160a01b031691633850c7bd9160048083019260e0929190829003018186803b1580156121f457600080fd5b505afa158015612208573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061222c91906137d0565b505060405163add9d74d60e01b815261015f60048201526001600160a01b0386166024820152600285900b6044820152949650929450730a0b5f2bccbf50f1ccf7477c8ad2362312480c519363add9d74d9350606401915061228b9050565b604080518083038186803b1580156122a257600080fd5b505af41580156122b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122da919061375d565b9350935050509091565b6122ec612929565b604051631262ee9360e01b815261015f600482015261ffff808416602483015282166044820152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190631262ee9390606401611c34565b604051632fa1b90960e11b815261015f60048201526024810185905260448101849052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190635f43721290606401611d44565b6001600160a01b0383166123e05760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610e59565b6001600160a01b0382166124415760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610e59565b6001600160a01b03838116600081815260fc602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600260655414156124f55760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610e59565b6002606555565b61012d5460ff16156116275760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401610e59565b6001606555565b60006125568484611dbb565b9050600019811461161157818110156125b15760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610e59565b611611848484840361237e565b6001600160a01b0383166126225760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610e59565b6001600160a01b0382166126845760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610e59565b61268f838383612d3f565b6001600160a01b038316600090815260fb6020526040902054818110156127075760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610e59565b6001600160a01b03808516600081815260fb60205260408082208686039055928616808252908390208054860190559151600080516020613d73833981519152906127559086815260200190565b60405180910390a3611611565b600080516020613d2c833981519152546001600160a01b031690565b61015f546001600160a01b03163314610edf57604051631b1319e560e01b815260040160405180910390fd5b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156127e2576127dd83612dc6565b505050565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561281b57600080fd5b505afa92505050801561284b575060408051601f3d908101601f19168201909252612848918101906136ea565b60015b6128ae5760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201526d6f6e206973206e6f74205555505360901b6064820152608401610e59565b600080516020613d2c833981519152811461291d5760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f786044820152681a58589b195555525160ba1b6064820152608401610e59565b506127dd838383612e62565b60c9546001600160a01b031633146116275760405162461bcd60e51b815260206004820152602260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206d616e616760448201526132b960f11b6064820152608401610e59565b600054610100900460ff166116275760405162461bcd60e51b8152600401610e5990613adc565b600054610100900460ff166129dc5760405162461bcd60e51b8152600401610e5990613adc565b611627612e87565b600054610100900460ff16612a0b5760405162461bcd60e51b8152600401610e5990613adc565b611627612eae565b600054610100900460ff16612a3a5760405162461bcd60e51b8152600401610e5990613adc565b6117278282612ede565b600054610100900460ff16612a6b5760405162461bcd60e51b8152600401610e5990613adc565b611627612f2c565b60c980546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b612acd612f60565b61012d805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6001600160a01b038216612b6e5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610e59565b612b7a60008383612d3f565b8060fd6000828254612b8c9190613c23565b90915550506001600160a01b038216600081815260fb6020908152604080832080548601905551848152600080516020613d73833981519152910160405180910390a35050565b612bdb6124fc565b61012d805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612afb3390565b6001600160a01b038216612c715760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610e59565b612c7d82600083612d3f565b6001600160a01b038216600090815260fb602052604090205481811015612cf15760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610e59565b6001600160a01b038316600081815260fb60209081526040808320868603905560fd8054879003905551858152919291600080516020613d73833981519152910160405180910390a3505050565b60405163f7c2522960e01b815261015f60048201526001600160a01b0380851660248301528316604482015260648101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063f7c252299060840160006040518083038186803b158015612da957600080fd5b505af4158015612dbd573d6000803e3d6000fd5b50505050505050565b6001600160a01b0381163b612e335760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b6064820152608401610e59565b600080516020613d2c83398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b612e6b83612faa565b600082511180612e785750805b156127dd576116118383612fea565b600054610100900460ff166125435760405162461bcd60e51b8152600401610e5990613adc565b600054610100900460ff16612ed55760405162461bcd60e51b8152600401610e5990613adc565b61162733612a73565b600054610100900460ff16612f055760405162461bcd60e51b8152600401610e5990613adc565b8151612f189060fe90602085019061311c565b5080516127dd9060ff90602084019061311c565b600054610100900460ff16612f535760405162461bcd60e51b8152600401610e5990613adc565b61012d805460ff19169055565b61012d5460ff166116275760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610e59565b612fb381612dc6565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b60606001600160a01b0383163b6130525760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b6064820152608401610e59565b600080846001600160a01b03168460405161306d919061395c565b600060405180830381855af49150503d80600081146130a8576040519150601f19603f3d011682016040523d82523d6000602084013e6130ad565b606091505b50915091506130d58282604051806060016040528060278152602001613d4c602791396130de565b95945050505050565b606083156130ed575081610d62565b610d6283838151156131025781518083602001fd5b8060405162461bcd60e51b8152600401610e599190613a31565b82805461312890613c67565b90600052602060002090601f01602090048101928261314a5760008555613190565b82601f1061316357805160ff1916838001178555613190565b82800160010185558215613190579182015b82811115613190578251825591602001919060010190613175565b5061319c9291506131a0565b5090565b5b8082111561319c57600081556001016131a1565b80516131c081613ce9565b919050565b8060408101831015610bf857600080fd5b60008083601f8401126131e7578182fd5b5081356001600160401b038111156131fd578182fd5b60208301915083602082850101111561321557600080fd5b9250929050565b600082601f83011261322c578081fd5b813561323f61323a82613bfc565b613ba9565b818152846020838601011115613253578283fd5b816020850160208301379081016020019190915292915050565b600082601f83011261327d578081fd5b815161328b61323a82613bfc565b81815284602083860101111561329f578283fd5b6132b0826020830160208701613c3b565b949350505050565b805160ff811681146131c057600080fd5b6000602082840312156132da578081fd5b8135610d6281613ce9565b6000602082840312156132f6578081fd5b8151610d6281613ce9565b60008060008060008060008060006101208a8c03121561331f578485fd5b895161332a81613ce9565b60208b01519099506001600160401b0380821115613346578687fd5b6133528d838e0161326d565b995060408c0151915080821115613367578687fd5b506133748c828d0161326d565b97505060608a015161338581613ce9565b955061339360808b016131b5565b94506133a160a08b016131b5565b935060c08a015192506133b660e08b016131b5565b91506101008a015190509295985092959850929598565b600080604083850312156133df578182fd5b82356133ea81613ce9565b915060208301356133fa81613ce9565b809150509250929050565b600080600060608486031215613419578081fd5b833561342481613ce9565b9250602084013561343481613ce9565b929592945050506040919091013590565b60008060408385031215613457578182fd5b823561346281613ce9565b915060208301356001600160401b0381111561347c578182fd5b6134888582860161321c565b9150509250929050565b6000806000606084860312156134a6578081fd5b83356134b181613ce9565b925060208401356134c181613d0c565b915060408401356001600160401b038111156134db578182fd5b6134e78682870161321c565b9150509250925092565b60008060408385031215613503578182fd5b823561350e81613ce9565b946020939093013593505050565b6000602080838503121561352e578182fd5b82356001600160401b0380821115613544578384fd5b818501915085601f830112613557578384fd5b813561356561323a82613bd9565b80828252858201915085850189878560051b8801011115613584578788fd5b875b848110156135bd5781358681111561359c57898afd5b6135aa8c8a838b010161321c565b8552509287019290870190600101613586565b50909998505050505050505050565b600060208083850312156135de578182fd5b82516001600160401b038111156135f3578283fd5b8301601f81018513613603578283fd5b805161361161323a82613bd9565b80828252848201915084840188868560061b8701011115613630578687fd5b8694505b8385101561367c57604080828b03121561364c578788fd5b613654613b81565b825161365f81613ce9565b815282880151888201528452600195909501949286019201613634565b50979650505050505050565b600060408284031215613699578081fd5b610d6283836131c5565b600080600080608085870312156136b8578182fd5b84356136c381613cfe565b93506020850135925060408501356136da81613ce9565b9396929550929360600135925050565b6000602082840312156136fb578081fd5b5051919050565b600080600080600060c08688031215613719578283fd5b853561372481613d0c565b9450602086013561373481613d0c565b9350604086013592506060860135915061375187608088016131c5565b90509295509295909350565b6000806040838503121561376f578182fd5b505080516020909101519092909150565b60008060008060608587031215613795578182fd5b843593506020850135925060408501356001600160401b038111156137b8578283fd5b6137c4878288016131d6565b95989497509550505050565b600080600080600080600060e0888a0312156137ea578081fd5b87516137f581613ce9565b602089015190975061380681613d0c565b604089015190965061381781613d1b565b606089015190955061382881613d1b565b608089015190945061383981613d1b565b925061384760a089016132b8565b915060c088015161385781613cfe565b8091505092959891949750929550565b60008060408385031215613879578182fd5b823561388481613d1b565b915060208301356133fa81613d1b565b6000602082840312156138a5578081fd5b5035919050565b600080604083850312156138be578182fd5b50508035926020909101359150565b60008060008060008060c087890312156138e5578384fd5b865195506020870151945060408701519350606087015192506080870151915060a087015190509295509295509295565b600060208284031215613927578081fd5b610d62826132b8565b60008151808452613948816020860160208601613c3b565b601f01601f19169290920160200192915050565b6000825161396e818460208701613c3b565b9190910192915050565b6000602080830181845280855180835260408601915060408160051b8701019250838701855b828110156139cc57603f198886030184526139ba858351613930565b9450928501929085019060010161399e565b5092979650505050505050565b602080825282518282018190526000919060409081850190868401855b82811015613a2457815180516001600160a01b031685528601518685015292840192908501906001016139f6565b5091979650505050505050565b602081526000610d626020830184613930565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b828152606081016040836020840137600081529392505050565b600060e0820190508782528660020b60208301528560020b604083015284606083015283608083015260408360a084013760008152979650505050505050565b604080519081016001600160401b0381118282101715613ba357613ba3613cd3565b60405290565b604051601f8201601f191681016001600160401b0381118282101715613bd157613bd1613cd3565b604052919050565b60006001600160401b03821115613bf257613bf2613cd3565b5060051b60200190565b60006001600160401b03821115613c1557613c15613cd3565b50601f01601f191660200190565b60008219821115613c3657613c36613cbd565b500190565b60005b83811015613c56578181015183820152602001613c3e565b838111156116115750506000910152565b600181811c90821680613c7b57607f821691505b60208210811415613c9c57634e487b7160e01b600052602260045260246000fd5b50919050565b6000600019821415613cb657613cb6613cbd565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052604160045260246000fd5b6001600160a01b0381168114610edf57600080fd5b8015158114610edf57600080fd5b8060020b8114610edf57600080fd5b61ffff81168114610edf57600080fdfe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122097217725fdcc4743db7d40f2dc086c6c434d94b17c5bb3c3f9ea1d77a39c98be64736f6c63430008040033

Deployed Bytecode

0x6080604052600436106103385760003560e01c806371908a03116101b2578063d0c93a7c116100ed578063e059c66011610090578063e059c66014610a72578063ee7a7c0414610a92578063eebc359a14610ab2578063f26f87ad14610ac7578063f2fde38b14610add578063f313179314610afd578063f3d2350e14610b12578063fa461e3314610b3257600080fd5b8063d0c93a7c146109bb578063d1af1ca9146103b8578063d21220a714610910578063d3487997146109db578063d7e458b5146109fb578063dd62ed3e14610a10578063de79e37414610a30578063df28408a14610a5d57600080fd5b80639cd643cc116101555780639cd643cc146108b0578063a457c2d7146108d0578063a9059cbb146108f0578063b2016bd414610910578063b390c0ab1461092f578063c45a01551461094f578063c4f2e7af1461096e578063c653089f1461098e57600080fd5b806371908a03146107cd578063727dd228146107e257806380e17d87146108115780638456cb591461083057806387788782146108455780639403c1ae1461086657806395d89b411461087b5780639b1344ac1461089057600080fd5b80633950935111610282578063528c198a11610225578063528c198a146106bb57806352d1902d146106db5780635c975abb146106f0578063601b48a4146107095780636112fe2e14610737578063628ec4db1461075757806363e968361461077757806370a082311461079757600080fd5b806339509351146105d55780633d048c27146105f55780633f4ba83a146106155780634043f5ca1461062a578063481c6a751461064a5780634a0997f4146106685780634f1ef2861461068857806351da5b171461069b57600080fd5b80631b2ef1ca116102ea5780631b2ef1ca1461044957806323b872dd146104695780632958d03114610489578063313ce5671461050e578063349e078f146105315780633659cfe614610573578063365b98b214610595578063367febea146105b557600080fd5b806306fdde031461033d57806307973ccf14610368578063095ea7b3146103885780630dfe1681146103b8578063122b6d55146103eb57806316f0115b1461041557806318160ddd14610434575b600080fd5b34801561034957600080fd5b50610352610b52565b60405161035f9190613a31565b60405180910390f35b34801561037457600080fd5b5061016b545b60405190815260200161035f565b34801561039457600080fd5b506103a86103a33660046134f1565b610be4565b604051901515815260200161035f565b3480156103c457600080fd5b50610161546001600160a01b03165b6040516001600160a01b03909116815260200161035f565b3480156103f757600080fd5b50610400610bfe565b6040805192835260208301919091520161035f565b34801561042157600080fd5b50610160546001600160a01b03166103d3565b34801561044057600080fd5b5060fd5461037a565b34801561045557600080fd5b5061037a6104643660046138ac565b610c92565b34801561047557600080fd5b506103a8610484366004613405565b610d43565b34801561049557600080fd5b506104f16104a43660046132c9565b6040805180820190915260008082526020820152506001600160a01b0316600090815261016a60209081526040918290208251808401909352805460ff1615158352600101549082015290565b60408051825115158152602092830151928101929092520161035f565b34801561051a57600080fd5b506101635460405160ff909116815260200161035f565b34801561053d57600080fd5b50610546610d69565b604080519687526020870195909552938501929092526060840152608083015260a082015260c00161035f565b34801561057f57600080fd5b5061059361058e3660046132c9565b610e10565b005b3480156105a157600080fd5b506103d36105b0366004613894565b610ee2565b3480156105c157600080fd5b506105936105d0366004613894565b610f24565b3480156105e157600080fd5b506103a86105f03660046134f1565b610f9b565b34801561060157600080fd5b50610593610610366004613492565b610fbd565b34801561062157600080fd5b50610593611617565b34801561063657600080fd5b5061016254600160e81b900460ff166103a8565b34801561065657600080fd5b5060c9546001600160a01b03166103d3565b34801561067457600080fd5b50610593610683366004613894565b611629565b610593610696366004613445565b611671565b3480156106a757600080fd5b506105936106b6366004613894565b61172b565b3480156106c757600080fd5b506105936106d63660046134f1565b611773565b3480156106e757600080fd5b5061037a61179d565b3480156106fc57600080fd5b5061012d5460ff166103a8565b34801561071557600080fd5b5061016354610100900461ffff165b60405161ffff909116815260200161035f565b34801561074357600080fd5b50610593610752366004613894565b61184b565b34801561076357600080fd5b5061037a610772366004613894565b611893565b34801561078357600080fd5b50610400610792366004613702565b611921565b3480156107a357600080fd5b5061037a6107b23660046132c9565b6001600160a01b0316600090815260fb602052604090205490565b3480156107d957600080fd5b506104006119cc565b3480156107ee57600080fd5b5061016254600160b81b900460020b5b60405160029190910b815260200161035f565b34801561081d57600080fd5b50610165546001600160a01b03166103d3565b34801561083c57600080fd5b50610593611a0a565b34801561085157600080fd5b50610163546301000000900461ffff16610724565b34801561087257600080fd5b50610593611a1a565b34801561088757600080fd5b50610352611aab565b34801561089c57600080fd5b5061016254600160a01b900460020b6107fe565b3480156108bc57600080fd5b506105936108cb366004613688565b611aba565b3480156108dc57600080fd5b506103a86108eb3660046134f1565b611afd565b3480156108fc57600080fd5b506103a861090b3660046134f1565b611b83565b34801561091c57600080fd5b50610162546001600160a01b03166103d3565b34801561093b57600080fd5b5061037a61094a3660046138ac565b611b91565b34801561095b57600080fd5b5061015f546001600160a01b03166103d3565b34801561097a57600080fd5b506105936109893660046138ac565b611be9565b34801561099a57600080fd5b506109ae6109a93660046138ac565b611c68565b60405161035f91906139d9565b3480156109c757600080fd5b5061016254600160d01b900460020b6107fe565b3480156109e757600080fd5b506105936109f6366004613780565b611d01565b348015610a0757600080fd5b50610593611d7a565b348015610a1c57600080fd5b5061037a610a2b3660046133cd565b611dbb565b348015610a3c57600080fd5b50610a50610a4b36600461351c565b611de6565b60405161035f9190613978565b348015610a6957600080fd5b5061037a611f7d565b348015610a7e57600080fd5b50610400610a8d3660046136a3565b61200a565b348015610a9e57600080fd5b50610593610aad3660046134f1565b6120ca565b348015610abe57600080fd5b5061037a6120f4565b348015610ad357600080fd5b506101645461037a565b348015610ae957600080fd5b50610593610af83660046132c9565b612130565b348015610b0957600080fd5b506104006121a8565b348015610b1e57600080fd5b50610593610b2d366004613867565b6122e4565b348015610b3e57600080fd5b50610593610b4d366004613780565b612337565b606060fe8054610b6190613c67565b80601f0160208091040260200160405190810160405280929190818152602001828054610b8d90613c67565b8015610bda5780601f10610baf57610100808354040283529160200191610bda565b820191906000526020600020905b815481529060010190602001808311610bbd57829003601f168201915b5050505050905090565b600033610bf281858561237e565b60019150505b92915050565b6040516001620adc9960e31b0319815261015f60048201526000908190730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063ffa91b38906024015b604080518083038186803b158015610c5257600080fd5b505af4158015610c66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c8a919061375d565b915091509091565b6000610c9c6124a2565b610ca46124fc565b60405163d1ee9bfd60e01b815261015f60048201526024810184905260448101839052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063d1ee9bfd906064015b60206040518083038186803b158015610cff57600080fd5b505af4158015610d13573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d3791906136ea565b9050610bf86001606555565b600033610d5185828561254a565b610d5c8585856125be565b60019150505b9392505050565b600080600080600080730a0b5f2bccbf50f1ccf7477c8ad2362312480c5163feaadfd361015f6040518263ffffffff1660e01b8152600401610dad91815260200190565b60c06040518083038186803b158015610dc557600080fd5b505af4158015610dd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dfd91906138cd565b949b939a50919850965094509092509050565b306001600160a01b037f000000000000000000000000e5acbf87a4403c954186e5234b6d237333540735161415610e625760405162461bcd60e51b8152600401610e5990613a44565b60405180910390fd5b7f000000000000000000000000e5acbf87a4403c954186e5234b6d2373335407356001600160a01b0316610e94612762565b6001600160a01b031614610eba5760405162461bcd60e51b8152600401610e5990613a90565b610ec38161277e565b60408051600080825260208201909252610edf918391906127aa565b50565b600061015f600c018281548110610f0957634e487b7160e01b600052603260045260246000fd5b6000918252602090912001546001600160a01b031692915050565b610f2c612929565b604051630decace760e01b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190630decace7906044015b60006040518083038186803b158015610f8057600080fd5b505af4158015610f94573d6000803e3d6000fd5b5050505050565b600033610bf2818585610fae8383611dbb565b610fb89190613c23565b61237e565b600054610100900460ff1615808015610fdd5750600054600160ff909116105b80610ff75750303b158015610ff7575060005460ff166001145b61105a5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610e59565b6000805460ff19166001179055801561107d576000805461ff0019166101001790555b60008060008060008060008060008a80602001905181019061109f9190613301565b9850985098509850985098509850985098506110b961298e565b6110c16129b5565b6110c96129e4565b6110d38888612a13565b6110db612a44565b6110e489612a73565b6001600160a01b03891661110b57604051636ba0d85d60e11b815260040160405180910390fd5b856001600160a01b03168d6001600160a01b0316630dfe16816040518163ffffffff1660e01b815260040160206040518083038186803b15801561114e57600080fd5b505afa158015611162573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061118691906132e5565b6001600160a01b0316146111ad5760405163e402fd1560e01b815260040160405180910390fd5b61016080546001600160a01b0319166001600160a01b038f1690811790915560408051630dfe168160e01b8152905160009291630dfe1681916004808301926020929190829003018186803b15801561120557600080fd5b505afa158015611219573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061123d91906132e5565b9050600061015f60010160009054906101000a90046001600160a01b03166001600160a01b031663d21220a76040518163ffffffff1660e01b815260040160206040518083038186803b15801561129357600080fd5b505afa1580156112a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cb91906132e5565b90508161015f60020160006101000a8154816001600160a01b0302191690836001600160a01b031602179055508061015f60030160006101000a8154816001600160a01b0302191690836001600160a01b031602179055508d61015f600301601a6101000a81548162ffffff021916908360020b62ffffff1602179055503361015f60000160006101000a8154816001600160a01b0302191690836001600160a01b031602179055506000826001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b1580156113af57600080fd5b505afa1580156113c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e79190613916565b90506000826001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561142457600080fd5b505afa158015611438573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061145c9190613916565b610162805460ff808416600160f81b026001600160f81b03918716600160f01b02919091166001600160f01b039092169190911717905561016580546001600160a01b03808d166001600160a01b0319928316179092556040805180820182528c841680825260209182018d90526101668054851690911790556101678c905581518083019092528a841680835291018990526101688054909216179055610169879055909150848116908b161461152457610163805460ff191660ff841617905581611536565b610163805460ff191660ff8316179055805b610163805460ff191660ff92909216919091179055604051631262ee9360e01b815261015f6004820152600a60248201526103e86044820152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190631262ee939060640160006040518083038186803b1580156115a657600080fd5b505af41580156115ba573d6000803e3d6000fd5b50505050505050505050505050505050508015611611576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b61161f612929565b611627612ac5565b565b611631612929565b60405163aa14b15360e01b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063aa14b15390604401610f68565b306001600160a01b037f000000000000000000000000e5acbf87a4403c954186e5234b6d2373335407351614156116ba5760405162461bcd60e51b8152600401610e5990613a44565b7f000000000000000000000000e5acbf87a4403c954186e5234b6d2373335407356001600160a01b03166116ec612762565b6001600160a01b0316146117125760405162461bcd60e51b8152600401610e5990613a90565b61171b8261277e565b611727828260016127aa565b5050565b611733612929565b60405163388bfeed60e21b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063e22ffbb490604401610f68565b33301461179357604051631628c08760e31b815260040160405180910390fd5b6117278282612b18565b6000306001600160a01b037f000000000000000000000000e5acbf87a4403c954186e5234b6d23733354073516146118385760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c6044820152771b1959081d1a1c9bdd59da0819195b1959d85d1958d85b1b60421b6064820152608401610e59565b50600080516020613d2c83398151915290565b611853612929565b604051637fec8ad360e01b815261015f600482015260248101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190637fec8ad390604401610f68565b6040516356d9182d60e11b815261015f600482015260248101829052600090730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063adb2305a9060440160206040518083038186803b1580156118e957600080fd5b505af41580156118fd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf891906136ea565b60008061192c612929565b604051631b63a06d60e21b8152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190636d8e81b49061196f9061015f908b908b908b908b908b90600401613b41565b604080518083038186803b15801561198657600080fd5b505af415801561199a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119be919061375d565b915091509550959350505050565b60405163812c13f360e01b815261015f60048201526000908190730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063812c13f390602401610c3b565b611a12612929565b611627612bd3565b611a22612929565b730a0b5f2bccbf50f1ccf7477c8ad2362312480c5163a4dc445d61015f611a5160c9546001600160a01b031690565b6040516001600160e01b031960e085901b16815260048101929092526001600160a01b031660248201526044015b60006040518083038186803b158015611a9757600080fd5b505af4158015611611573d6000803e3d6000fd5b606060ff8054610b6190613c67565b611ac2612929565b60405163c8ce5eb760e01b8152730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063c8ce5eb790610f689061015f908590600401613b27565b60003381611b0b8286611dbb565b905083811015611b6b5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610e59565b611b78828686840361237e565b506001949350505050565b600033610bf28185856125be565b6000611b9b6124a2565b611ba36124fc565b6040516293442f60e11b815261015f60048201526024810184905260448101839052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190630126885e90606401610ce7565b611bf1612929565b6040516331038ee160e21b815261015f60048201526024810183905260448101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063c40e3b84906064015b60006040518083038186803b158015611c4c57600080fd5b505af4158015611c60573d6000803e3d6000fd5b505050505050565b604051637db1f66560e11b815261015f60048201526024810183905260448101829052606090730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063fb63ecca9060640160006040518083038186803b158015611cc557600080fd5b505af4158015611cd9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610d6291908101906135cc565b604051635692f48560e01b815261015f60048201526024810185905260448101849052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190635692f485906064015b60006040518083038186803b158015611d5c57600080fd5b505af4158015611d70573d6000803e3d6000fd5b5050505050505050565b611d82612929565b604051637436b83560e01b815261015f6004820152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190637436b83590602401611a7f565b6001600160a01b03918216600090815260fc6020908152604080832093909416825291909152205490565b6060611df0612929565b81516001600160401b03811115611e1757634e487b7160e01b600052604160045260246000fd5b604051908082528060200260200182016040528015611e4a57816020015b6060815260200190600190039081611e355790505b50905060005b8251811015611f4e57600080306001600160a01b0316858481518110611e8657634e487b7160e01b600052603260045260246000fd5b6020026020010151604051611e9b919061395c565b600060405180830381855af49150503d8060008114611ed6576040519150601f19603f3d011682016040523d82523d6000602084013e611edb565b606091505b509150915081611f0d57805115611ef457805181602001fd5b604051637c83e73360e11b815260040160405180910390fd5b80848481518110611f2e57634e487b7160e01b600052603260045260246000fd5b602002602001018190525050508080611f4690613ca2565b915050611e50565b506040517ff1441a081a033a01c1623ac6a2ca24f2cc88f9b4a47b112e006f4838f9c4e52e90600090a1919050565b604051633081559960e11b815261015f6004820152600090730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190636102ab32906024015b60206040518083038186803b158015611fcd57600080fd5b505af4158015611fe1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061200591906136ea565b905090565b600080612015612929565b60405163646bd58560e01b815261015f60048201528615156024820152604481018690526001600160a01b038516606482015260848101849052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063646bd5859060a401604080518083038186803b15801561208557600080fd5b505af4158015612099573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120bd919061375d565b9150915094509492505050565b3330146120ea57604051631628c08760e31b815260040160405180910390fd5b6117278282612c11565b60405163fea8519360e01b815261015f6004820152600090730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063fea8519390602401611fb5565b612138612929565b6001600160a01b03811661219f5760405162461bcd60e51b815260206004820152602860248201527f4f776e61626c653a206e6577206d616e6167657220697320746865207a65726f604482015267206164647265737360c01b6064820152608401610e59565b610edf81612a73565b6101605460408051633850c7bd60e01b815290516000928392839283926001600160a01b031691633850c7bd9160048083019260e0929190829003018186803b1580156121f457600080fd5b505afa158015612208573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061222c91906137d0565b505060405163add9d74d60e01b815261015f60048201526001600160a01b0386166024820152600285900b6044820152949650929450730a0b5f2bccbf50f1ccf7477c8ad2362312480c519363add9d74d9350606401915061228b9050565b604080518083038186803b1580156122a257600080fd5b505af41580156122b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122da919061375d565b9350935050509091565b6122ec612929565b604051631262ee9360e01b815261015f600482015261ffff808416602483015282166044820152730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190631262ee9390606401611c34565b604051632fa1b90960e11b815261015f60048201526024810185905260448101849052730a0b5f2bccbf50f1ccf7477c8ad2362312480c5190635f43721290606401611d44565b6001600160a01b0383166123e05760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610e59565b6001600160a01b0382166124415760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610e59565b6001600160a01b03838116600081815260fc602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600260655414156124f55760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610e59565b6002606555565b61012d5460ff16156116275760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401610e59565b6001606555565b60006125568484611dbb565b9050600019811461161157818110156125b15760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610e59565b611611848484840361237e565b6001600160a01b0383166126225760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610e59565b6001600160a01b0382166126845760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610e59565b61268f838383612d3f565b6001600160a01b038316600090815260fb6020526040902054818110156127075760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610e59565b6001600160a01b03808516600081815260fb60205260408082208686039055928616808252908390208054860190559151600080516020613d73833981519152906127559086815260200190565b60405180910390a3611611565b600080516020613d2c833981519152546001600160a01b031690565b61015f546001600160a01b03163314610edf57604051631b1319e560e01b815260040160405180910390fd5b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156127e2576127dd83612dc6565b505050565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561281b57600080fd5b505afa92505050801561284b575060408051601f3d908101601f19168201909252612848918101906136ea565b60015b6128ae5760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201526d6f6e206973206e6f74205555505360901b6064820152608401610e59565b600080516020613d2c833981519152811461291d5760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f786044820152681a58589b195555525160ba1b6064820152608401610e59565b506127dd838383612e62565b60c9546001600160a01b031633146116275760405162461bcd60e51b815260206004820152602260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206d616e616760448201526132b960f11b6064820152608401610e59565b600054610100900460ff166116275760405162461bcd60e51b8152600401610e5990613adc565b600054610100900460ff166129dc5760405162461bcd60e51b8152600401610e5990613adc565b611627612e87565b600054610100900460ff16612a0b5760405162461bcd60e51b8152600401610e5990613adc565b611627612eae565b600054610100900460ff16612a3a5760405162461bcd60e51b8152600401610e5990613adc565b6117278282612ede565b600054610100900460ff16612a6b5760405162461bcd60e51b8152600401610e5990613adc565b611627612f2c565b60c980546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b612acd612f60565b61012d805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6001600160a01b038216612b6e5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610e59565b612b7a60008383612d3f565b8060fd6000828254612b8c9190613c23565b90915550506001600160a01b038216600081815260fb6020908152604080832080548601905551848152600080516020613d73833981519152910160405180910390a35050565b612bdb6124fc565b61012d805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612afb3390565b6001600160a01b038216612c715760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610e59565b612c7d82600083612d3f565b6001600160a01b038216600090815260fb602052604090205481811015612cf15760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610e59565b6001600160a01b038316600081815260fb60209081526040808320868603905560fd8054879003905551858152919291600080516020613d73833981519152910160405180910390a3505050565b60405163f7c2522960e01b815261015f60048201526001600160a01b0380851660248301528316604482015260648101829052730a0b5f2bccbf50f1ccf7477c8ad2362312480c519063f7c252299060840160006040518083038186803b158015612da957600080fd5b505af4158015612dbd573d6000803e3d6000fd5b50505050505050565b6001600160a01b0381163b612e335760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b6064820152608401610e59565b600080516020613d2c83398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b612e6b83612faa565b600082511180612e785750805b156127dd576116118383612fea565b600054610100900460ff166125435760405162461bcd60e51b8152600401610e5990613adc565b600054610100900460ff16612ed55760405162461bcd60e51b8152600401610e5990613adc565b61162733612a73565b600054610100900460ff16612f055760405162461bcd60e51b8152600401610e5990613adc565b8151612f189060fe90602085019061311c565b5080516127dd9060ff90602084019061311c565b600054610100900460ff16612f535760405162461bcd60e51b8152600401610e5990613adc565b61012d805460ff19169055565b61012d5460ff166116275760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610e59565b612fb381612dc6565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b60606001600160a01b0383163b6130525760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b6064820152608401610e59565b600080846001600160a01b03168460405161306d919061395c565b600060405180830381855af49150503d80600081146130a8576040519150601f19603f3d011682016040523d82523d6000602084013e6130ad565b606091505b50915091506130d58282604051806060016040528060278152602001613d4c602791396130de565b95945050505050565b606083156130ed575081610d62565b610d6283838151156131025781518083602001fd5b8060405162461bcd60e51b8152600401610e599190613a31565b82805461312890613c67565b90600052602060002090601f01602090048101928261314a5760008555613190565b82601f1061316357805160ff1916838001178555613190565b82800160010185558215613190579182015b82811115613190578251825591602001919060010190613175565b5061319c9291506131a0565b5090565b5b8082111561319c57600081556001016131a1565b80516131c081613ce9565b919050565b8060408101831015610bf857600080fd5b60008083601f8401126131e7578182fd5b5081356001600160401b038111156131fd578182fd5b60208301915083602082850101111561321557600080fd5b9250929050565b600082601f83011261322c578081fd5b813561323f61323a82613bfc565b613ba9565b818152846020838601011115613253578283fd5b816020850160208301379081016020019190915292915050565b600082601f83011261327d578081fd5b815161328b61323a82613bfc565b81815284602083860101111561329f578283fd5b6132b0826020830160208701613c3b565b949350505050565b805160ff811681146131c057600080fd5b6000602082840312156132da578081fd5b8135610d6281613ce9565b6000602082840312156132f6578081fd5b8151610d6281613ce9565b60008060008060008060008060006101208a8c03121561331f578485fd5b895161332a81613ce9565b60208b01519099506001600160401b0380821115613346578687fd5b6133528d838e0161326d565b995060408c0151915080821115613367578687fd5b506133748c828d0161326d565b97505060608a015161338581613ce9565b955061339360808b016131b5565b94506133a160a08b016131b5565b935060c08a015192506133b660e08b016131b5565b91506101008a015190509295985092959850929598565b600080604083850312156133df578182fd5b82356133ea81613ce9565b915060208301356133fa81613ce9565b809150509250929050565b600080600060608486031215613419578081fd5b833561342481613ce9565b9250602084013561343481613ce9565b929592945050506040919091013590565b60008060408385031215613457578182fd5b823561346281613ce9565b915060208301356001600160401b0381111561347c578182fd5b6134888582860161321c565b9150509250929050565b6000806000606084860312156134a6578081fd5b83356134b181613ce9565b925060208401356134c181613d0c565b915060408401356001600160401b038111156134db578182fd5b6134e78682870161321c565b9150509250925092565b60008060408385031215613503578182fd5b823561350e81613ce9565b946020939093013593505050565b6000602080838503121561352e578182fd5b82356001600160401b0380821115613544578384fd5b818501915085601f830112613557578384fd5b813561356561323a82613bd9565b80828252858201915085850189878560051b8801011115613584578788fd5b875b848110156135bd5781358681111561359c57898afd5b6135aa8c8a838b010161321c565b8552509287019290870190600101613586565b50909998505050505050505050565b600060208083850312156135de578182fd5b82516001600160401b038111156135f3578283fd5b8301601f81018513613603578283fd5b805161361161323a82613bd9565b80828252848201915084840188868560061b8701011115613630578687fd5b8694505b8385101561367c57604080828b03121561364c578788fd5b613654613b81565b825161365f81613ce9565b815282880151888201528452600195909501949286019201613634565b50979650505050505050565b600060408284031215613699578081fd5b610d6283836131c5565b600080600080608085870312156136b8578182fd5b84356136c381613cfe565b93506020850135925060408501356136da81613ce9565b9396929550929360600135925050565b6000602082840312156136fb578081fd5b5051919050565b600080600080600060c08688031215613719578283fd5b853561372481613d0c565b9450602086013561373481613d0c565b9350604086013592506060860135915061375187608088016131c5565b90509295509295909350565b6000806040838503121561376f578182fd5b505080516020909101519092909150565b60008060008060608587031215613795578182fd5b843593506020850135925060408501356001600160401b038111156137b8578283fd5b6137c4878288016131d6565b95989497509550505050565b600080600080600080600060e0888a0312156137ea578081fd5b87516137f581613ce9565b602089015190975061380681613d0c565b604089015190965061381781613d1b565b606089015190955061382881613d1b565b608089015190945061383981613d1b565b925061384760a089016132b8565b915060c088015161385781613cfe565b8091505092959891949750929550565b60008060408385031215613879578182fd5b823561388481613d1b565b915060208301356133fa81613d1b565b6000602082840312156138a5578081fd5b5035919050565b600080604083850312156138be578182fd5b50508035926020909101359150565b60008060008060008060c087890312156138e5578384fd5b865195506020870151945060408701519350606087015192506080870151915060a087015190509295509295509295565b600060208284031215613927578081fd5b610d62826132b8565b60008151808452613948816020860160208601613c3b565b601f01601f19169290920160200192915050565b6000825161396e818460208701613c3b565b9190910192915050565b6000602080830181845280855180835260408601915060408160051b8701019250838701855b828110156139cc57603f198886030184526139ba858351613930565b9450928501929085019060010161399e565b5092979650505050505050565b602080825282518282018190526000919060409081850190868401855b82811015613a2457815180516001600160a01b031685528601518685015292840192908501906001016139f6565b5091979650505050505050565b602081526000610d626020830184613930565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b828152606081016040836020840137600081529392505050565b600060e0820190508782528660020b60208301528560020b604083015284606083015283608083015260408360a084013760008152979650505050505050565b604080519081016001600160401b0381118282101715613ba357613ba3613cd3565b60405290565b604051601f8201601f191681016001600160401b0381118282101715613bd157613bd1613cd3565b604052919050565b60006001600160401b03821115613bf257613bf2613cd3565b5060051b60200190565b60006001600160401b03821115613c1557613c15613cd3565b50601f01601f191660200190565b60008219821115613c3657613c36613cbd565b500190565b60005b83811015613c56578181015183820152602001613c3e565b838111156116115750506000910152565b600181811c90821680613c7b57607f821691505b60208210811415613c9c57634e487b7160e01b600052602260045260246000fd5b50919050565b6000600019821415613cb657613cb6613cbd565b5060010190565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052604160045260246000fd5b6001600160a01b0381168114610edf57600080fd5b8015158114610edf57600080fd5b8060020b8114610edf57600080fd5b61ffff81168114610edf57600080fdfe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa264697066735822122097217725fdcc4743db7d40f2dc086c6c434d94b17c5bb3c3f9ea1d77a39c98be64736f6c63430008040033

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

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

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