ETH Price: $3,691.61 (+1.64%)
 

Overview

Max Total Supply

1,282,484,170.807424742690671489 ULTI

Holders

1,266

Total Transfers

-

Market

Onchain Market Cap

$0.00

Circulating Supply Market Cap

-

Other Info

Token Contract (WITH 18 Decimals)

Loading...
Loading
Loading...
Loading
Loading...
Loading

Click here to update the token information / general information
# Exchange Pair Price  24H Volume % Volume

Contract Source Code Verified (Exact Match)

Contract Name:
ULTI

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
File 1 of 48 : ULTI.sol
// SPDX-License-Identifier: MIT

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// 1. The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 2. Any use, reproduction, or distribution of this Software, in whole or in part,
// must include clear and appropriate attribution to @0xStef as the original author.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// ██╗   ██╗██╗  ████████╗██╗    ██╗███████╗    ██╗   ██╗███╗   ██╗██╗ ██████╗ ██╗   ██╗███████╗
// ██║   ██║██║  ╚══██╔══╝██║    ██║██╔════╝    ██║   ██║████╗  ██║██║██╔═══██╗██║   ██║██╔════╝
// ██║   ██║██║     ██║   ██║    ██║███████╗    ██║   ██║██╔██╗ ██║██║██║   ██║██║   ██║█████╗
// ██║   ██║██║     ██║   ██║    ██║╚════██║    ██║   ██║██║╚██╗██║██║██║▄▄ ██║██║   ██║██╔══╝
// ╚██████╔╝███████╗██║   ██║    ██║███████║    ╚██████╔╝██║ ╚████║██║╚██████╔╝╚██████╔╝███████╗
//  ╚═════╝ ╚══════╝╚═╝   ╚═╝    ╚═╝╚══════╝     ╚═════╝ ╚═╝  ╚═══╝╚═╝ ╚══▀▀═╝  ╚═════╝ ╚══════╝

// ██╗   ██╗██╗  ████████╗██╗    ██╗███████╗    ███████╗ ██████╗ ██████╗     ███████╗██╗   ██╗███████╗██████╗ ██╗   ██╗ ██████╗ ███╗   ██╗███████╗
// ██║   ██║██║  ╚══██╔══╝██║    ██║██╔════╝    ██╔════╝██╔═══██╗██╔══██╗    ██╔════╝██║   ██║██╔════╝██╔══██╗╚██╗ ██╔╝██╔═══██╗████╗  ██║██╔════╝
// ██║   ██║██║     ██║   ██║    ██║███████╗    █████╗  ██║   ██║██████╔╝    █████╗  ██║   ██║█████╗  ██████╔╝ ╚████╔╝ ██║   ██║██╔██╗ ██║█████╗
// ██║   ██║██║     ██║   ██║    ██║╚════██║    ██╔══╝  ██║   ██║██╔══██╗    ██╔══╝  ╚██╗ ██╔╝██╔══╝  ██╔══██╗  ╚██╔╝  ██║   ██║██║╚██╗██║██╔══╝
// ╚██████╔╝███████╗██║   ██║    ██║███████║    ██║     ╚██████╔╝██║  ██║    ███████╗ ╚████╔╝ ███████╗██║  ██║   ██║   ╚██████╔╝██║ ╚████║███████╗
//  ╚═════╝ ╚══════╝╚═╝   ╚═╝    ╚═╝╚══════╝    ╚═╝      ╚═════╝ ╚═╝  ╚═╝    ╚══════╝  ╚═══╝  ╚══════╝╚═╝  ╚═╝   ╚═╝    ╚═════╝ ╚═╝  ╚═══╝╚══════╝

// ██╗   ██╗██╗  ████████╗██╗    ██╗███████╗     ██╗ ██╗ ██████╗ ██╗   ██╗██████╗ ███████╗██████╗ ███████╗███████╗██╗
// ██║   ██║██║  ╚══██╔══╝██║    ██║██╔════╝    ████████╗██╔══██╗██║   ██║██╔══██╗██╔════╝██╔══██╗██╔════╝██╔════╝██║
// ██║   ██║██║     ██║   ██║    ██║███████╗    ╚██╔═██╔╝██████╔╝██║   ██║██████╔╝█████╗  ██║  ██║█████╗  █████╗  ██║
// ██║   ██║██║     ██║   ██║    ██║╚════██║    ████████╗██╔═══╝ ██║   ██║██╔══██╗██╔══╝  ██║  ██║██╔══╝  ██╔══╝  ██║
// ╚██████╔╝███████╗██║   ██║    ██║███████║    ╚██╔═██╔╝██║     ╚██████╔╝██║  ██║███████╗██████╔╝███████╗██║     ██║
//  ╚═════╝ ╚══════╝╚═╝   ╚═╝    ╚═╝╚══════╝     ╚═╝ ╚═╝ ╚═╝      ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═════╝ ╚══════╝╚═╝     ╚═╝

// ULTI IS UNIQUE, ULTI IS FOR EVERYONE, ULTI IS #PureDeFi

// @author: @0xStef
pragma solidity 0.8.28;

// OpenZeppelin contracts
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {EnumerableMap} from "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

// Uniswap V3 interfaces and libraries
import {IUniswapV3Factory} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {ISwapRouter} from "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";

// Modified Uniswap V3 interfaces and libraries to reconcile compatibility issues
import {INonfungiblePositionManager} from "./lib/uniswap/INonfungiblePositionManager.sol";
import {TickMath} from "./lib/uniswap/TickMath.sol";
import {OracleLibrary} from "./lib/uniswap/Oracle.sol";
import {LiquidityAmounts} from "./lib/uniswap/LiquidityAmounts.sol";

// Third-party interfaces
import {IWrappedNative} from "./interfaces/IWrappedNative.sol";

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

// Custom errors
error LiquidityPoolAlreadyExists();
error LiquidityPositionAlreadyExists();
error LiquidityPositionNotInitialized();
error DepositExpired();
error DepositCooldownActive();
error DepositNativeNotSupported();
error DepositInsufficientAmount();
error DepositCannotReferSelf();
error DepositCircularReferral();
error DepositInsufficientUltiAllocation();
error DepositLiquidityInsufficientEthAmount();
error DepositLiquidityInsufficientUltiAmount();
error ClaimUltiCooldownActive();
error ClaimUltiEmpty();
error PumpCooldownActive();
error PumpOnlyForTopContributors();
error PumpMaxPumpsReached();
error PumpInsufficientInputTokenAmount();
error PumpInsufficientMinimumUltiAmount();
error PumpInsufficientUltiOutput();
error PumpExpired();
error ClaimAllBonusesCooldownActive();
error ClaimAllBonusesEmpty();
error SnipingProctectionInvalidDayInCycle(uint8 dayInCycle);
error TWAPCalculationFailed();

/// @custom:security-contact [email protected]
contract ULTI is ERC20, Ownable, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableMap for EnumerableMap.AddressToUintMap;

    // ===============================================
    // State Variables
    // ===============================================

    /// @notice Instance of the Uniswap V3 Factory contract
    IUniswapV3Factory public immutable uniswapFactory;

    /// @notice Instance of the Uniswap V3 SwapRouter contract
    ISwapRouter public immutable uniswapRouter;

    /// @notice Instance of the Uniswap V3 NonfungiblePositionManager contract
    INonfungiblePositionManager public immutable nonfungiblePositionManager;

    /// @notice Address of the input token (e.g. WETH, DAI, etc.)
    address public immutable inputTokenAddress;

    /// @notice Address of the wrapped native token (e.g. WETH, WBNB, etc.) to optionally enable depositNative()
    address public immutable wrappedNativeTokenAddress;

    /// @notice Flag indicating if ULTI is token0 in the liquidity pool
    bool public immutable isUltiToken0;

    /// @notice Initial ratio ULTI:INPUT_TOKEN
    /// @dev This value is scaled by the input token's decimals in the constructor
    uint256 public immutable initialRatio;

    /// @notice Minimum amount required for a deposit to be valid
    /// @dev Economic considerations for minimum deposit:
    /// - Consider future price appreciation of the input token vs. stable coins (USD) to prevent excluding users globally
    /// - Avoid setting it too low to prevent the streak bonus being easily gamed
    uint256 public immutable minimumDepositAmount;

    /// @notice Minimum number of observations required for TWAP calculation
    /// @dev This provides granularity for the 18m9s (1089s) TWAP window.
    /// For reference:
    /// - At 12s blocks: stores 1,152s (19.2 min) of price history (Ethereum mainnet case)
    /// - At 1s blocks: stores 96s (1.6 min) of price history
    /// - At 0.2s blocks: stores 19.2s of price history
    /// Even with partial coverage for fast networks, multiple observations still provide manipulation resistance
    uint16 public immutable minimumTwapObservations;

    /// @notice Uniswap V3 pool for the liquidity. Immutable pool held by the contract
    IUniswapV3Pool public liquidityPool;

    /// @notice Token ID of the Uniswap V3 position
    uint256 public liquidityPositionTokenId;

    /// @notice Timestamp when ULTI was launched
    uint64 public launchTimestamp;

    /// @notice Timestamp of the last pump action
    uint64 public nextPumpTimestamp;

    // ===============================================
    // Mappings
    // ===============================================

    /// @notice Stores the allocated amount of ULTI tokens claimable by each user
    /// @dev User address => Allocated ULTI to claim in the future
    mapping(address user => uint256 allocatedAmount) public claimableUlti;

    /// @notice Stores the amount of all allocated bonuses for claim in the future for each user (including referral, top contributor, and streak bonuses)
    /// @dev User address => Total claimable bonuses
    mapping(address user => uint256 bonuses) public claimableBonuses;

    /// @notice Tracks the next allowed timestamp for ULTI claim or deposit for each user
    /// @dev User address => Next allowed claim or deposit timestamp
    mapping(address user => uint256 nextDepositOrClaimTimestamp) public nextDepositOrClaimTimestamp;

    /// @notice Stores the referrer address for each user
    /// @dev User address => Referrer address
    mapping(address user => address referrer) public referrers;

    /// @notice Stores the timestamp of the next bonuses claim for each user
    /// @dev User address => Last claim timestamp
    mapping(address user => uint256 nextAllBonusesClaimTimestamp) public nextAllBonusesClaimTimestamp;

    /// @notice Stores the total ULTI ever allocated to a user during deposits to calculate the Skin-in-the-Game cap (excluding top contributor and referral bonuses)
    /// @dev User address => Total allocated ULTI
    mapping(address user => uint256 totalUltiAllocatedEver) public totalUltiAllocatedEver;

    /// @notice Stores the amount of referral bonuses accumulated by each user
    /// @dev User address => Total referral bonuses accumulated
    mapping(address user => uint256 referralBonuses) public accumulatedReferralBonuses;

    /// @notice Stores the amount of input token deposited by each user for each cycle
    /// @dev Cycle => User address => input token deposited
    mapping(uint32 cycle => mapping(address user => uint256 inputTokenDeposited)) public totalInputTokenDeposited;

    /// @notice Stores the amount of input token referred by each user for each cycle
    /// @dev Cycle => User address => input token referred
    mapping(uint32 cycle => mapping(address user => uint256 inputTokenReferred)) public totalInputTokenReferred;

    /// @notice Stores the amount of ULTI minted for each user for each cycle
    /// @dev Cycle => User address => ULTI minted
    mapping(uint32 cycle => mapping(address user => uint256 ultiAllocated)) public totalUltiAllocated;

    /// @notice Stores the streak count for each user for each cycle
    /// @dev Cycle => User address => Streak count
    /// @dev Note: For the current cycle, the streak count is loosely tracked and depends on the user making a deposit.
    ///      The count is only finalized and confirmed when the user makes their first deposit in the next cycle.
    ///      This means a user could technically have participated in the previous cycle but if they haven't deposited
    ///      in the current cycle yet, their streak value will remain 0 until they do.
    mapping(uint32 cycle => mapping(address user => uint32 streakCount)) public streakCounts;

    /// @notice Stores the discounted contribution for each user for each cycle
    /// @dev Cycle => User address => Discounted ULTI contribution
    mapping(uint32 cycle => mapping(address user => uint256 discountedContribution)) public discountedContributions;

    /// @notice Stores the top contributors and their discounted contributions for each cycle
    /// @dev Cycle => Map of top contributors and their respective discounted contribution
    mapping(uint32 cycle => EnumerableMap.AddressToUintMap topContributors) private topContributors;

    /// @notice Stores the address of the minimum contributor for each cycle
    /// @dev Cycle => Address of the minimum contributor
    mapping(uint32 cycle => address minContributorAddress) public minContributorAddress;

    /// @notice Stores the minimum discounted contribution for top contributors for each cycle
    /// @dev Cycle => Minimum discounted contribution
    mapping(uint32 cycle => uint256 minDiscountedContribution) public minDiscountedContribution;

    /// @notice Stores the total bonuses for top contributors for each cycle
    /// @dev Cycle => Total bonuses for top contributors
    mapping(uint32 cycle => uint256 topContributorsBonuses) public topContributorsBonuses;

    /// @notice Indicates whether top contributors' bonuses have been allocated for a given cycle
    /// @dev Cycle => Whether bonuses have been allocated
    mapping(uint32 cycle => bool isTopContributorsBonusAllocated) public isTopContributorsBonusAllocated;

    /// @notice Stores the set of addresses that have pumped for each cycle
    /// @dev Cycle => Set of addresses that have pumped
    mapping(uint32 cycle => EnumerableSet.AddressSet pumpers) private pumpers;

    /// @notice Stores the number of pumps performed by each user for each cycle
    /// @dev Cycle => User address => Number of pumps performed
    mapping(uint32 cycle => mapping(address user => uint16 pumpCount)) public pumpCounts;

    // ===============================================
    // Events
    // ===============================================

    /// @notice Emitted when the ULTI token is launched
    /// @param founderGiveaway Amount of input token given away by the founder
    /// @param lpAddress Address of the created liquidity pool
    event Launched(uint256 founderGiveaway, address lpAddress);

    /// @notice Emitted when a user deposits input token and receives ULTI tokens
    /// @param cycle The current cycle number
    /// @param user The address of the user who made the deposit
    /// @param referrer The address of the user's referrer (if any)
    /// @param inputTokenDeposited The amount of input token deposited
    /// @param inputTokenForLP The amount of input token tokens deposited into the liquidity position
    /// @param ultiForLP The amount of ULTI tokens to mint for the liquidity position
    /// @param ultiForUser The amount of ULTI tokens to mint for the user without bonus
    /// @param streakBonus The amount of ULTI tokens awarded as streak bonus
    /// @param streakCount The number of consecutive cycles the user has deposited
    /// @param referrerBonus The amount of ULTI tokens awarded to the referrer
    /// @param referredBonus The amount of ULTI tokens awarded to the referred user
    /// @param autoClaimed Whether the ULTI tokens were automatically claimed as part of the deposit
    /// @param cycleContribution The discounted contribution of the user for the cycle
    event Deposited(
        uint32 indexed cycle,
        address indexed user,
        address indexed referrer,
        uint256 inputTokenDeposited,
        uint256 inputTokenForLP,
        uint256 ultiForLP,
        uint256 ultiForUser,
        uint256 streakBonus,
        uint32 streakCount,
        uint256 referrerBonus,
        uint256 referredBonus,
        bool autoClaimed,
        uint256 cycleContribution
    );

    /// @notice Emitted when a user claims their ULTI tokens
    /// @param cycle The current cycle number
    /// @param user The address of the user claiming tokens
    /// @param amount The amount of ULTI tokens claimed
    event Claimed(uint32 indexed cycle, address indexed user, uint256 amount);

    /// @notice Emitted when a pump action is executed
    /// @param cycle The current cycle number
    /// @param user The address of the user who executed the pump
    /// @param inputTokenToSwap The amount of input token used for the pump
    /// @param ultiBurned The amount of ULTI tokens burned during the pump
    /// @param pumpCount The number of times the user has pumped in this cycle
    /// @param twap The current ULTI/INPUT_TOKEN TWAP during the pump
    event Pumped(
        uint32 indexed cycle,
        address indexed user,
        uint256 inputTokenToSwap,
        uint256 ultiBurned,
        uint16 pumpCount,
        uint256 twap
    );

    /// @notice Emitted when a top contributor is added, updated, or replaced in a cycle
    /// @dev This event tracks changes to the top contributors list, including:
    ///      - When a new contributor is added (up to MAX_TOP_CONTRIBUTORS)
    ///      - When an existing contributor's contribution is updated
    ///      - When a contributor replaces another in the top contributors list
    /// @param cycle The cycle number in which the top contributor change occurred
    /// @param contributorAddress The address of the contributor being added or updated
    /// @param removedContributorAddress The address of the contributor that was removed (address(0) if no removal)
    /// @param contribution The new total discounted contribution amount for this contributor
    event TopContributorsUpdated(
        uint32 indexed cycle,
        address indexed contributorAddress,
        address indexed removedContributorAddress,
        uint256 contribution
    );

    /// @notice Emitted when top contributor bonuses are distributed for a cycle
    /// @param cycle The cycle number for which bonuses are distributed
    /// @param ultiAmount The total amount of ULTI tokens distributed as bonuses
    event TopContributorBonusesDistributed(uint32 indexed cycle, uint256 ultiAmount);

    /// @notice Emitted when liquidity fees are collected and processed
    /// @param cycle The current cycle number
    /// @param inputTokenEarned The amount of input token earned from fees
    /// @param ultiBurned The amount of ULTI tokens burned from fees
    event LiquidityFeesProcessed(uint32 indexed cycle, uint256 inputTokenEarned, uint256 ultiBurned);

    /// @notice Emitted when a user claims all their accumulated bonuses
    /// @param cycle The current cycle number
    /// @param user The address of the user claiming the bonuses
    /// @param ultiAmount The total amount of ULTI tokens claimed as bonuses
    event AllBonusesClaimed(uint32 indexed cycle, address indexed user, uint256 ultiAmount);

    // ===============================================
    // Modifiers
    // ===============================================

    /**
     * @dev Modifier to ensure that the function can only be called after the liquidity position is initialized.
     * This modifier is used to prevent certain functions from being called before the ULTI token is fully launched.
     */
    modifier unstoppable() {
        if (liquidityPositionTokenId == 0) revert LiquidityPositionNotInitialized();
        _;
    }

    // ===============================================
    // Core Contract Setup
    // ===============================================

    /**
     * @notice Initializes the ULTI token contract with Uniswap V3 integration and token configuration
     * @dev Sets up the ULTI token contract by:
     *      1. Initializing Uniswap V3 interfaces (router, factory, position manager)
     *      2. Setting input token address
     *      3. Setting wrapped native token address for native deposits
     *      4. Determining token ordering for Uniswap pool
     *      5. Setting initial ratio
     *      6. Setting minimum deposit amount
     *      7. Setting minimum TWAP observations
     *      8. Setting unlimited approvals for Uniswap interactions
     * @param _name The name of the token
     * @param _symbol The symbol/tag of the token
     * @param uniswapRouterAddress The address of the Uniswap V3 Router
     * @param uniswapFactoryAddress The address of the Uniswap V3 Factory
     * @param nonfungiblePositionManagerAddress The address of the Uniswap V3 NonfungiblePositionManager
     * @param _inputTokenAddress The address of the input token (e.g. WETH, DAI, etc.)
     * @param _wrappedNativeTokenAddress The address of the wrapped native token (e.g. WETH, WBNB, etc.) to optionally enable depositNative()
     * @param _initialRatio The initial ratio of ULTI to input token
     * @param _minimumDepositAmount The minimum amount required for a deposit to be valid
     */
    constructor(
        string memory _name,
        string memory _symbol,
        address uniswapRouterAddress,
        address uniswapFactoryAddress,
        address nonfungiblePositionManagerAddress,
        address _inputTokenAddress,
        address _wrappedNativeTokenAddress,
        uint256 _initialRatio,
        uint256 _minimumDepositAmount,
        uint16 _minimumTwapObservations
    ) ERC20(_name, _symbol) Ownable(msg.sender) {
        // 1. Initialize Uniswap V3 interfaces
        uniswapRouter = ISwapRouter(uniswapRouterAddress);
        uniswapFactory = IUniswapV3Factory(uniswapFactoryAddress);
        nonfungiblePositionManager = INonfungiblePositionManager(nonfungiblePositionManagerAddress);

        // 2. Set input token address
        inputTokenAddress = _inputTokenAddress;

        // 3. Set wrapped native token address
        wrappedNativeTokenAddress = _wrappedNativeTokenAddress;

        // 4. Determine token ordering
        isUltiToken0 = address(this) < inputTokenAddress;

        // 5. Set initial ratio
        initialRatio = _initialRatio;

        // 6. Set minimum deposit amount
        minimumDepositAmount = _minimumDepositAmount;

        // 7. Set minimum TWAP observations
        minimumTwapObservations = _minimumTwapObservations;

        // 8. Set unlimited approvals
        _approve(address(this), address(nonfungiblePositionManager), type(uint256).max);
        _approve(address(this), address(uniswapRouter), type(uint256).max);
        IERC20(inputTokenAddress).forceApprove(address(nonfungiblePositionManager), type(uint256).max);
        IERC20(inputTokenAddress).forceApprove(address(uniswapRouter), type(uint256).max);

        // SECURITY NOTE: Unlimited approvals are granted to trusted Uniswap V3 contracts.
        // These contracts are well-audited and battle-tested but represent a theoretical risk if compromised.
    }

    /**
     * @notice Accepts native token deposits and wraps them into WETH, WBNB, etc.
     * @dev Automatically wraps received native tokens into their wrapped version
     *      This allows the contract to accept direct native token transfers
     *      which get added to the long-term reserve
     *      Handles direct native token transfers with empty msg.data
     */
    receive() external payable {
        if (inputTokenAddress != wrappedNativeTokenAddress) revert DepositNativeNotSupported();
        IWrappedNative(wrappedNativeTokenAddress).deposit{value: msg.value}();
    }

    /**
     * @notice Fallback function that accepts native token deposits and wraps them
     * @dev Automatically wraps received native tokens into their wrapped version
     *      This allows the contract to accept direct native token transfers
     *      which get added to the long-term reserve
     *      Catches and handles:
     *      - Native token transfers with non-empty msg.data
     *      - Calls to undefined functions
     *      - Incorrectly encoded function calls
     */
    fallback() external payable {
        if (inputTokenAddress != wrappedNativeTokenAddress) revert DepositNativeNotSupported();
        IWrappedNative(wrappedNativeTokenAddress).deposit{value: msg.value}();
    }

    /**
     * @notice Starts the ULTI token by creating the initial trading pool. Can only be called once by the owner with at least 33 units of input token.
     * @dev Launches the ULTI token by:
     *      1. Verifying the liquidity position doesn't exist
     *      2. Transferring input tokens from owner to contract
     *      3. Setting initial launch and pump timestamps
     *      4. Creating initial liquidity position with input tokens
     *      5. Renouncing contract ownership
     *      6. Emitting launch event
     * @param founderGiveaway Amount of input tokens to initialize liquidity position with
     */
    function launch(uint256 founderGiveaway) external onlyOwner {
        // 1. Verify the liquidity position doesn't exist and validating minimum input token amount
        if (liquidityPositionTokenId != 0) revert LiquidityPositionAlreadyExists();

        // 2. Transfer input tokens from owner
        IERC20(inputTokenAddress).safeTransferFrom(msg.sender, address(this), founderGiveaway);

        // 3. Set initial timestamps
        launchTimestamp = uint64(block.timestamp);
        nextPumpTimestamp = uint64(block.timestamp + ULTIShared.PUMP_INTERVAL);

        // 4. Create initial liquidity position
        _createLiquidity(founderGiveaway, block.timestamp);

        // 5. Renounce ownership
        renounceOwnership();

        // 6. Emit launch event
        emit Launched(founderGiveaway, address(liquidityPool));
    }

    // ===============================================
    // Price & Liquidity
    // ===============================================

    /**
     * @notice Gets the current price of ULTI tokens in input token
     * @dev External wrapper function to retrieve the current spot price from the Uniswap V3 pool. The result is scaled by 1e18, so 1e18 represents 1 input token per ULTI
     * @return spotPrice The current spot price in ULTI/INPUT_TOKEN format (how much input token is needed to buy 1 ULTI)
     */
    function getSpotPrice() external view returns (uint256) {
        return _getSpotPrice();
    }

    /**
     * @notice Gets the current exchange rate between ULTI tokens and input token from the liquidity pool
     * @dev Uses UniswapV3's OracleLibrary approach for price calculation. Safely calculates spot price using multi-step computation to prevent overflow.
     *      Uses OpenZeppelin's Math.mulDiv for safe multiplication and division with overflow protection:
     *      1. For token0 (ULTI): price = (sqrtPrice^2 * 1e18) / 2^192
     *      2. For token1 (ULTI): price = (2^192 * 1e18) / sqrtPrice^2
     * @return spotPrice The current price ratio between ULTI and input token (input token needed to buy 1 ULTI)
     */
    function _getSpotPrice() internal view returns (uint256 spotPrice) {
        // 1. Get square root price from pool slot0
        (uint160 sqrtPriceX96,,,,,,) = liquidityPool.slot0();
        uint256 sqrtPrice = uint256(sqrtPriceX96);

        if (isUltiToken0) {
            // 2. When ULTI is token0:
            // First step: Calculate (sqrtPrice * sqrtPrice) / 2^96
            // This reduces the intermediate value by 2^96 early to prevent overflow
            uint256 priceX96 = Math.mulDiv(sqrtPrice, sqrtPrice, 1 << 96);

            // Second step: Calculate (priceX96 * 1e18) / 2^96
            // This completes the calculation while maintaining precision
            spotPrice = Math.mulDiv(priceX96, 1e18, 1 << 96);
        } else {
            // When ULTI is token1:
            // First step: Calculate (2^96 * 1e18) / sqrtPrice
            // This keeps intermediate values manageable
            uint256 invPriceX96 = Math.mulDiv(1 << 96, 1e18, sqrtPrice);

            // Second step: Calculate (invPriceX96 * 2^96) / sqrtPrice
            // This completes the inverse price calculation
            spotPrice = Math.mulDiv(invPriceX96, 1 << 96, sqrtPrice);
        }
    }

    /**
     * @notice Gets the average price of ULTI tokens over a recent time period
     * @dev External wrapper that returns the current Time-Weighted Average Price (TWAP).
     * Always calculates fresh TWAP value to avoid returning stale data.
     * @return currentTwap The current time-weighted average price
     */
    function getTWAP() external view returns (uint256 currentTwap) {
        return _calculateTWAP();
    }

    /**
     * @notice Calculates the time-weighted average price (TWAP) of ULTI tokens in input token
     * @dev Main execution steps:
     *      1. Returns initial ratio if minimum TWAP time hasn't elapsed since launch
     *      2. Sets up observation window parameters for Uniswap oracle:
     *         - Uses MIN_TWAP_INTERVAL for window size
     *         - Gets observations at start and end of window
     *      3. Attempts to calculate TWAP from Uniswap observations:
     *         - Gets cumulative ticks from pool
     *         - Calculates average tick over window
     *         - Converts tick to price quote with ULTI as base token
     *      4. Revert if TWAP calculation fails
     * @return twap The time-weighted average price in input token per ULTI (scaled by 1e18)
     */
    function _calculateTWAP() internal view returns (uint256 twap) {
        // 1. Return initial ratio if minimum TWAP time hasn't elapsed
        if (block.timestamp < launchTimestamp + ULTIShared.MIN_TWAP_INTERVAL) {
            return 1e18 / initialRatio;
        }

        // 2. Set up observation window parameters
        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = ULTIShared.MIN_TWAP_INTERVAL; // observation window
        secondsAgos[1] = 0;

        // 3. Get cumulative ticks and compute average
        try liquidityPool.observe(secondsAgos) returns (int56[] memory tickCumulatives, uint160[] memory) {
            // 3a. Calculate time-weighted average tick
            int56 tickCumulativeDelta = tickCumulatives[1] - tickCumulatives[0];
            int24 timeWeightedAverageTick = int24(tickCumulativeDelta / int32(secondsAgos[0]));

            // Adjust for negative tickCumulativeDelta to handle truncation correctly
            if (tickCumulativeDelta < 0 && (tickCumulativeDelta % int56(uint56(secondsAgos[0])) != 0)) {
                timeWeightedAverageTick--;
            }

            // 3b. Convert tick to price quote
            // Always pass ULTI as base token (amount of 1e18 = 1 ULTI) and input token as quote token
            // This ensures we get the price in INPUT_TOKEN/ULTI format consistently
            twap = OracleLibrary.getQuoteAtTick(
                timeWeightedAverageTick,
                1e18, // amountIn: 1 ULTI token (18 decimals)
                address(this), // base token (ULTI)
                inputTokenAddress // quote token (INPUT_TOKEN)
            );
        } catch {
            // 4. Revert if TWAP calculation fails
            revert TWAPCalculationFailed();
        }

        return twap;
    }

    /**
     * @notice Creates the initial trading pool for ULTI and input token on Uniswap
     * @dev Main execution steps:
     *      1. Verifies no pool exists yet by checking Uniswap factory
     *      2. Creates new Uniswap V3 pool and stores instance if none exists. Uses existing pool otherwise
     *      3. Calculates initial square root price based on `initialRatio`
     *      4. Initializes pool with calculated price
     *      5. Increases observation cardinality to prevent TWAP manipulation
     *      6. Mints ULTI tokens to match input token amount at initial ratio
     *      7. Creates full range liquidity position with both tokens
     *      8. Stores position token ID for future operations
     *      9. Keeps any leftover tokens in contract for future use
     * @param inputTokenForLP Amount of input token to add to the liquidity position
     * @param deadline The timestamp after which the transaction will revert
     */
    function _createLiquidity(uint256 inputTokenForLP, uint256 deadline) private {
        // 1. Check if the Uniswap pool already exists
        address liquidityPoolAddress = uniswapFactory.getPool(address(this), inputTokenAddress, ULTIShared.LP_FEE);

        // 2. Create and store pool if it doesn't exist
        if (liquidityPoolAddress == address(0)) {
            liquidityPoolAddress = uniswapFactory.createPool(address(this), inputTokenAddress, ULTIShared.LP_FEE);
            liquidityPool = IUniswapV3Pool(liquidityPoolAddress);
        } else {
            // SECURITY NOTE: DoS risk if a pool with the same parameters is created before `launch` is executed.
            // This risk is accepted due to its low impact (cost of deploying ULTI) and very low likelihood of happening.
            revert LiquidityPoolAlreadyExists();
        }

        // 3. Calculate the square root price to initialize the pool
        uint160 initialSqrtPriceX96;
        if (isUltiToken0) {
            uint256 sqrtPrice = Math.sqrt((1 << 192) / initialRatio);
            initialSqrtPriceX96 = uint160(sqrtPrice);
        } else {
            uint256 sqrtPrice = Math.sqrt(uint256(initialRatio) << 192);
            initialSqrtPriceX96 = uint160(sqrtPrice);
        }

        // 4. Initialize the Uniswap pool with the calculated price
        IUniswapV3Pool(liquidityPoolAddress).initialize(initialSqrtPriceX96);

        // 5. Increase observation cardinality to prevent TWAP manipulation
        IUniswapV3Pool(liquidityPoolAddress).increaseObservationCardinalityNext(minimumTwapObservations);

        // 6. Calculate and mint ULTI tokens for liquidity
        uint256 ultiForLP = inputTokenForLP * initialRatio;
        _mint(address(this), ultiForLP);

        // 7. Create full range liquidity position
        INonfungiblePositionManager.MintParams memory mintParams = INonfungiblePositionManager.MintParams({
            token0: isUltiToken0 ? address(this) : inputTokenAddress,
            token1: isUltiToken0 ? inputTokenAddress : address(this),
            fee: ULTIShared.LP_FEE,
            tickLower: ULTIShared.LP_MIN_TICK,
            tickUpper: ULTIShared.LP_MAX_TICK,
            amount0Desired: isUltiToken0 ? ultiForLP : inputTokenForLP,
            amount1Desired: isUltiToken0 ? inputTokenForLP : ultiForLP,
            amount0Min: 0,
            amount1Min: 0,
            recipient: address(this),
            deadline: deadline
        });

        // 8. Store position token ID
        (uint256 tokenId,,,) = nonfungiblePositionManager.mint(mintParams);
        liquidityPositionTokenId = tokenId;

        // 9. Keeps any leftover tokens in contract for future use:
        // If there are any leftover input token, keep in the contract: it will be used for future pumps
        // If there are any leftover ULTI, keep in the contract and do nothing
    }

    /**
     * @notice Tries to add more liquidity to the trading pool to make trading easier and more stable for everyone
     * @dev Main execution steps:
     *      1. Validates input amounts are non-zero
     *      2. Mints new ULTI tokens to this contract for liquidity
     *      3. Calculates minimum amounts with 0.33% slippage tolerance
     *      4. Constructs parameters for increasing liquidity
     *      5. Calls position manager and tries to increase liquidity.
     *      6. Keeps any leftover tokens in contract for future use
     * @param inputTokenForLP Amount of input token to add to the liquidity position
     * @param ultiForLP Amount of ULTI to add to the liquidity position
     * @param deadline The timestamp after which the transaction will revert
     */
    function _tryIncreaseLiquidity(uint256 inputTokenForLP, uint256 ultiForLP, uint256 deadline) private {
        // 1. Validate input amounts are non-zero
        if (inputTokenForLP == 0) revert DepositLiquidityInsufficientEthAmount();
        if (ultiForLP == 0) revert DepositLiquidityInsufficientUltiAmount();

        // 2. Mint ULTI tokens to this contract for liquidity provision
        _mint(address(this), ultiForLP);

        // 3. Calculate minimum amounts for ULTI and input token, accounting for slippage
        // Ensures liquidity provision won't lose more than MAX_ADD_LP_SLIPPAGE_BPS due to slippage
        uint256 minUltiAmount = (ultiForLP * (10000 - ULTIShared.MAX_ADD_LP_SLIPPAGE_BPS)) / 10000;
        uint256 minInputTokenAmount = (inputTokenForLP * (10000 - ULTIShared.MAX_ADD_LP_SLIPPAGE_BPS)) / 10000;

        // 4. Construct parameters for increasing liquidity
        INonfungiblePositionManager.IncreaseLiquidityParams memory increaseParams = INonfungiblePositionManager
            .IncreaseLiquidityParams({
            tokenId: liquidityPositionTokenId,
            amount0Desired: isUltiToken0 ? ultiForLP : inputTokenForLP,
            amount1Desired: isUltiToken0 ? inputTokenForLP : ultiForLP,
            amount0Min: isUltiToken0 ? minUltiAmount : minInputTokenAmount,
            amount1Min: isUltiToken0 ? minInputTokenAmount : minUltiAmount,
            deadline: deadline
        });

        // 5. Call position manager to increase liquidity
        // Note: In most cases liquidity is expected to be added but in very volatile markets, this step will be skipped.
        // This occurs when deposits are made following significant price changes, where the difference
        // between the TWAP and current spot price exceeds the pool's slippage limits
        try nonfungiblePositionManager.increaseLiquidity(increaseParams) {}
        catch {
            // Skip, failing to add liquidity should never block deposits
            // The input token dedicated to liquidity will instead be used to pump
        }

        // 6. Keeps any leftover tokens in contract for future use:
        // If there are any leftover input token, keep in the contract: it will be used for future pumps
        // If there are any leftover ULTI, keep in the contract and do nothing
    }

    /**
     * @notice Collects and processes fees earned from providing liquidity, burning ULTI fees and keeping input token fees in the contract
     * @dev Main execution steps:
     *      1. Prepares collection parameters to collect all accumulated fees
     *      2. Calls position manager to collect fees into this contract
     *      3. Based on token ordering:
     *         - Burns collected ULTI fees by calling _burn()
     *         - Keeps collected input token fees in contract
     *      4. Emits event with amounts processed
     * @dev Requires liquidityPositionTokenId to be set and contract to have sufficient balance
     */
    function _collectAndProcessLiquidityFees() private {
        // 1. Prepare collection parameters
        INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({
            tokenId: liquidityPositionTokenId,
            recipient: address(this),
            amount0Max: type(uint128).max, // Collect all ULTI fees
            amount1Max: type(uint128).max // Collect all input token fees
        });

        // 2. Collect the fees
        (uint256 amount0, uint256 amount1) = nonfungiblePositionManager.collect(params);

        uint256 inputTokenEarned;
        uint256 ultiBurned;

        // 3. Burn ULTI fees, keep the input token in the contract
        if (isUltiToken0) {
            if (amount0 > 0) {
                _burn(address(this), amount0);
                ultiBurned = amount0;
            }
            if (amount1 > 0) {
                inputTokenEarned = amount1;
            }
        } else {
            if (amount1 > 0) {
                _burn(address(this), amount1);
                ultiBurned = amount1;
            }
            if (amount0 > 0) {
                inputTokenEarned = amount0;
            }
        }

        // 4. Emits event with amounts processed
        emit LiquidityFeesProcessed(getCurrentCycle(), inputTokenEarned, ultiBurned);
    }

    /**
     * @notice Gets how much input token and ULTI tokens are currently in the liquidity position and total in the pool
     * @dev Calculates token amounts in the Uniswap V3 pool through these steps:
     *      1. Get liquidity of the contract's position
     *      2. Retrieve pool's current price and tick boundaries
     *      3. Compute token amounts based on current price and boundaries
     *      4. Map token0/token1 to ULTI/INPUT_TOKEN based on pool token ordering flag
     *      5. Get total token balances in the pool
     * @return inputTokenAmountInPosition The amount of input token in the current liquidity position
     * @return ultiAmountInPosition The amount of ULTI in the current liquidity position
     * @return inputTokenAmountInPool The total amount of input token in the liquidity pool
     * @return ultiAmountInPool The total amount of ULTI in the liquidity pool
     */
    function getLiquidityAmounts()
        external
        view
        returns (
            uint256 inputTokenAmountInPosition,
            uint256 ultiAmountInPosition,
            uint256 inputTokenAmountInPool,
            uint256 ultiAmountInPool
        )
    {
        // 1. Get liquidity of the contract's position
        (,,,,,,, uint128 liquidity,,,,) = nonfungiblePositionManager.positions(liquidityPositionTokenId);

        // 2. Retrieve pool's current price and tick boundaries
        (uint160 sqrtPriceX96,,,,,,) = liquidityPool.slot0();
        uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(ULTIShared.LP_MIN_TICK);
        uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(ULTIShared.LP_MAX_TICK);

        // 3. Compute token amounts based on current price and boundaries
        (uint256 amount0, uint256 amount1) =
            LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity);

        // 4. Map token0/token1 to ULTI/INPUT_TOKEN based on ordering
        if (isUltiToken0) {
            ultiAmountInPosition = amount0;
            inputTokenAmountInPosition = amount1;
        } else {
            inputTokenAmountInPosition = amount0;
            ultiAmountInPosition = amount1;
        }

        // 5. Get total token balances in the pool
        inputTokenAmountInPool = IERC20(inputTokenAddress).balanceOf(address(liquidityPool));
        ultiAmountInPool = IERC20(address(this)).balanceOf(address(liquidityPool));
    }

    // ===============================================
    // Deposit & Claims
    // ===============================================

    /**
     * @notice Allows users to deposit native currency (ETH, BNB, etc.) to receive ULTI tokens after a waiting period
     * @dev Main execution steps:
     *      1. Validates input token address matches wrapped native token
     *      2. Validates non-zero native currency amount sent
     *      3. Calls internal _deposit() with native flag set to true
     * @param referrer The address that referred this deposit
     * @param minUltiToAllocate Minimum ULTI tokens to receive to prevent slippage
     * @param deadline Timestamp when transaction expires
     * @param autoClaim Whether to claim pending ULTI before depositing
     */
    function depositNative(address referrer, uint256 minUltiToAllocate, uint256 deadline, bool autoClaim)
        external
        payable
        nonReentrant
        unstoppable
    {
        if (inputTokenAddress != wrappedNativeTokenAddress) revert DepositNativeNotSupported();

        // Passing `true` flag for native deposit
        _deposit(msg.value, referrer, minUltiToAllocate, deadline, autoClaim, true);
    }

    /**
     * @notice Allows users to deposit a ERC20 input tokens to receive ULTI tokens after a waiting period
     * @param inputTokenAmount Amount of input token to deposit
     * @param referrer The address that referred this deposit
     * @param minUltiToAllocate Minimum ULTI tokens to receive to prevent slippage
     * @param deadline Timestamp when transaction expires
     * @param autoClaim Whether to claim pending ULTI before depositing
     */
    function deposit(
        uint256 inputTokenAmount,
        address referrer,
        uint256 minUltiToAllocate,
        uint256 deadline,
        bool autoClaim
    ) external nonReentrant unstoppable {
        // Passing `false` flag for ERC20 token deposit
        _deposit(inputTokenAmount, referrer, minUltiToAllocate, deadline, autoClaim, false);
    }

    /**
     * @notice Processes a user's deposit of input tokens or native currency to receive ULTI tokens
     * @dev Processes deposits:
     *      1. Validates deposit requirements:
     *         - Checks input amount is non-zero
     *         - Validates referrer address
     *         - Verifies cooldown period has passed
     *      2. Auto-claims pending ULTI if:
     *         - Auto-claim flag is true
     *         - Cooldown period has passed
     *         - User has pending ULTI
     *      3. Transfers tokens from user to contract:
     *         - For native: wraps received native currency into its corresponding wrapped token
     *         - For tokens: transfers input tokens from user
     *      4. Processes allocation:
     *         - Calculates ULTI amounts for user and liquidity position
     *         - Adds liquidity to Uniswap pool
     *      5. Calculates and adds streak bonus based on allocated ULTI
     *      6. Updates user's total lifetime ULTI allocation
     *      7. Processes referral bonuses for referrer and referred user
     *      8. Updates contributor rankings with new allocation
     *      9. Resets deposit/claim cooldown cooldown
     *      10. Initializes bonus claim timer if first deposit
     *      11. Emits detailed deposit event
     * @param inputTokenAmount Amount of input token to deposit
     * @param referrer The address that referred this deposit
     * @param minUltiToAllocate Minimum ULTI tokens to receive to prevent slippage
     * @param deadline Timestamp when transaction expires
     * @param autoClaim Whether to claim pending ULTI before depositing
     * @param isNative Whether the deposit is made with native currency
     */
    function _deposit(
        uint256 inputTokenAmount,
        address referrer,
        uint256 minUltiToAllocate,
        uint256 deadline,
        bool autoClaim,
        bool isNative
    ) private {
        // 1. Validate deposit requirements
        if (inputTokenAmount < minimumDepositAmount) revert DepositInsufficientAmount();
        if (referrer == msg.sender) revert DepositCannotReferSelf();
        if (referrers[referrer] == msg.sender) revert DepositCircularReferral();
        if (block.timestamp > deadline) revert DepositExpired();
        if (block.timestamp < nextDepositOrClaimTimestamp[msg.sender]) revert DepositCooldownActive();

        // 2. Auto-claim pending ULTI if requested
        bool autoClaimed;
        if (autoClaim && claimableUlti[msg.sender] > 0) {
            _claimUlti();
            autoClaimed = true;
        }

        // 3. Transfer input tokens from user to contract
        if (isNative) {
            // Convert native to wrapped native (e.g. ETH to WETH)
            IWrappedNative(wrappedNativeTokenAddress).deposit{value: msg.value}();
        } else {
            IERC20(inputTokenAddress).safeTransferFrom(msg.sender, address(this), inputTokenAmount);
        }

        // 4. Process deposit allocation
        (uint256 ultiForUser, uint256 ultiForLP, uint256 inputTokenForLP) =
            _allocateDeposit(inputTokenAmount, minUltiToAllocate, deadline);

        uint32 cycle = getCurrentCycle();

        // 5. Calculate the streak bonus and allocate it based on the ULTI just allocated to the user
        (uint256 streakBonus, uint32 streakCount) = _updateStreakBonus(msg.sender, inputTokenAmount, ultiForUser, cycle);

        // 6. Update total ULTI ever allocated for user to increase their Skin-in-the-Game cap (includes streak bonus, excludes other bonuses)
        uint256 ultiForUserWithStreakBonus = ultiForUser + streakBonus;
        totalUltiAllocatedEver[msg.sender] += ultiForUserWithStreakBonus;

        // 7. Calculate referral bonus and allocate it based on the ULTI just allocated to the user including the streak bonus
        (address effectiveReferrer, uint256 referrerBonus, uint256 referredBonus) =
            _updateReferrals(referrer, inputTokenAmount, ultiForUserWithStreakBonus, cycle);

        // 8. Update contributors and top contributors rankings based on total ULTI just allocated including the streak bonus
        uint256 cycleContribution =
            _updateContributors(cycle, msg.sender, inputTokenAmount, 0, ultiForUserWithStreakBonus);

        // 9. Reset deposit/claim cooldown cooldown
        nextDepositOrClaimTimestamp[msg.sender] = block.timestamp + ULTIShared.DEPOSIT_CLAIM_INTERVAL;

        // 10. Initialize next bonus claim timestamp if not already set
        if (nextAllBonusesClaimTimestamp[msg.sender] == 0) {
            nextAllBonusesClaimTimestamp[msg.sender] = block.timestamp + ULTIShared.ALL_BONUSES_CLAIM_INTERVAL;
        }

        // 11. Emit deposit event
        emit Deposited(
            cycle,
            msg.sender,
            effectiveReferrer,
            inputTokenAmount,
            inputTokenForLP,
            ultiForLP,
            ultiForUser,
            streakBonus,
            streakCount,
            referrerBonus,
            referredBonus,
            autoClaimed,
            cycleContribution
        );
    }

    /**
     * @notice Processes a user's deposit of input tokens and allocates ULTI tokens in return
     * @dev Processes deposit allocation:
     *      1. Get TWAP
     *      2. Calculates ULTI tokens to give user based on early bird or TWAP price
     *      3. Verifies user gets at least their minimum requested ULTI amount
     *      4. Calculates input token and ULTI portions for liquidity position using the deposit price
     *      5. Try adding calculated amounts to the liquidity position
     *      6. Updates user's ULTI allocation
     * @param inputTokenAmount Amount of input tokens being deposited
     * @param minUltiToAllocate Minimum ULTI tokens to receive to prevent slippage
     * @param deadline Timestamp when transaction expires
     * @return ultiForUser Amount of ULTI tokens allocated to user without bonus
     * @return ultiForLP Amount of ULTI tokens allocated to liquidity position
     * @return inputTokenForLP Amount of input tokens allocated to liquidity position
     */
    function _allocateDeposit(uint256 inputTokenAmount, uint256 minUltiToAllocate, uint256 deadline)
        private
        returns (uint256 ultiForUser, uint256 ultiForLP, uint256 inputTokenForLP)
    {
        // 1. Get TWAP
        uint256 twap = _calculateTWAP();

        // 2. Calculates ULTI tokens to give user based on early bird or TWAP price
        if (block.timestamp < launchTimestamp + ULTIShared.EARLY_BIRD_PRICE_DURATION) {
            ultiForUser = inputTokenAmount * initialRatio;
        } else {
            ultiForUser = 1e18 * inputTokenAmount / twap;
        }

        // 3. Verify user gets at least their minimum requested ULTI amount
        if (ultiForUser < minUltiToAllocate) revert DepositInsufficientUltiAllocation();

        // 4. Calculate INPUT and ULTI portions for liquidity position using the current spot price to prevent slippage issues
        inputTokenForLP = (inputTokenAmount * ULTIShared.LP_CONTRIBUTION_PERCENTAGE) / 100;
        ultiForLP = 1e18 * inputTokenForLP / twap;

        // 5. Try adding calculated amounts to the liquidity position
        _tryIncreaseLiquidity(inputTokenForLP, ultiForLP, deadline);

        // 6. Updates user's ULTI allocation
        claimableUlti[msg.sender] += ultiForUser;

        return (ultiForUser, ultiForLP, inputTokenForLP);
    }

    /**
     * @notice Claim pending ULTI tokens
     * @dev Calls internal _claimUlti function to process the claim
     */
    function claimUlti() external nonReentrant unstoppable {
        _claimUlti();
    }

    /**
     * @notice Allows users to claim their pending ULTI tokens
     * @dev Processes ULTI token claims:
     *      1. Validates the 24h cooldown period has passed
     *      2. Validates user has ULTI tokens available to claim
     *      3. Records the claimable amount and resets user's allocation
     *      4. Mints the ULTI tokens to the user
     *      5. Emits claim event with details
     */
    function _claimUlti() private {
        // 1. Validate cooldown period
        if (block.timestamp < nextDepositOrClaimTimestamp[msg.sender]) revert ClaimUltiCooldownActive();

        // 2. Validate claimable amount
        if (claimableUlti[msg.sender] == 0) revert ClaimUltiEmpty();

        // 3. Record amount and reset allocation
        uint256 ultiToClaim = claimableUlti[msg.sender];
        claimableUlti[msg.sender] = 0;

        // 4. Mint tokens to user
        _mint(msg.sender, ultiToClaim);

        // 5. Emit claim event
        emit Claimed(getCurrentCycle(), msg.sender, ultiToClaim);
    }

    /**
     * @notice Claims all earned bonuses in one go after the cooldown period
     * @dev Processes bonus claims through these steps:
     *      1. Validate cooldown period has passed
     *      2. Get and validate user's allocated bonuses
     *      3. Reset allocated bonuses to 0
     *      4. Reset accumulated referral bonuses to 0 (reset skin in the game buffer)
     *      5. Mint bonus tokens to user
     *      6. Set next claim timestamp
     *      7. Emit claim event
     */
    function claimAllBonuses() external nonReentrant unstoppable {
        // 1. Validate cooldown period has passed
        if (block.timestamp < nextAllBonusesClaimTimestamp[msg.sender]) revert ClaimAllBonusesCooldownActive();

        // 2. Get and validate user's allocated bonuses
        uint256 bonuses = claimableBonuses[msg.sender];
        if (bonuses == 0) revert ClaimAllBonusesEmpty();

        // 3. Reset allocated bonuses to 0
        claimableBonuses[msg.sender] = 0;

        // 4. Reset accumulated referral bonuses to 0 (reset skin in the game buffer)
        accumulatedReferralBonuses[msg.sender] = 0;

        // 5. Mint bonus tokens to user
        _mint(msg.sender, bonuses);

        // 6. Set next claim timestamp
        nextAllBonusesClaimTimestamp[msg.sender] = block.timestamp + ULTIShared.ALL_BONUSES_CLAIM_INTERVAL;

        // 7. Emit claim event
        emit AllBonusesClaimed(getCurrentCycle(), msg.sender, bonuses);
    }

    // ===============================================
    // Pump Mechanism
    // ===============================================

    /**
     * @notice Checks if an address is an active pumper for a given cycle
     * @dev Active pumpers must have at least MIN_PUMPS_FOR_ACTIVE_PUMPERS pumps, 11 in a cycle
     * @param cycle The cycle to check
     * @param pumper The address to check
     * @return bool True if address is an active pumper
     */
    function _isActivePumper(uint32 cycle, address pumper) internal view returns (bool) {
        return pumpCounts[cycle][pumper] >= ULTIShared.MIN_PUMPS_FOR_ACTIVE_PUMPERS;
    }

    /**
     * @notice Allows top contributors to increase ULTI token value
     * @dev Main execution steps:
     *      1. Validates transaction requirements:
     *         - Checks deadline not passed
     *         - Checks pump cooldown period elapsed
     *         - Verifies caller is top contributor
     *         - Verifies pump count is less than max allowed
     *      2. Performs cycle maintenance if needed
     *      3. Updates time-weighted average price (TWAP)
     *      4. Calculates input token amount for pump:
     *         - Takes 0.00419061% of contract balance per pump
     *         - Equivalent to ~3.55% per cycle and ~33% per year
     *      5. Calculate minimum ULTI output based on user's max price
     *      6. Swaps input tokens for ULTI via Uniswap
     *      7. Burns received ULTI tokens
     *      8. Increments pump count for current cycle
     *      9. Sets next pump timestamp
     * @param maxInputTokenPerUlti The maximum amount of input token per ULTI to use for a pump
     * @param deadline The timestamp after which the transaction will revert
     * @return inputTokenToSwap The amount of input token used for the pump
     * @return ultiToBurn The amount of ULTI tokens burned in the process
     */
    function pump(uint256 maxInputTokenPerUlti, uint256 deadline)
        external
        nonReentrant
        unstoppable
        returns (uint256 inputTokenToSwap, uint256 ultiToBurn)
    {
        // 1. Validate transaction requirements
        if (block.timestamp > deadline) revert PumpExpired();
        if (block.timestamp < nextPumpTimestamp) revert PumpCooldownActive();
        uint32 cycle = getCurrentCycle();
        if (!topContributors[cycle].contains(msg.sender)) revert PumpOnlyForTopContributors();
        if (pumpCounts[cycle][msg.sender] >= ULTIShared.MAX_PUMPS_FOR_ACTIVE_PUMPERS) revert PumpMaxPumpsReached();

        // 2. Perform cycle maintenance if needed
        if (cycle > 1 && !isTopContributorsBonusAllocated[cycle - 1]) {
            _allocateTopContributorsBonuses(cycle - 1);
            _collectAndProcessLiquidityFees();
        }

        // 3. Update time-weighted average price
        uint256 twap = _calculateTWAP();

        // 4. Calculate input token amount to use for pump:
        // 0.00419061% per pump, equivalent to ~3.55% per cycle and ~33% per year
        uint256 inputTokenBalance = IERC20(inputTokenAddress).balanceOf(address(this));
        inputTokenToSwap = inputTokenBalance * ULTIShared.PUMP_FACTOR_NUMERATOR / ULTIShared.PUMP_FACTOR_DENOMINATOR;

        // 5. Calculate minimum ULTI output based on user's max price
        uint256 minUltiAmount = inputTokenToSwap * 1e18 / maxInputTokenPerUlti;

        // 6. Swap input token for ULTI tokens
        ultiToBurn = _swapInputTokenForUlti(inputTokenToSwap, minUltiAmount, twap, deadline);

        // 7. Burn received ULTI tokens
        _burn(msg.sender, ultiToBurn);

        // 8. Increment pump count for current cycle
        _updatePumpCount(cycle, msg.sender);

        // 9. Set next allowed pump timestamp
        nextPumpTimestamp = uint64(block.timestamp + ULTIShared.PUMP_INTERVAL);

        emit Pumped(cycle, msg.sender, inputTokenToSwap, ultiToBurn, pumpCounts[cycle][msg.sender], twap);
    }

    /**
     * @notice Swaps input tokens for ULTI tokens using Uniswap with slippage protection
     * @dev Main execution steps:
     *      1. Validates input parameters are non-zero
     *      2. Calculates expected ULTI output based on provided TWAP
     *      3. Determines effective minimum ULTI amount using max of:
     *         - User specified minimum amount
     *         - Internal slippage protection (MAX_SWAP_SLIPPAGE_BPS)
     *      4. Executes swap via Uniswap exactInputSingle
     *      5. Validates received ULTI amount meets minimum requirements
     * @param inputAmountToSwap Amount of input token to swap
     * @param minUltiAmount Minimum amount of ULTI tokens to receive
     * @param twap Current time-weighted average price used for calculations
     * @param deadline The timestamp after which the transaction will revert
     * @return ultiAmount The amount of ULTI tokens received from the swap
     */
    function _swapInputTokenForUlti(uint256 inputAmountToSwap, uint256 minUltiAmount, uint256 twap, uint256 deadline)
        private
        returns (uint256 ultiAmount)
    {
        if (inputAmountToSwap == 0) revert PumpInsufficientInputTokenAmount();
        if (minUltiAmount == 0) revert PumpInsufficientMinimumUltiAmount();

        // 2. Calculate expected output without slippage
        uint256 expectedUltiAmountWithoutSlippage = inputAmountToSwap * 1e18 / twap;

        // 3. Choose the higher minimum amount between user-specified and internal slippage protection
        uint256 minUltiAmountInternal =
            (expectedUltiAmountWithoutSlippage * (10000 - ULTIShared.MAX_SWAP_SLIPPAGE_BPS)) / 10000;
        uint256 effectiveMinUltiAmount = minUltiAmount > minUltiAmountInternal ? minUltiAmount : minUltiAmountInternal;

        // 4. Execute swap
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({
            tokenIn: inputTokenAddress,
            tokenOut: address(this),
            fee: ULTIShared.LP_FEE,
            recipient: msg.sender,
            deadline: deadline,
            amountIn: inputAmountToSwap,
            amountOutMinimum: effectiveMinUltiAmount,
            sqrtPriceLimitX96: 0
        });

        ultiAmount = uniswapRouter.exactInputSingle(params);

        // 5. Validate output amount
        if (ultiAmount < effectiveMinUltiAmount) {
            revert PumpInsufficientUltiOutput();
        }

        return ultiAmount;
    }

    /**
     * @notice Keeps track of how many times a user has pumped in a cycle
     * @dev Adds pumper to set if not present and increments their pump count.
     *      Using unchecked is safe since pump counts are limited by MAX_PUMPS_FOR_ACTIVE_PUMPERS.
     *      For new pumpers, incrementing from 0 gives us 1.
     *      For existing pumpers, we increment their current count.
     * @param cycle The current cycle number
     * @param pumper The address of the user who performed the pump
     */
    function _updatePumpCount(uint32 cycle, address pumper) private {
        pumpers[cycle].add(pumper);
        unchecked {
            pumpCounts[cycle][pumper]++;
        }
    }

    /**
     * @notice Gets a list of all addresses that have participated in pumping during a specific cycle
     * @dev Retrieves pumper addresses as an array from EnumerableSet
     * @param cycle The cycle number to get pumpers for
     * @return An array of addresses representing all pumpers in the specified cycle
     */
    function getPumpers(uint32 cycle) external view returns (address[] memory) {
        return pumpers[cycle].values();
    }

    /**
     * @notice Gets a list of all active pumpers (those who met minimum pump threshold) for a specific cycle
     * @dev Active pumpers must have at least MIN_PUMPS_FOR_ACTIVE_PUMPERS pumps
     * @param cycle The cycle number to get active pumpers for
     * @return Array of addresses representing active pumpers in the specified cycle
     */
    function getActivePumpers(uint32 cycle) external view returns (address[] memory) {
        EnumerableSet.AddressSet storage cyclePumpers = pumpers[cycle];
        uint256 totalPumpers = cyclePumpers.length();

        // First pass: count active pumpers
        uint32 activeCount = 0;
        for (uint32 i = 0; i < totalPumpers; i++) {
            address pumper = cyclePumpers.at(i);
            if (_isActivePumper(cycle, pumper)) {
                activeCount++;
            }
        }

        // Second pass: populate active pumpers array
        address[] memory activePumpers = new address[](activeCount);
        uint32 currentIndex = 0;
        for (uint32 i = 0; i < totalPumpers; i++) {
            address pumper = cyclePumpers.at(i);
            if (_isActivePumper(cycle, pumper)) {
                activePumpers[currentIndex] = pumper;
                currentIndex++;
            }
        }

        return activePumpers;
    }

    // ===============================================
    // Contributors Management
    // ===============================================

    /**
     * @notice Updates a contributor's activity and rewards for the current cycle
     * @dev Executes the following steps:
     *      1. Updates contributor's total deposits and referrals for the cycle
     *      2. Updates top contributors ranking with new contribution
     *      3. Calculates and increments the total top contributor bonus based on the current ULTI allocated + streak bonus
     * @param cycle The current cycle number
     * @param contributorAddress The address of the contributor
     * @param inputTokenDeposited Amount of input token deposited by the contributor
     * @param inputTokenReferred Amount of input token referred by the contributor
     * @param ultiAllocated Amount of ULTI allocated for the contributor
     * @return cycleContribution The discounted contribution of the user for the cycle
     */
    function _updateContributors(
        uint32 cycle,
        address contributorAddress,
        uint256 inputTokenDeposited,
        uint256 inputTokenReferred,
        uint256 ultiAllocated
    ) private returns (uint256 cycleContribution) {
        // 1. Update contributor's total deposits and referrals for the cycle
        totalInputTokenDeposited[cycle][contributorAddress] += inputTokenDeposited;
        totalInputTokenReferred[cycle][contributorAddress] += inputTokenReferred;
        totalUltiAllocated[cycle][contributorAddress] += ultiAllocated;

        // 2. Calculate discounted contribution with sniping protection
        uint256 currentContribution =
            (ultiAllocated * _getSnipingProtectionFactor(getCurrentDayInCycle())) / ULTIShared.PRECISION_FACTOR_1E6;

        // 3. Update total discounted contribution
        cycleContribution = discountedContributions[cycle][contributorAddress] + currentContribution;
        discountedContributions[cycle][contributorAddress] = cycleContribution;

        // 2. Update top contributors ranking with new contribution
        _updateTopContributors(cycle, contributorAddress, cycleContribution);

        // 3. Calculate and add bonus rewards: 3% of allocation size
        uint256 tcBonus = ultiAllocated * ULTIShared.TOP_CONTRIBUTOR_BONUS_PERCENTAGE / 100;
        topContributorsBonuses[cycle] += tcBonus;
    }

    /**
     * @notice Updates the list of top contributors for a cycle for any contribution being made (direct or for referrer)
     * @dev Processes the update through the following steps:
     *      1. Gets the current top contributors mapping for the cycle
     *      2. Calculates the updated discounted contribution for the contributor
     *      3. Caches minimum contribution
     *      4. If less than max contributors (33):
     *         - Adds or updates the contributor directly
     *         - Updates minimum contribution tracking if needed
     *      5. Most common case: early exits if contribution not higher than minimum
     *      6. Try to set the new contributor or update the existing contribution
     *      7. Finds new minimum contributor by iterating through all contributors
     *      8. Updates minimum tracking variables
     * @param cycle The current cycle number
     * @param contributorAddress The address of the contributor to update or add
     * @param cycleContribution The discounted contribution of the user for the cycle
     */
    function _updateTopContributors(uint32 cycle, address contributorAddress, uint256 cycleContribution) private {
        // 1. Get current top contributors mapping
        EnumerableMap.AddressToUintMap storage _topContributors = topContributors[cycle];
        uint256 length = _topContributors.length();

        // 3. Cache minimum contribution
        uint256 minContribution = minDiscountedContribution[cycle];

        // 4. Handle case when below max contributors
        if (length < ULTIShared.MAX_TOP_CONTRIBUTORS) {
            _topContributors.set(contributorAddress, cycleContribution);

            // Update min contribution if this is the first entry or new minimum
            if (length == 0 || cycleContribution < minContribution) {
                minDiscountedContribution[cycle] = cycleContribution;
                minContributorAddress[cycle] = contributorAddress;
            }

            // Emit event for new or updated contributor
            emit TopContributorsUpdated(cycle, contributorAddress, address(0), cycleContribution);
            return;
        }

        // 5. Most common case: early exit if contribution is not higher than current minimum
        // Note: In case of ties (equal discounted contributions), existing minimum top contributors maintain their position
        if (cycleContribution <= minContribution) {
            return;
        }

        // 6. Try to set the new contributor or update the existing contribution
        address removedContributorAddress;
        if (_topContributors.set(contributorAddress, cycleContribution)) {
            // Only remove minContributor if contributorAddress is a new entry
            _topContributors.remove(minContributorAddress[cycle]);
            removedContributorAddress = minContributorAddress[cycle];
        }

        // 7. Find new minimum contributor by iterating through all contributors
        uint256 newMinContribution = type(uint256).max;
        address newMinContributor = address(0);
        length = _topContributors.length();
        for (uint8 i = 0; i < length; i++) {
            (address currentContributor, uint256 currentContribution) = _topContributors.at(i);
            if (currentContribution < newMinContribution) {
                newMinContribution = currentContribution;
                newMinContributor = currentContributor;
            }
        }

        // 8. Update minimum tracking variables
        minDiscountedContribution[cycle] = newMinContribution;
        minContributorAddress[cycle] = newMinContributor;

        // Emit event for the update
        emit TopContributorsUpdated(cycle, contributorAddress, removedContributorAddress, cycleContribution);
    }

    /**
     * @notice Distributes bonus ULTI tokens to the top contributors from a past cycle
     * @dev Processes bonus distribution through these steps:
     *      1. Gets total bonus amount allocated for cycle and skips if 0 or future cycle
     *      2. Calculates total contribution across all top contributors
     *      3. For each top contributor:
     *         - Calculates proportional bonus based on their contribution
     *         - Adds 3.3% extra if they were an active pumper (>= 10 pumps)
     *         - Adds bonus to their claimable amount
     *      4. Marks cycle bonuses as distributed
     *      5. Emits event with distribution details
     * @param cycle The cycle for which to distribute bonuses
     */
    function _allocateTopContributorsBonuses(uint32 cycle) private {
        // 1. Get the total bonus amount allocated for this cycle
        uint256 topContributorsBonusAmount = topContributorsBonuses[cycle];

        // Skip if no bonuses amount were allocated for this cycle
        if (topContributorsBonusAmount == 0) {
            isTopContributorsBonusAllocated[cycle] = true;
            return;
        }

        // Skip if trying to distribute bonuses for current or future cycles
        if (cycle >= getCurrentCycle()) {
            return;
        }

        // 2. Calculate total contribution
        EnumerableMap.AddressToUintMap storage _topContributors = topContributors[cycle];
        uint256 totalTopContributorsContribution = 0;
        uint256 length = _topContributors.length();
        for (uint8 i = 0; i < length; i++) {
            (, uint256 contribution) = _topContributors.at(i);
            totalTopContributorsContribution += contribution;
        }

        // 3. Calculate and allocate bonuses for each top contributor
        for (uint8 i = 0; i < length; i++) {
            (address contributor, uint256 relativeContribution) = _topContributors.at(i);

            // Calculate base bonus proportional to contribution
            uint256 bonus = (topContributorsBonusAmount * relativeContribution) / totalTopContributorsContribution;

            // Apply active pumper bonus if they qualify
            if (_isActivePumper(cycle, contributor) && bonus > 0) {
                bonus = bonus * (100 + ULTIShared.ACTIVE_PUMPERS_BONUS_PERCENTAGE) / 100;
            }

            if (bonus > 0) {
                claimableBonuses[contributor] += bonus;
            }
        }

        // 4. Mark as distributed
        isTopContributorsBonusAllocated[cycle] = true;

        // 5. Emit event
        emit TopContributorBonusesDistributed(cycle, topContributorsBonusAmount);
    }

    /**
     * @notice Checks if a given address is a top contributor for a specific cycle
     * @dev External wrapper function that calls internal _isTopContributor
     * @param cycle The cycle number to check
     * @param user The address to check
     * @return bool True if the address is a top contributor for the specified cycle
     */
    function isTopContributor(uint32 cycle, address user) public view returns (bool) {
        return _isTopContributor(cycle, user);
    }

    /**
     * @notice Internal function to check if an address is a top contributor
     * @dev Uses EnumerableMap's contains function to efficiently check if the address exists in the top contributors mapping
     * @param cycle The cycle number to check
     * @param user The address to check
     * @return bool True if the address is a top contributor for the specified cycle
     */
    function _isTopContributor(uint32 cycle, address user) internal view returns (bool) {
        return topContributors[cycle].contains(user);
    }

    /**
     * @notice Gets the list of top contributors for a specific cycle
     * @dev Retrieves the top contributors list by calling _getTopContributors to fetch the data
     * @param cycle The cycle number to get the top contributors for
     * @return An array of TopContributor structs representing the top contributors
     */
    function getTopContributors(uint32 cycle) external view returns (ULTIShared.TopContributor[] memory) {
        return _getTopContributors(cycle);
    }

    /**
     * @notice Gets a list of all top contributors and their contribution details for a given cycle
     * @dev Function execution steps:
     *      1. Get the mapping of top contributors for the specified cycle
     *      2. Create a new array to store the top contributors data
     *      3. For each top contributor:
     *         - Get their address and discounted contribution amount
     *         - Fetch their full contribution details (input token deposited/referred, ULTI allocated, pump count)
     *         - Store all data in the array
     *      4. Return the populated array
     * @param cycle The cycle number to get the top contributors for
     * @return An array of TopContributor structs representing the top contributors
     */
    function _getTopContributors(uint32 cycle) private view returns (ULTIShared.TopContributor[] memory) {
        // 1. Get mapping of top contributors for this cycle
        EnumerableMap.AddressToUintMap storage _topContributors = topContributors[cycle];
        uint256 length = _topContributors.length();

        // 2. Create array to store top contributors data
        ULTIShared.TopContributor[] memory topContributorsArray = new ULTIShared.TopContributor[](length);

        // 3. Populate array with each top contributor's full details
        for (uint8 i = 0; i < length; i++) {
            (address contributorAddress, uint256 discountedContribution) = _topContributors.at(i);
            topContributorsArray[i] = ULTIShared.TopContributor({
                contributorAddress: contributorAddress,
                inputTokenDeposited: totalInputTokenDeposited[cycle][contributorAddress],
                inputTokenReferred: totalInputTokenReferred[cycle][contributorAddress],
                ultiAllocated: totalUltiAllocated[cycle][contributorAddress],
                discountedContribution: discountedContribution,
                pumpCount: pumpCounts[cycle][contributorAddress]
            });
        }

        // 4. Return the populated array
        return topContributorsArray;
    }

    // ===============================================
    // Referral System
    // ===============================================

    /**
     * @notice Processes referral bonuses (2-way) when a user makes a deposit
     * @dev Execution steps:
     *      1. Gets effective referrer (stored or provided)
     *      2. Updates referrer mapping if not already set and valid referrer provided
     *      3. If valid referrer exists:
     *         a. Cap referral bonus based on skin-in-game limit
     *         b. Initialize next bonus claim timestamp for referrer if needed
     *         c. Update referrer's allocated bonuses and contributions
     *         d. Calculate and allocate referred user bonus (33% of referrer bonus)
     * @param referrer The address of the referrer
     * @param inputTokenReferred The amount of input token deposited by user (referred by referrer)
     * @param ultiToMint The amount of ULTI tokens to mint for the depositor before calculating the referral bonuses
     * @param cycle The current cycle number
     * @return effectiveReferrer The actual referrer used (stored or provided)
     * @return referrerBonus The amount of bonus tokens allocated to the referrer
     * @return referredBonus The amount of bonus tokens allocated to the referred user
     */
    function _updateReferrals(address referrer, uint256 inputTokenReferred, uint256 ultiToMint, uint32 cycle)
        private
        returns (address effectiveReferrer, uint256 referrerBonus, uint256 referredBonus)
    {
        // 1. Get effective referrer - use stored if available, otherwise use provided
        effectiveReferrer = referrers[msg.sender] != address(0) ? referrers[msg.sender] : referrer;

        // 2. Update referrer mapping if not already set and valid referrer provided: not set, not zero. Not circular already checked in `_deposit`
        if (referrers[msg.sender] == address(0) && referrer != address(0)) {
            referrers[msg.sender] = referrer;
        }

        // 3. Calculate referrer bonus if valid effective referrer exists
        if (effectiveReferrer != address(0)) {
            referrerBonus = (ultiToMint * _getReferralBonusPercentage(cycle)) / (100 * ULTIShared.PRECISION_FACTOR_1E6);

            // 3a. Cap referral bonus based on skin-in-game limit (10X of total ULTI allocated ever)
            // Note: if the cap is reached, no referrer and referred bonuses will be accumulated.
            uint256 skinInAGameCap =
                totalUltiAllocatedEver[effectiveReferrer] * ULTIShared.REFERRAL_SKIN_IN_THE_GAME_CAP_MULTIPLIER;
            uint256 remainingBonusAllowance = skinInAGameCap > accumulatedReferralBonuses[effectiveReferrer]
                ? skinInAGameCap - accumulatedReferralBonuses[effectiveReferrer]
                : 0;
            referrerBonus = referrerBonus > remainingBonusAllowance ? remainingBonusAllowance : referrerBonus;

            if (referrerBonus > 0) {
                // 3b. Initialize next bonus claim timestamp for referrer if not already set
                if (nextAllBonusesClaimTimestamp[effectiveReferrer] == 0) {
                    nextAllBonusesClaimTimestamp[effectiveReferrer] =
                        block.timestamp + ULTIShared.ALL_BONUSES_CLAIM_INTERVAL;
                }

                // 3c. Update referrer's allocated bonuses and contributions
                claimableBonuses[effectiveReferrer] += referrerBonus;
                accumulatedReferralBonuses[effectiveReferrer] += referrerBonus;
                _updateContributors(cycle, effectiveReferrer, 0, inputTokenReferred, referrerBonus);

                // 3d. Calculate and allocate referred user bonus
                referredBonus = (referrerBonus * ULTIShared.REFERRAL_BONUS_FOR_REFERRED_PERCENTAGE) / 100;
                claimableBonuses[msg.sender] += referredBonus;
                // The bonus for referred users encourages the use of referral links over independent deposits.
                // This increases confidence in the referral program's effectiveness among referrers.
                // Note that this small additional bonus is excluded from the depositor's total contribution.
            }
        }

        return (effectiveReferrer, referrerBonus, referredBonus);
    }

    // ===============================================
    // Streak Management
    // ===============================================

    /**
     * @notice Calculates bonus rewards for users who consistently deposit across multiple cycles
     * @dev Calculates streak bonus through following steps:
     *      1. Updates user's streak count based on deposit history
     *      2. Checks if streak is long enough for bonus (min 4 cycles)
     *      3. Calculates bonus percentage based on streak length:
     *         - Uses formula: maxBonus + 1 - (1/streakCount)
     *         - Scales values by precision factor
     *      4. Applies bonus percentage to base ULTI amount
     * @param user The address of the user
     * @param inputTokenDeposited The amount of input token deposited
     * @param ultiToMintWithoutBonus The amount of ULTI to be minted for the deposit without bonus
     * @param cycle The current cycle number
     * @return The streak bonus amount allocated
     * @return The streak count
     */
    function _updateStreakBonus(address user, uint256 inputTokenDeposited, uint256 ultiToMintWithoutBonus, uint32 cycle)
        private
        returns (uint256, uint32)
    {
        // 1. Update streak count
        uint32 streakCount = _updateStreakCount(cycle, user, inputTokenDeposited);

        // 2. Check minimum streak count requirement
        if (streakCount < ULTIShared.STREAK_BONUS_COUNT_START) {
            return (0, streakCount);
        }

        // 3. Calculate streak bonus percentage
        uint256 streakBonusPercentage =
            ULTIShared.STREAK_BONUS_MAX_PLUS_ONE_SCALED - (ULTIShared.PRECISION_FACTOR_1E6 / streakCount); // scaled by 1e6

        // 4. Calculate final bonus amount
        uint256 streakBonus = ultiToMintWithoutBonus * streakBonusPercentage / ULTIShared.PRECISION_FACTOR_1E6;

        claimableBonuses[msg.sender] += streakBonus;

        return (streakBonus, streakCount);
    }

    /**
     * @notice Updates a user's streak of consecutive cycles with deposits
     * @dev Main execution steps:
     *      1. Handle first cycle as special case:
     *         - Set streak count to 1 since no previous cycle exists
     *      2. For subsequent cycles:
     *         - Get previous cycle's total deposits
     *         - Calculate current cycle's total deposits including new deposit
     *         - Get previous streak count
     *         - Check if current deposits are within valid range (1X-10X of previous)
     *         - Increment streak if valid, reset to 1 if invalid
     *      3. Store and return new streak count
     * @param cycle The current cycle number
     * @param user The address of the user
     * @param inputTokenDeposited The amount of input token being deposited
     * @return The updated streak count for the user
     */
    function _updateStreakCount(uint32 cycle, address user, uint256 inputTokenDeposited) private returns (uint32) {
        // Cache storage reads
        uint32 newStreakCount;

        // 1. Handle first cycle as special case: no previous cycle to look up
        if (cycle == 1) {
            newStreakCount = 1;
        } else {
            // 2. Calculate total deposits for current and previous cycles
            uint256 previousCycleDeposits = totalInputTokenDeposited[cycle - 1][user];
            uint256 currentCycleDeposits = totalInputTokenDeposited[cycle][user] + inputTokenDeposited;

            // Compute streak validity in a single condition
            bool validStreak =
                currentCycleDeposits >= previousCycleDeposits && currentCycleDeposits <= 10 * previousCycleDeposits;

            // Update streak count based on validity: increment if valid, reset to 1 if invalid (break the streak)
            newStreakCount = validStreak ? streakCounts[cycle - 1][user] + 1 : 1;
        }

        // 3. Store and return new streak count
        streakCounts[cycle][user] = newStreakCount;
        return newStreakCount;
    }

    // ===============================================
    // Cycle & Time Management
    // ===============================================

    /**
     * @notice Returns the current cycle number
     * @dev Calculates the current cycle number through these steps:
     *      1. Gets time elapsed since launch by subtracting launch timestamp from current time
     *      2. Divides elapsed time by cycle duration to get number of completed cycles
     *      3. Adds 1 to account for current ongoing cycle
     *      4. Converts result to uint32 for storage efficiency
     * @return The current cycle number
     */
    function getCurrentCycle() public view returns (uint32) {
        return uint32((block.timestamp - launchTimestamp) / ULTIShared.CYCLE_INTERVAL) + 1;
    }

    /**
     * @notice Returns which day we are currently in within the cycle (1-33)
     * @dev Uses modulo to get elapsed time within current cycle, then converts to days
     * @return The current day number (1-33) within the cycle
     */
    function getCurrentDayInCycle() public view returns (uint8) {
        return uint8(((block.timestamp - launchTimestamp) % ULTIShared.CYCLE_INTERVAL) / 1 days + 1);
    }

    /**
     * @notice Retrieves the referral bonus percentage value for a specific cycle
     * @dev Provides external access to the internal referral bonus percentage values
     * @param cycle The cycle number to fetch the percentage for
     * @return The referral bonus percentage value for the specified cycle
     */
    function getReferralBonusPercentage(uint32 cycle) external pure returns (uint32) {
        return _getReferralBonusPercentage(cycle);
    }

    /// @notice Referral Bonus Percentage Array - used to normalize down the weight of bonuses and soften inflation overtime
    /// @dev This array represents the exponentially decaying referral percentage for each cycle.
    /// It starts at 33% for cycle 1, reaches 3% by cycle 33, then remains at 3% forever.
    /// Mathematical formula: A(i) = max(33% * (3% / 33%)^(i / 32), 3%)
    /// Array contains discrete values for cycles 1 to 33
    /// Each value is scaled by 10^6 for precision (33% => 33,000,000)
    /// Usage:
    /// - Index 0 corresponds to cycle 1
    /// - Index 32 corresponds to cycle 33
    /// - To apply percentage: actualValue = (originalValue * _getReferralBonusPercentage(cycleNumber)) / 100_000_000
    /// @param cycle The cycle number to get the percentage for
    /// @return The referral bonus percentage value for the specified cycle, scaled by 10^6
    function _getReferralBonusPercentage(uint32 cycle) internal pure returns (uint32) {
        if (cycle <= ULTIShared.ULTI_NUMBER) {
            // Pre-computed values for cycles 1-33
            uint32[33] memory percentages = [
                33000000,
                30617548,
                28407099,
                26356235,
                24453433,
                22688006,
                21050034,
                19530316,
                18120316,
                16812110,
                15598352,
                14472221,
                13427392,
                12457995,
                11558584,
                10724106,
                9949874,
                9231538,
                8565062,
                7946703,
                7372987,
                6840691,
                6346824,
                5888612,
                5463480,
                5069042,
                4703080,
                4363538,
                4048511,
                3756226,
                3485044,
                3233439,
                3000000
            ];
            return percentages[cycle - 1];
        } else {
            return 3000000; // 3% for all cycles after 33
        }
    }

    /**
     * @notice Retrieves the sniping protection factor for a given day within the current cycle
     * @dev Uses the internal _getSnipingProtectionFactor function to fetch the factor
     * @param dayInCycle The day number within the current cycle (1-33)
     * @return The sniping protection factor for the given day, scaled by 10^6
     */
    function getSnipingProtectionFactor(uint8 dayInCycle) external pure returns (uint32) {
        return _getSnipingProtectionFactor(dayInCycle);
    }

    /// @notice Sniping Protection Factor Array - used as last minute snipping protection when updating top contributors
    /// @dev This array represents a logistic function that creates a sharply falling curve.
    /// It smoothly transitions from 100% protection at the start of the cycle
    /// to approximately ~1% protection at the end of the cycle.
    /// Mathematical formula: f(d) = 3 / (1 + exp(0.4 * (d - 35) + 0.09)) - 2
    /// Where:
    ///   d: day of the cycle (1 to 33)
    ///   f(d): discounting factor for day d
    /// Array contains discrete values for d = [1, 33]
    /// Each value is scaled by 10^6 for precision (~1X =>  999,996)
    /// Usage:
    /// - Input 1 corresponds to day 1 of the cycle
    /// - Input 33 corresponds to day 33 of the cycle
    /// - To apply discount: actualValue = (originalValue * getSnipingProtectionFactor(dayOfCycle)) / 100_000_000
    /// @param dayInCycle The day number within the current cycle (1-33)
    /// @return The sniping protection factor for the given day, scaled by 10^6
    function _getSnipingProtectionFactor(uint8 dayInCycle) internal pure returns (uint32) {
        if (dayInCycle < 1 || dayInCycle > ULTIShared.ULTI_NUMBER) {
            revert SnipingProctectionInvalidDayInCycle(dayInCycle);
        }

        uint32[33] memory factors = [
            uint32(999996),
            uint32(999994),
            uint32(999991),
            uint32(999986),
            uint32(999980),
            uint32(999970),
            uint32(999955),
            uint32(999933),
            uint32(999900),
            uint32(999851),
            uint32(999778),
            uint32(999668),
            uint32(999505),
            uint32(999262),
            uint32(998899),
            uint32(998358),
            uint32(997551),
            uint32(996348),
            uint32(994556),
            uint32(991885),
            uint32(987911),
            uint32(982000),
            uint32(973227),
            uint32(960234),
            uint32(941060),
            uint32(912913),
            uint32(871910),
            uint32(812842),
            uint32(729106),
            uint32(613057),
            uint32(457184),
            uint32(256387),
            uint32(11203)
        ];
        return factors[dayInCycle - 1];
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

File 7 of 48 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Enumerable.sol)

pragma solidity ^0.8.20;

import {IERC721Enumerable} from "../token/ERC721/extensions/IERC721Enumerable.sol";

File 8 of 48 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC721Metadata.sol)

pragma solidity ^0.8.20;

import {IERC721Metadata} from "../token/ERC721/extensions/IERC721Metadata.sol";

File 9 of 48 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

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

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

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

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

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

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

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

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

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

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

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

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

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

        emit Transfer(from, to, value);
    }

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

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

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

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

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

File 10 of 48 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

File 12 of 48 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

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

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

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

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

File 13 of 48 : IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.20;

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

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

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

pragma solidity ^0.8.20;

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

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

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

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

File 15 of 48 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

File 16 of 48 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

pragma solidity ^0.8.20;

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

File 20 of 48 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

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

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

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

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

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

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

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

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

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

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 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²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

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

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

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

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

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

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

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

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

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

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

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

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

File 22 of 48 : Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

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

pragma solidity ^0.8.20;

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

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

    uint256 private _status;

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

    constructor() {
        _status = NOT_ENTERED;
    }

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Library for managing an enumerable variant of Solidity's
 * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
 * type.
 *
 * Maps have the following properties:
 *
 * - Entries are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Entries are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableMap for EnumerableMap.UintToAddressMap;
 *
 *     // Declare a set state variable
 *     EnumerableMap.UintToAddressMap private myMap;
 * }
 * ```
 *
 * The following map types are supported:
 *
 * - `uint256 -> address` (`UintToAddressMap`) since v3.0.0
 * - `address -> uint256` (`AddressToUintMap`) since v4.6.0
 * - `bytes32 -> bytes32` (`Bytes32ToBytes32Map`) since v4.6.0
 * - `uint256 -> uint256` (`UintToUintMap`) since v4.7.0
 * - `bytes32 -> uint256` (`Bytes32ToUintMap`) since v4.7.0
 * - `uint256 -> bytes32` (`UintToBytes32Map`) since v5.1.0
 * - `address -> address` (`AddressToAddressMap`) since v5.1.0
 * - `address -> bytes32` (`AddressToBytes32Map`) since v5.1.0
 * - `bytes32 -> address` (`Bytes32ToAddressMap`) since v5.1.0
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableMap, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableMap.
 * ====
 */
library EnumerableMap {
    using EnumerableSet for EnumerableSet.Bytes32Set;

    // To implement this library for multiple types with as little code repetition as possible, we write it in
    // terms of a generic Map type with bytes32 keys and values. The Map implementation uses private functions,
    // and user-facing implementations such as `UintToAddressMap` are just wrappers around the underlying Map.
    // This means that we can only create new EnumerableMaps for types that fit in bytes32.

    /**
     * @dev Query for a nonexistent map key.
     */
    error EnumerableMapNonexistentKey(bytes32 key);

    struct Bytes32ToBytes32Map {
        // Storage of keys
        EnumerableSet.Bytes32Set _keys;
        mapping(bytes32 key => bytes32) _values;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
        map._values[key] = value;
        return map._keys.add(key);
    }

    /**
     * @dev Removes a key-value pair from a map. O(1).
     *
     * Returns true if the key was removed from the map, that is if it was present.
     */
    function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool) {
        delete map._values[key];
        return map._keys.remove(key);
    }

    /**
     * @dev Returns true if the key is in the map. O(1).
     */
    function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool) {
        return map._keys.contains(key);
    }

    /**
     * @dev Returns the number of key-value pairs in the map. O(1).
     */
    function length(Bytes32ToBytes32Map storage map) internal view returns (uint256) {
        return map._keys.length();
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool exists, bytes32 value) {
        bytes32 val = map._values[key];
        if (val == bytes32(0)) {
            return (contains(map, key), bytes32(0));
        } else {
            return (true, val);
        }
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32) {
        bytes32 value = map._values[key];
        if (value == 0 && !contains(map, key)) {
            revert EnumerableMapNonexistentKey(key);
        }
        return value;
    }

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

    // UintToUintMap

    struct UintToUintMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToUintMap storage map, uint256 key, uint256 value) internal returns (bool) {
        return set(map._inner, bytes32(key), bytes32(value));
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToUintMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(UintToUintMap storage map, uint256 key) internal view returns (bool exists, uint256 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
        return (success, uint256(val));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) {
        return uint256(get(map._inner, bytes32(key)));
    }

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

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

        return result;
    }

    // UintToAddressMap

    struct UintToAddressMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
        return set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToAddressMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool exists, address value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
        return (success, address(uint160(uint256(val))));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
        return address(uint160(uint256(get(map._inner, bytes32(key)))));
    }

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

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

        return result;
    }

    // UintToBytes32Map

    struct UintToBytes32Map {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(UintToBytes32Map storage map, uint256 key, bytes32 value) internal returns (bool) {
        return set(map._inner, bytes32(key), value);
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(UintToBytes32Map storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(UintToBytes32Map storage map, uint256 key) internal view returns (bool exists, bytes32 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(key));
        return (success, val);
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(UintToBytes32Map storage map, uint256 key) internal view returns (bytes32) {
        return get(map._inner, bytes32(key));
    }

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

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

        return result;
    }

    // AddressToUintMap

    struct AddressToUintMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(AddressToUintMap storage map, address key, uint256 value) internal returns (bool) {
        return set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(AddressToUintMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(AddressToUintMap storage map, address key) internal view returns (bool exists, uint256 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
        return (success, uint256(val));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
        return uint256(get(map._inner, bytes32(uint256(uint160(key)))));
    }

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

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

        return result;
    }

    // AddressToAddressMap

    struct AddressToAddressMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(AddressToAddressMap storage map, address key, address value) internal returns (bool) {
        return set(map._inner, bytes32(uint256(uint160(key))), bytes32(uint256(uint160(value))));
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(AddressToAddressMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(AddressToAddressMap storage map, address key) internal view returns (bool exists, address value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
        return (success, address(uint160(uint256(val))));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(AddressToAddressMap storage map, address key) internal view returns (address) {
        return address(uint160(uint256(get(map._inner, bytes32(uint256(uint160(key)))))));
    }

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

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

        return result;
    }

    // AddressToBytes32Map

    struct AddressToBytes32Map {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(AddressToBytes32Map storage map, address key, bytes32 value) internal returns (bool) {
        return set(map._inner, bytes32(uint256(uint160(key))), value);
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(AddressToBytes32Map storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(AddressToBytes32Map storage map, address key) internal view returns (bool exists, bytes32 value) {
        (bool success, bytes32 val) = tryGet(map._inner, bytes32(uint256(uint160(key))));
        return (success, val);
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(AddressToBytes32Map storage map, address key) internal view returns (bytes32) {
        return get(map._inner, bytes32(uint256(uint160(key))));
    }

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

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

        return result;
    }

    // Bytes32ToUintMap

    struct Bytes32ToUintMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(Bytes32ToUintMap storage map, bytes32 key, uint256 value) internal returns (bool) {
        return set(map._inner, key, bytes32(value));
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(Bytes32ToUintMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(Bytes32ToUintMap storage map, bytes32 key) internal view returns (bool exists, uint256 value) {
        (bool success, bytes32 val) = tryGet(map._inner, key);
        return (success, uint256(val));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(Bytes32ToUintMap storage map, bytes32 key) internal view returns (uint256) {
        return uint256(get(map._inner, key));
    }

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

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

        return result;
    }

    // Bytes32ToAddressMap

    struct Bytes32ToAddressMap {
        Bytes32ToBytes32Map _inner;
    }

    /**
     * @dev Adds a key-value pair to a map, or updates the value for an existing
     * key. O(1).
     *
     * Returns true if the key was added to the map, that is if it was not
     * already present.
     */
    function set(Bytes32ToAddressMap storage map, bytes32 key, address value) internal returns (bool) {
        return set(map._inner, key, bytes32(uint256(uint160(value))));
    }

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

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

    /**
     * @dev Returns the number of elements in the map. O(1).
     */
    function length(Bytes32ToAddressMap storage map) internal view returns (uint256) {
        return length(map._inner);
    }

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

    /**
     * @dev Tries to returns the value associated with `key`. O(1).
     * Does not revert if `key` is not in the map.
     */
    function tryGet(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (bool exists, address value) {
        (bool success, bytes32 val) = tryGet(map._inner, key);
        return (success, address(uint160(uint256(val))));
    }

    /**
     * @dev Returns the value associated with `key`. O(1).
     *
     * Requirements:
     *
     * - `key` must be in the map.
     */
    function get(Bytes32ToAddressMap storage map, bytes32 key) internal view returns (address) {
        return address(uint160(uint256(get(map._inner, key))));
    }

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

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

        return result;
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

File 26 of 48 : 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 27 of 48 : IUniswapV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}

File 28 of 48 : 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 29 of 48 : 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 30 of 48 : 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 31 of 48 : 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 32 of 48 : 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 33 of 48 : 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 34 of 48 : 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 35 of 48 : 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 36 of 48 : IERC721Permit.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

import '@openzeppelin/contracts/token/ERC721/IERC721.sol';

/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
    /// @notice The permit typehash used in the permit signature
    /// @return The typehash for the permit
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /// @notice The domain separator used in the permit signature
    /// @return The domain seperator used in encoding of permit signature
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}

File 37 of 48 : IPeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
    /// @return Returns the address of the Uniswap V3 factory
    function factory() external view returns (address);

    /// @return Returns the address of WETH9
    function WETH9() external view returns (address);
}

File 38 of 48 : IPeripheryPayments.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    /// @param amountMinimum The minimum amount of WETH9 to unwrap
    /// @param recipient The address receiving ETH
    function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;

    /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH() external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    /// @param token The contract address of the token which will be transferred to `recipient`
    /// @param amountMinimum The minimum amount of token required for a transfer
    /// @param recipient The destination address of the token
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) external payable;
}

File 39 of 48 : IPoolInitializer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
    /// @param token0 The contract address of token0 of the pool
    /// @param token1 The contract address of token1 of the pool
    /// @param fee The fee amount of the v3 pool for the specified token pair
    /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
    /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint24 fee,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}

File 40 of 48 : ISwapRouter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

File 41 of 48 : IWrappedNative.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/**
 * @title IWrappedNative
 * @dev Interface for wrapped native currency (e.g., ETH => WETH, BNB => WBNB, etc.)
 * @notice Based on the canonical WETH9 implementation
 * @notice See: https://github.com/Uniswap/v2-periphery/blob/master/contracts/interfaces/IWETH.sol
 */
interface IWrappedNative {
    /// @notice Deposit native currency (e.g., ETH) to get wrapped tokens (e.g., WETH)
    function deposit() external payable;

    /// @notice Withdraw native currency (e.g., ETH) by burning wrapped tokens (e.g., WETH)
    function withdraw(uint256) external;
}

File 42 of 48 : FullMath.sol
// SPDX-License-Identifier: MIT

// This file is a modified copy of the official Uniswap FullMath library from @uniswap/v3-core/contracts/libraries/FullMath.sol
// The modifications were made to ensure compatibility with Solidity version 0.8.x, as the original library was designed for Solidity versions >=0.4.0.
// Modifications: pragma version and use of bitwise operator line 66

pragma solidity 0.8.28; // Modified from: "pragma solidity >=0.4.0;"

/// @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 for more efficient computing
            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.
            uint256 twos = (~denominator + 1) & denominator; // Modified from: uint256 twos = -denominator & denominator;
            // 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) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}

File 43 of 48 : INonfungiblePositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-later

// This file is a modified copy of the official Uniswap INonfungiblePositionManager library from @uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol
// The modifications were made to ensure compatibility with Solidity version 0.8.x, as the original library was designed for Solidity versions >=0.7.5.
// Modifications: pragma version and valid imports

pragma solidity 0.8.28; // Modified from: "pragma solidity >=0.7.5;"
pragma abicoder v2;

// Modified: the path of the official Uniswap IERC721Metadata previously @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
import "@openzeppelin/contracts/interfaces/IERC721Metadata.sol";

// Modified: the path of the official Uniswap IERC721Enumerable previously @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
import "@openzeppelin/contracts/interfaces/IERC721Enumerable.sol";

// Modified: the path of the official Uniswap PoolAddress previously @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol
import "./PoolAddress.sol";

import "@uniswap/v3-periphery/contracts/interfaces/IPoolInitializer.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IERC721Permit.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryPayments.sol";
import "@uniswap/v3-periphery/contracts/interfaces/IPeripheryImmutableState.sol";

/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
    IPoolInitializer,
    IPeripheryPayments,
    IPeripheryImmutableState,
    IERC721Metadata,
    IERC721Enumerable,
    IERC721Permit
{
    /// @notice Emitted when liquidity is increased for a position NFT
    /// @dev Also emitted when a token is minted
    /// @param tokenId The ID of the token for which liquidity was increased
    /// @param liquidity The amount by which liquidity for the NFT position was increased
    /// @param amount0 The amount of token0 that was paid for the increase in liquidity
    /// @param amount1 The amount of token1 that was paid for the increase in liquidity
    event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when liquidity is decreased for a position NFT
    /// @param tokenId The ID of the token for which liquidity was decreased
    /// @param liquidity The amount by which liquidity for the NFT position was decreased
    /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
    /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
    event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when tokens are collected for a position NFT
    /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
    /// @param tokenId The ID of the token for which underlying tokens were collected
    /// @param recipient The address of the account that received the collected tokens
    /// @param amount0 The amount of token0 owed to the position that was collected
    /// @param amount1 The amount of token1 owed to the position that was collected
    event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);

    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return nonce The nonce for permits
    /// @return operator The address that is approved for spending
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return fee The fee associated with the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(uint256 tokenId)
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// @notice Creates a new position wrapped in a NFT
    /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
    /// a method does not exist, i.e. the pool is assumed to be initialized.
    /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
    /// @return tokenId The ID of the token that represents the minted position
    /// @return liquidity The amount of liquidity for this position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mint(MintParams calldata params)
        external
        payable
        returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
    /// @param params tokenId The ID of the token for which liquidity is being increased,
    /// amount0Desired The desired amount of token0 to be spent,
    /// amount1Desired The desired amount of token1 to be spent,
    /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
    /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return liquidity The new liquidity amount as a result of the increase
    /// @return amount0 The amount of token0 to acheive resulting liquidity
    /// @return amount1 The amount of token1 to acheive resulting liquidity
    function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Decreases the amount of liquidity in a position and accounts it to the position
    /// @param params tokenId The ID of the token for which liquidity is being decreased,
    /// amount The amount by which liquidity will be decreased,
    /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
    /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return amount0 The amount of token0 accounted to the position's tokens owed
    /// @return amount1 The amount of token1 accounted to the position's tokens owed
    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external
        payable
        returns (uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
    /// @param params tokenId The ID of the NFT for which tokens are being collected,
    /// recipient The account that should receive the tokens,
    /// amount0Max The maximum amount of token0 to collect,
    /// amount1Max The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
    /// must be collected first.
    /// @param tokenId The ID of the token that is being burned
    function burn(uint256 tokenId) external payable;
}

File 44 of 48 : LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-2.0-or-later

// This file is a modified copy of the official Uniswap LiquidityAmounts library from @uniswap/v3-periphery/contracts/libraries/LiquidityAmounts.sol
// The modifications were made to ensure compatibility with Solidity version 0.8.x, as the original library was designed for Solidity versions >=0.5.0.
// Modifications: pragma version and replace Uniswap's FullMath by OpenZeppelin's Math

pragma solidity 0.8.28; // Modified from: "pragma solidity >=0.5.0;"

// Modified: use OpenZeppelin Math that supports uint512 Overflow Handling instead of @uniswap/v3-core/contracts/libraries/FullMath.sol
import "@openzeppelin/contracts/utils/math/Math.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 {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    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 representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @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 = Math.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
        return toUint128(Math.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 representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @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(Math.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
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    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 representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    function getAmount0ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
        internal
        pure
        returns (uint256 amount0)
    {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return Math.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 representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount of token1
    function getAmount1ForLiquidity(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity)
        internal
        pure
        returns (uint256 amount1)
    {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return Math.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
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    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 45 of 48 : Oracle.sol
// SPDX-License-Identifier: BUSL-1.1

// This file is a modified copy of the official Uniswap Oracle library from @uniswap/v3-core/contracts/libraries/Oracle.sol
// The modifications were made to ensure compatibility with Solidity version 0.8.x, as the original library was designed for Solidity versions >=0.5.0.
// Modification: pragma version, valid imports, only kept `getQuoteAtTick` and remove all other functions

pragma solidity 0.8.28; // Modified: the pragma was changed from "pragma solidity >=0.5.0;"

// Modified: local import instead of @uniswap/v3-core/contracts/libraries/FullMath.sol
import "./FullMath.sol";

// Modified: local import instead of @uniswap/v3-core/contracts/libraries/FullMath.sol
import "./TickMath.sol";

import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    // Modified: only kept the `getQuoteAtTick` compared to the orignal version

    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(int24 tick, uint128 baseAmount, address baseToken, address quoteToken)
        internal
        pure
        returns (uint256 quoteAmount)
    {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }
}

File 46 of 48 : PoolAddress.sol
// SPDX-License-Identifier: GPL-2.0-or-later

// This file is a modified copy of the official Uniswap PoolAddress library from @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol
// The modifications were made to ensure compatibility with Solidity version 0.8.x, as the original library was designed for Solidity versions >=0.5.0.
// Modification: pragma version, and casting to uint160 in `computeAddress` line 37

pragma solidity 0.8.28; // Modified: the pragma was changed from "pragma solidity >=0.5.0;"

/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
    bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;

    /// @notice The identifying key of the pool
    struct PoolKey {
        address token0;
        address token1;
        uint24 fee;
    }

    /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
    /// @param tokenA The first token of a pool, unsorted
    /// @param tokenB The second token of a pool, unsorted
    /// @param fee The fee level of the pool
    /// @return Poolkey The pool details with ordered token0 and token1 assignments
    function getPoolKey(address tokenA, address tokenB, uint24 fee) internal pure returns (PoolKey memory) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
    }

    /// @notice Deterministically computes the pool address given the factory and PoolKey
    /// @param factory The Uniswap V3 factory contract address
    /// @param key The PoolKey
    /// @return pool The contract address of the V3 pool
    function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1);
        pool = address(
            uint160( // Explicit conversion to uint160 added for compatibility with Solidity 0.8.x
                uint256(
                    keccak256(
                        abi.encodePacked(
                            hex"ff",
                            factory,
                            keccak256(abi.encode(key.token0, key.token1, key.fee)),
                            POOL_INIT_CODE_HASH
                        )
                    )
                )
            )
        );
    }
}

File 47 of 48 : TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later

// This file is a modified copy of the official Uniswap TickMath library from @uniswap/v3-core/contracts/libraries/TickMath.sol
// The modifications were made to ensure compatibility with Solidity version 0.8.x, as the original library was designed for Solidity versions >=0.5.0.
// Modification: pragma version, wrapping `getSqrtRatioAtTick` and `getTickAtSqrtRatio` with unchecked, and casting to uint24 in `getSqrtRatioAtTick` line 30

pragma solidity 0.8.28; // Modified: the pragma was changed from "pragma solidity >=0.5.0;"

/// @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) {
        unchecked {
            uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
            require(absTick <= uint256(uint24(MAX_TICK)), "T"); // Explicit conversion to uint24 added for compatibility with Solidity 0.8.x

            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) {
        unchecked {
            // 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;
        }
    }
}

File 48 of 48 : ULTIShared.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;

/// @title ULTI Protocol Constants
/// @notice Contains all constants used in the ULTI protocol
/// @author @0xStef
library ULTIShared {
    // ===============================================
    // Constants
    // ===============================================

    /// @notice The number associated with ULTI, used in various calculations
    uint256 public constant ULTI_NUMBER = 33;

    /// @notice Maximum number of top contributors that can be tracked per cycle (33)
    uint256 public constant MAX_TOP_CONTRIBUTORS = ULTI_NUMBER;

    // Time-related constants
    /// @notice Cycle interval in seconds (33 days in seconds)
    uint256 public constant CYCLE_INTERVAL = 2851200;

    /// @notice Minimum interval between ULTI claims or deposits (24 hours in seconds)
    uint256 public constant DEPOSIT_CLAIM_INTERVAL = 86400;

    /// @notice Duration of the early bird price period after launch (24 hours in seconds)
    uint256 public constant EARLY_BIRD_PRICE_DURATION = 86400;

    /// @notice Minimum time interval for Time-Weighted Average Price (TWAP) calculation
    uint32 public constant MIN_TWAP_INTERVAL = 1089; // 18 minutes and 9 seconds in seconds

    /// @notice Interval between all bonuses claims (99 days)
    uint256 public constant ALL_BONUSES_CLAIM_INTERVAL = 8553600; // 99 days in seconds

    // Liquidity pool constants
    /// @notice Percentage of contributions allocated to liquidity pool (3%)
    uint256 public constant LP_CONTRIBUTION_PERCENTAGE = 3;

    /// @notice The fee tier for the Uniswap V3 pool (1%)
    uint24 public constant LP_FEE = 10000;

    /// @notice The minimum tick value for Uniswap V3 pool at 1%
    int24 public constant LP_MIN_TICK = -887200;

    /// @notice The maximum tick value for Uniswap V3 pool at 1%
    int24 public constant LP_MAX_TICK = 887200;

    /// @notice Maximum allowed slippage for adding liquidity in basis points: 99 BPS (0.99%)
    uint256 public constant MAX_ADD_LP_SLIPPAGE_BPS = 99;

    /// @notice Maximum allowed slippage for swaps in basis points: 132 BPS (1.32%)
    uint256 public constant MAX_SWAP_SLIPPAGE_BPS = 132;

    // Bonus-related constants
    /// @notice Percentage of contributions allocated to top contributors (3%)
    uint256 public constant TOP_CONTRIBUTOR_BONUS_PERCENTAGE = 3;

    /// @notice Cycle number when streak bonus starts
    uint256 public constant STREAK_BONUS_COUNT_START = 4;

    /// @notice Streak bonus maximum percentage (33%)
    uint256 public constant STREAK_BONUS_MAX_PERCENTAGE = 33;

    /// @notice Precomputed value for streak bonus calculation: (STREAK_BONUS_MAX_PERCENTAGE + 1) * PRECISION_FACTOR_1E6 / 100
    uint256 public constant STREAK_BONUS_MAX_PLUS_ONE_SCALED = 340000; // (33 + 1) * 1e6 / 100 = 340000

    /// @notice Percentage of referrer's bonus given to the referred user (33%)
    uint256 public constant REFERRAL_BONUS_FOR_REFERRED_PERCENTAGE = 33;

    /// @notice Maximum multiplier for referrer's skin in the game cap (10x)
    uint256 public constant REFERRAL_SKIN_IN_THE_GAME_CAP_MULTIPLIER = 10;

    // Pump-related constants
    /// @notice Interval between pump actions: 3300 seconds (55 minutes)
    uint256 public constant PUMP_INTERVAL = (ULTI_NUMBER * 100 seconds);

    /// @notice Numerator for pump factor calculation
    uint256 public constant PUMP_FACTOR_NUMERATOR = 419061;

    /// @notice Denominator for pump factor calculation
    uint256 public constant PUMP_FACTOR_DENOMINATOR = 1e10;

    /// @notice Minimum number of pumps (11) required to be classified as an active pumper
    uint256 public constant MIN_PUMPS_FOR_ACTIVE_PUMPERS = 11;

    /// @notice Maximum number of pumps allowed per user per cycle (33)
    uint256 public constant MAX_PUMPS_FOR_ACTIVE_PUMPERS = 33;

    /// @notice Percentage bonus for active pumpers (3% of the top contributor bonus)
    uint256 public constant ACTIVE_PUMPERS_BONUS_PERCENTAGE = 3;

    // Utility constants
    /// @notice Precision factor used in various calculations
    uint256 public constant PRECISION_FACTOR_1E6 = 1e6;

    // ===============================================
    // Structs
    // ===============================================

    /// @notice Represents a top contributor's data for a given cycle
    /// @dev Used to track and rank contributors based on their contributions and pump activity
    struct TopContributor {
        /// @notice Address of the contributor
        address contributorAddress;
        /// @notice Amount of input token deposited by the contributor
        uint256 inputTokenDeposited;
        /// @notice Amount of input token referred by the contributor
        uint256 inputTokenReferred;
        /// @notice Amount of ULTI allocated for the contributor
        uint256 ultiAllocated;
        /// @notice Discounted contribution value used for ranking
        uint256 discountedContribution;
        /// @notice Number of pump actions performed by the contributor
        uint16 pumpCount;
    }
}

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

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"address","name":"uniswapRouterAddress","type":"address"},{"internalType":"address","name":"uniswapFactoryAddress","type":"address"},{"internalType":"address","name":"nonfungiblePositionManagerAddress","type":"address"},{"internalType":"address","name":"_inputTokenAddress","type":"address"},{"internalType":"address","name":"_wrappedNativeTokenAddress","type":"address"},{"internalType":"uint256","name":"_initialRatio","type":"uint256"},{"internalType":"uint256","name":"_minimumDepositAmount","type":"uint256"},{"internalType":"uint16","name":"_minimumTwapObservations","type":"uint16"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ClaimAllBonusesCooldownActive","type":"error"},{"inputs":[],"name":"ClaimAllBonusesEmpty","type":"error"},{"inputs":[],"name":"ClaimUltiCooldownActive","type":"error"},{"inputs":[],"name":"ClaimUltiEmpty","type":"error"},{"inputs":[],"name":"DepositCannotReferSelf","type":"error"},{"inputs":[],"name":"DepositCircularReferral","type":"error"},{"inputs":[],"name":"DepositCooldownActive","type":"error"},{"inputs":[],"name":"DepositExpired","type":"error"},{"inputs":[],"name":"DepositInsufficientAmount","type":"error"},{"inputs":[],"name":"DepositInsufficientUltiAllocation","type":"error"},{"inputs":[],"name":"DepositLiquidityInsufficientEthAmount","type":"error"},{"inputs":[],"name":"DepositLiquidityInsufficientUltiAmount","type":"error"},{"inputs":[],"name":"DepositNativeNotSupported","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"LiquidityPoolAlreadyExists","type":"error"},{"inputs":[],"name":"LiquidityPositionAlreadyExists","type":"error"},{"inputs":[],"name":"LiquidityPositionNotInitialized","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"PumpCooldownActive","type":"error"},{"inputs":[],"name":"PumpExpired","type":"error"},{"inputs":[],"name":"PumpInsufficientInputTokenAmount","type":"error"},{"inputs":[],"name":"PumpInsufficientMinimumUltiAmount","type":"error"},{"inputs":[],"name":"PumpInsufficientUltiOutput","type":"error"},{"inputs":[],"name":"PumpMaxPumpsReached","type":"error"},{"inputs":[],"name":"PumpOnlyForTopContributors","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint8","name":"dayInCycle","type":"uint8"}],"name":"SnipingProctectionInvalidDayInCycle","type":"error"},{"inputs":[],"name":"TWAPCalculationFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"cycle","type":"uint32"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"ultiAmount","type":"uint256"}],"name":"AllBonusesClaimed","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":"uint32","name":"cycle","type":"uint32"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Claimed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"cycle","type":"uint32"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"referrer","type":"address"},{"indexed":false,"internalType":"uint256","name":"inputTokenDeposited","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"inputTokenForLP","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ultiForLP","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ultiForUser","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"streakBonus","type":"uint256"},{"indexed":false,"internalType":"uint32","name":"streakCount","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"referrerBonus","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"referredBonus","type":"uint256"},{"indexed":false,"internalType":"bool","name":"autoClaimed","type":"bool"},{"indexed":false,"internalType":"uint256","name":"cycleContribution","type":"uint256"}],"name":"Deposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"founderGiveaway","type":"uint256"},{"indexed":false,"internalType":"address","name":"lpAddress","type":"address"}],"name":"Launched","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"cycle","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"inputTokenEarned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ultiBurned","type":"uint256"}],"name":"LiquidityFeesProcessed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"cycle","type":"uint32"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"inputTokenToSwap","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"ultiBurned","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"pumpCount","type":"uint16"},{"indexed":false,"internalType":"uint256","name":"twap","type":"uint256"}],"name":"Pumped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"cycle","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"ultiAmount","type":"uint256"}],"name":"TopContributorBonusesDistributed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint32","name":"cycle","type":"uint32"},{"indexed":true,"internalType":"address","name":"contributorAddress","type":"address"},{"indexed":true,"internalType":"address","name":"removedContributorAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"contribution","type":"uint256"}],"name":"TopContributorsUpdated","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"},{"stateMutability":"payable","type":"fallback"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"accumulatedReferralBonuses","outputs":[{"internalType":"uint256","name":"referralBonuses","type":"uint256"}],"stateMutability":"view","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":"value","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":[],"name":"claimAllBonuses","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"claimUlti","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"claimableBonuses","outputs":[{"internalType":"uint256","name":"bonuses","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"claimableUlti","outputs":[{"internalType":"uint256","name":"allocatedAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"inputTokenAmount","type":"uint256"},{"internalType":"address","name":"referrer","type":"address"},{"internalType":"uint256","name":"minUltiToAllocate","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bool","name":"autoClaim","type":"bool"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"referrer","type":"address"},{"internalType":"uint256","name":"minUltiToAllocate","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"bool","name":"autoClaim","type":"bool"}],"name":"depositNative","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"discountedContributions","outputs":[{"internalType":"uint256","name":"discountedContribution","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"getActivePumpers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentCycle","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentDayInCycle","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLiquidityAmounts","outputs":[{"internalType":"uint256","name":"inputTokenAmountInPosition","type":"uint256"},{"internalType":"uint256","name":"ultiAmountInPosition","type":"uint256"},{"internalType":"uint256","name":"inputTokenAmountInPool","type":"uint256"},{"internalType":"uint256","name":"ultiAmountInPool","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"getPumpers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"getReferralBonusPercentage","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint8","name":"dayInCycle","type":"uint8"}],"name":"getSnipingProtectionFactor","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getSpotPrice","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTWAP","outputs":[{"internalType":"uint256","name":"currentTwap","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"getTopContributors","outputs":[{"components":[{"internalType":"address","name":"contributorAddress","type":"address"},{"internalType":"uint256","name":"inputTokenDeposited","type":"uint256"},{"internalType":"uint256","name":"inputTokenReferred","type":"uint256"},{"internalType":"uint256","name":"ultiAllocated","type":"uint256"},{"internalType":"uint256","name":"discountedContribution","type":"uint256"},{"internalType":"uint16","name":"pumpCount","type":"uint16"}],"internalType":"struct ULTIShared.TopContributor[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"initialRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"inputTokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"isTopContributor","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"isTopContributorsBonusAllocated","outputs":[{"internalType":"bool","name":"isTopContributorsBonusAllocated","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isUltiToken0","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"founderGiveaway","type":"uint256"}],"name":"launch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"launchTimestamp","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidityPool","outputs":[{"internalType":"contract IUniswapV3Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidityPositionTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"minContributorAddress","outputs":[{"internalType":"address","name":"minContributorAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"minDiscountedContribution","outputs":[{"internalType":"uint256","name":"minDiscountedContribution","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minimumDepositAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minimumTwapObservations","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"nextAllBonusesClaimTimestamp","outputs":[{"internalType":"uint256","name":"nextAllBonusesClaimTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"nextDepositOrClaimTimestamp","outputs":[{"internalType":"uint256","name":"nextDepositOrClaimTimestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextPumpTimestamp","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nonfungiblePositionManager","outputs":[{"internalType":"contract INonfungiblePositionManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"maxInputTokenPerUlti","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"pump","outputs":[{"internalType":"uint256","name":"inputTokenToSwap","type":"uint256"},{"internalType":"uint256","name":"ultiToBurn","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"pumpCounts","outputs":[{"internalType":"uint16","name":"pumpCount","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"referrers","outputs":[{"internalType":"address","name":"referrer","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"streakCounts","outputs":[{"internalType":"uint32","name":"streakCount","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"}],"name":"topContributorsBonuses","outputs":[{"internalType":"uint256","name":"topContributorsBonuses","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"totalInputTokenDeposited","outputs":[{"internalType":"uint256","name":"inputTokenDeposited","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"totalInputTokenReferred","outputs":[{"internalType":"uint256","name":"inputTokenReferred","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"cycle","type":"uint32"},{"internalType":"address","name":"user","type":"address"}],"name":"totalUltiAllocated","outputs":[{"internalType":"uint256","name":"ultiAllocated","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"totalUltiAllocatedEver","outputs":[{"internalType":"uint256","name":"totalUltiAllocatedEver","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","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":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uniswapFactory","outputs":[{"internalType":"contract IUniswapV3Factory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"uniswapRouter","outputs":[{"internalType":"contract ISwapRouter","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"wrappedNativeTokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]

6101a080604052346105d657615e20803803809161001d82856105db565b83398101610140828203126105d65781516001600160401b0381116105d657816100489184016105fe565b602083015190916001600160401b0382116105d6576100689184016105fe565b906100756040840161066d565b926100826060820161066d565b9261008f6080830161066d565b61009b60a0840161066d565b906100a860c0850161066d565b9560e0850151936101206101008701519601519661ffff881688036105d6578051906001600160401b0382116104d35760035490600182811c921680156105cc575b60208310146104b35781601f84931161055c575b50602090601f83116001146104f4576000926104e9575b50508160011b916000199060031b1c1916176003555b8051906001600160401b0382116104d35760045490600182811c921680156104c9575b60208310146104b35781601f849311610443575b50602090601f83116001146103db576000926103d0575b50508160011b916000199060031b1c1916176004555b33156103ba5760058054336001600160a01b03198216811790925561022e9991906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3600160065560018060a01b031660a05260018060a01b031660805260018060a01b0316948560c0528160e0526101005260018060a01b031630106101205261014052610160526101805230610681565b60a051610244906001600160a01b031630610681565b60e05160c051610260916001600160a01b03918216911661071a565b60e05160a05161027c916001600160a01b03918216911661071a565b6040516155e1908161083f8239608051818181611e160152611f7e015260a051818181610fe3015261266d015260c0518181816106ff01528181611291015281816115b3015281816116150152818161228a0152612f27015260e05181818161049e01528181610e5a0152818161170e01528181611eda0152818161281701528181612d69015281816139e10152613b9f01526101005181818161047901528181611e8501526139bd01526101205181818161064501528181610cfa015281816112c9015281816116cd0152818161202d015281816126320152612e6d01526101405181818161059e0152818161149a0152818161205501528181612135015281816123f401528181612dc4015261410f0152610160518181816104c701528181612ce701526134f30152610180518181816120fc01526127630152f35b631e4fbdf760e01b600052600060045260246000fd5b015190503880610179565b600460009081528281209350601f198516905b81811061042b5750908460019594939210610412575b505050811b0160045561018f565b015160001960f88460031b161c19169055388080610404565b929360206001819287860151815501950193016103ee565b60046000529091507f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b601f840160051c810191602085106104a9575b90601f859493920160051c01905b81811061049a5750610162565b6000815584935060010161048d565b909150819061047f565b634e487b7160e01b600052602260045260246000fd5b91607f169161014e565b634e487b7160e01b600052604160045260246000fd5b015190503880610115565b600360009081528281209350601f198516905b818110610544575090846001959493921061052b575b505050811b0160035561012b565b015160001960f88460031b161c1916905538808061051d565b92936020600181928786015181550195019301610507565b60036000529091507fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b601f840160051c810191602085106105c2575b90601f859493920160051c01905b8181106105b357506100fe565b600081558493506001016105a6565b9091508190610598565b91607f16916100ea565b600080fd5b601f909101601f19168101906001600160401b038211908210176104d357604052565b81601f820112156105d6578051906001600160401b0382116104d35760405192610632601f8401601f1916602001856105db565b828452602083830101116105d65760005b82811061065857505060206000918301015290565b80602080928401015182828701015201610643565b51906001600160a01b03821682036105d657565b6001600160a01b0316908115610704576001600160a01b03169081156106ee57806000526001602052604060002082600052602052604060002060001990557f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560206040516000198152a3565b634a1406b160e11b600052600060045260246000fd5b63e602df0560e01b600052600060045260246000fd5b60405190602060008184019463095ea7b360e01b865260018060a01b03169485602486015281196044860152604485526107556064866105db565b84519082855af16000513d826107b2575b50501561077257505050565b6107ab6107b0936040519063095ea7b360e01b6020830152602482015260006044820152604481526107a56064826105db565b826107d7565b6107d7565b565b9091506107cf57506001600160a01b0381163b15155b3880610766565b6001146107c8565b906000602091828151910182855af115610832576000513d61082957506001600160a01b0381163b155b6108085750565b635274afe760e01b60009081526001600160a01b0391909116600452602490fd5b60011415610801565b6040513d6000823e3d90fdfe6080806040526004361015610028575b5036156100205761001e6139b3565b005b61001e6139b3565b600090813560e01c9081621cf236146135ee5750806305ecd003146135d357806306fdde0314613516578063080c279a146134db578063095ea7b3146134315780631296afb61461340057806318160ddd146133e2578063218acfd2146133ad5780632299e86214612ca657806323b872dd14612bc657806324ac0a9314612b8d5780632554447f14612b545780632959539014612b16578063313ce56714612afa5780633725597714612aa857806337bdb73014612a5857806339fb339e1461294e5780633ad863b5146128fe5780633e29da71146128c957806341161da11461289057806346ef64c41461286a57806348c56b971461284657806349401a3c146128015780634a3b68cc146127c057806359d7fff514612787578063647d153d1461274857806365cf7c9b14612721578063665a11ca146126f857806370a08231146126c0578063715018a61461269c578063735de9f71461265757806380ad62a21461261a57806382969bc3146124d357806385b12c7c14611eb45780638b99610014611e6f5780638bbcc07b14611e455780638bdb2afa14611e005780638da5cb5b14611dd757806391eb4bd614611db957806393b8898f14611d8057806395d89b4114611c7757806397d088f814611a62578063a7e0c60414611a0f578063a9059cbb146119dd578063b30d0aa2146115e2578063b44a27221461159d578063be26ed7f14611582578063c9c44de214611549578063caa18928146114f6578063d1ea4054146114bd578063d4611ec214611482578063dbd5ac6214610d84578063dc76fabc14610ca7578063dd62ed3e14610c52578063e0770b3e1461043a578063e4ec10d6146103d5578063f20eeb551461037e578063f2fde38b146102f55763f628e49f0361000f57346102f25760203660031901126102f25760ff604060209263ffffffff6102de613665565b168152601a84522054166040519015158152f35b80fd5b50346102f25760203660031901126102f25761030f613704565b6103176144c8565b6001600160a01b0316801561036a57600580546001600160a01b0319811683179091556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b631e4fbdf760e01b82526004829052602482fd5b50346102f25760403660031901126102f257604061039a613665565b9163ffffffff6103a861371a565b93168152601c602052209060018060a01b0316600052602052602061ffff60406000205416604051908152f35b50346102f25760403660031901126102f25761043060209160406103f7613665565b9163ffffffff61040561371a565b9316815260168552206001600160a01b03909116600090815260019091016020526040902054151590565b6040519015158152f35b5060803660031901126102f25761044f613704565b604435906064358015158103610c4e57610467614141565b60085415610c3f576001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811693907f000000000000000000000000000000000000000000000000000000000000000016849003610c30577f00000000000000000000000000000000000000000000000000000000000000003410610c21576001600160a01b03831693338514610c1257848652600d60205260408620546001600160a01b03163314610c0357814211610bf457338652600c60205260408620544210610be6578590819380610bd1575b610bbd575b803b15610bb9578160049160405192838092630d0e30db60e41b825234905af18015610bae57610b95575b5050610578613a54565b916001600160401b0360095416620151808101809111610b8157421015610b55576105c37f000000000000000000000000000000000000000000000000000000000000000034613895565b935b6024358510610b46576003340234810460031434151715610b3257606490049384670de0b6b3a764000002670de0b6b3a764000081048603610b1e579061060b916137b8565b928415610b0f578315610afd5761062284306142cf565b61271061062e8561387d565b049061271061063c8761387d565b049189600854937f00000000000000000000000000000000000000000000000000000000000000009081600014610af65788935b8215610aef578a925b8015610ae85781945b5015610ae05750925b6040519561069887613730565b86526020860190815260408601918252606086019283526080860193845260a086019485526040519563219f5d1760e01b87525160048701525160248601525160448501525160648401525160848301525160a482015260608160c4818b60018060a01b037f0000000000000000000000000000000000000000000000000000000000000000165af1610aa3575b50338752600a6020526040872061073e86825461379e565b905561074861396f565b94610755868234336149cf565b90610760818461379e565b92338b52600f60205260408b2061077885825461379e565b9055338b52600d60205260408b20548b958695916001600160a01b031615610a9d5750338c52600d60205260408c20546001600160a01b03169a5b338d52600d60205260408d20546001600160a01b03161580610a94575b610a71575b506001600160a01b038b169a8b6108cd575b506107f49034338c614c55565b966201518042018042116108b957338d52600c60205260408d2055338c52600e60205260408c20541561089a575b9063ffffffff93929160405199348b5260208b015260408a0152606089015260808801521660a086015260c085015260e084015215156101008301526101208201527f907a4953eafd8d897ea997ad9bfa21da6e8cfbebaa112f8644d5d0820168f94d61014063ffffffff33941692a4600160065580f35b6282848042018042116108b957338d52600e60205260408d2055610822565b634e487b7160e01b8d52601160045260248dfd5b9091929394506305f5e1006108f063ffffffff6108e98d61433e565b1684613895565b048b8d52600f60205260408d2054600a810290808204600a1490151715610a5d578d9695949392918d91828952601060205260408920548111600014610a555782895260106020526040892054610946916137ab565b905b81811115610a4d5750915b8c8398841593841561096a575b50505050506107e7565b85969b5080829694959652600e602052604082205415610a12575b81816040926109c1979452600b6020528282206109a387825461379e565b905581526010602052206109b884825461379e565b90553491614b3f565b506021820291820460211417156109fe5760646107f4910495338d52600b60205260408d206109f188825461379e565b90559038808c8f8f610960565b634e487b7160e01b8c52601160045260248cfd5b50505050628284804201804211610a39578d8f52600e60205260408f2055828c8f8f610985565b634e487b7160e01b8f52601160045260248ffd5b905091610953565b508790610948565b634e487b7160e01b8e52601160045260248efd5b338d52600d60205260408d2080546001600160a01b0319169091179055386107d5565b508015156107d0565b9a6107b3565b6060813d606011610ad8575b81610abc6060938361377d565b81010312610ad457610acd906138ca565b5038610726565b8780fd5b3d9150610aaf565b90509261068b565b8294610682565b8992610679565b8993610670565b600162292fd760e11b03198852600488fd5b630531ac1760e11b8852600488fd5b634e487b7160e01b89526011600452602489fd5b634e487b7160e01b88526011600452602488fd5b63b9c5901b60e01b8752600487fd5b34670de0b6b3a764000002670de0b6b3a764000081043403610b815783610b7b916137b8565b936105c5565b634e487b7160e01b87526011600452602487fd5b81610b9f9161377d565b610baa57843861056e565b8480fd5b6040513d84823e3d90fd5b5080fd5b925050610bc8614163565b84600192610543565b50338252600a6020526040822054151561053e565b622ddbdd60e51b8652600486fd5b6380040f8d60e01b8652600486fd5b633eb1c49160e21b8652600486fd5b635f4ccded60e11b8652600486fd5b631210e84760e01b8552600485fd5b63052dd2e760e41b8552600485fd5b63b806e7fd60e01b8452600484fd5b8380fd5b50346102f25760403660031901126102f2576040610c6e613704565b91610c7761371a565b9260018060a01b031681526001602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102f257806003193601126102f257600754604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115610bae5760209291610d4f575b506001600160a01b03167f000000000000000000000000000000000000000000000000000000000000000015610d3857610d2b81610d3092614f7d565b614fdd565b604051908152f35b80610d45610d4a92614ebe565b614ed2565b610d30565b610d71915060e03d60e011610d7d575b610d69818361377d565b8101906138ed565b50505050505038610cee565b503d610d5f565b50346102f25760403660031901126102f257602435610da1614141565b6008541561147357804211611464576001600160401b0360095460401c16421061145557610dcd61396f565b63ffffffff8116908184526016602052610dfb60408520339060019160005201602052604060002054151590565b1561144657818452601c6020526040842060018060a01b033316600052602052602161ffff604060002054161015611437576001821180611412575b6111fd575b50610e45613a54565b6040516370a0823160e01b81523060048201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169290602081602481875afa9081156111725786916111cb575b50620664f5810290808204620664f514901517156111b7576402540be400900493670de0b6b3a76400008502851590868104670de0b6b3a764000014821715610b3257610eea600435826137b8565b916111a85781156111995784610eff916137b8565b61268c81029080820461268c1490151715610b32576127109004808211156111915750905b6040519461010086018681106001600160401b0382111761117d5760409081529086523060208088019182526127108884019081523360608a0190815260808a0195865260a08a018b815260c08b0188815260e08c018e8152965163414bf38960e01b81529b516001600160a01b0390811660048e01529551861660248d0152925162ffffff1660448c01529051841660648b0152945160848a0152935160a4890152925160c48801529051811660e487015285906101049082908a907f0000000000000000000000000000000000000000000000000000000000000000165af1938415611172578694611139575b50831061112a57611024833361494e565b808552601b6020526110393360408720615426565b50808552601c6020526040852060018060a01b0333166000526020526040600020805461ffff600181831601169061ffff1916179055610ce4420180421161111457604095869167ffffffffffffffff60401b60095491841b169067ffffffffffffffff60401b191617600955828152601c6020522060018060a01b03331660005260205261ffff856000205416918551928584528460208501528684015260608301527fef77962ab378257316a9b3549cbb270fce18ce65180332939e21bda117ed149260803393a3600160065582519182526020820152f35b634e487b7160e01b600052601160045260246000fd5b633aee2ed960e21b8552600485fd5b9093506020813d60201161116a575b816111556020938361377d565b8101031261116557519238611013565b600080fd5b3d9150611148565b6040513d88823e3d90fd5b634e487b7160e01b89526041600452602489fd5b905090610f24565b638abef0a560e01b8852600488fd5b633ff4ef4360e01b8852600488fd5b634e487b7160e01b86526011600452602486fd5b90506020813d6020116111f5575b816111e66020938361377d565b81010312611165575138610e9b565b3d91506111d9565b61120961120e9161399a565b6147ad565b60085460405190608082018281106001600160401b038211176113fe57604090815290825230602083019081526001600160801b0383830181815260608501828152845163fc6f786560e01b81529551600487015292516001600160a01b03908116602487015290518216604486015291511660648401528290608490829088907f0000000000000000000000000000000000000000000000000000000000000000165af180156113f357849185916113ba575b50849085927f00000000000000000000000000000000000000000000000000000000000000006000146113625780611339575b5060008051602061558c8339815191529181604092611331575b505b63ffffffff61131e61396f565b169382519182526020820152a238610e3c565b90503861130f565b6040919350918261135960008051602061558c833981519152943061494e565b939150916112f5565b9080611391575b5060008051602061558c8339815191529181604092611389575b50611311565b905038611383565b604091935091826113b160008051602061558c833981519152943061494e565b93915091611369565b9150506040813d6040116113eb575b816113d66040938361377d565b81010312610c4e5760208151910151386112c2565b3d91506113c9565b6040513d86823e3d90fd5b634e487b7160e01b86526041600452602486fd5b5063ffffffff6114218261399a565b168452601a60205260ff60408520541615610e37565b631dcf30bf60e11b8452600484fd5b633800201960e01b8452600484fd5b63df74c15f60e01b8252600482fd5b637ea1c91b60e11b8252600482fd5b63b806e7fd60e01b8252600482fd5b50346102f257806003193601126102f25760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b50346102f25760203660031901126102f2576020906040906001600160a01b036114e5613704565b168152600e83522054604051908152f35b50346102f25760403660031901126102f2576040611512613665565b9163ffffffff61152061371a565b931681526012602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102f25760203660031901126102f2576004359060ff821682036102f257602061157483614613565b63ffffffff60405191168152f35b50346102f257806003193601126102f257602061157461396f565b50346102f257806003193601126102f2576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102f257806003193601126102f25760085460405163133f757160e31b8152600481019190915290610180826024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9182156119d057819261190d575b50600754604051633850c7bd60e01b81526001600160a01b039091169260e082600481875afa9182156119025783926118db575b50620d89a0926118b257640100eed0b4925060009173ff120d460d67f1db5b71087bd404babb342b5987906001600160a01b03811684868211611807575050506116cb9293614e4a565b7f000000000000000000000000000000000000000000000000000000000000000015611801575b6040516370a0823160e01b8152600481018490526020816024817f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165afa9081156117c3576000916117cf575b50604051936370a0823160e01b85526004850152602084602481305afa9182156117c35760009261178e575b60809450604051938452602084015260408301526060820152f35b91506020843d6020116117bb575b816117a96020938361377d565b81010312611165576080935191611773565b3d915061179c565b6040513d6000823e3d90fd5b90506020813d6020116117f9575b816117ea6020938361377d565b81010312611165575138611747565b3d91506117dd565b906116f2565b90929194828410600014611877575050936001600160801b039161183084869761186497614e4a565b959190829082906001600160a01b0382161161186a575b506001600160a01b039261185c929150614e31565b169116614f7d565b906116cb565b9250905061185c38611847565b509461186494506001600160801b03925081816001600160a01b038083169082161161186a57506001600160a01b039261185c929150614e31565b60405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606490fd5b6118f591925060e03d60e011610d7d57610d69818361377d565b5050505050509038611681565b6040513d85823e3d90fd5b909150610180813d82116119c8575b8161192a610180938361377d565b81010312610bb95780516bffffffffffffffffffffffff811603610bb957611954602082016138a8565b50611961604082016138a8565b5061196e606082016138a8565b50608081015162ffffff811603610bb95761198b60a082016138bc565b5061199860c082016138bc565b506119c06101606119ab60e084016138ca565b926119b961014082016138ca565b50016138ca565b50903861164d565b3d915061191c565b50604051903d90823e3d90fd5b50346102f25760403660031901126102f257611a046119fa613704565b602435903361420a565b602060405160018152f35b50346102f25760403660031901126102f2576040611a2b613665565b9163ffffffff611a3961371a565b931681526013602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102f25760203660031901126102f25763ffffffff611a81613665565b1680825260166020526040822090815490611a9b8261381f565b90611aa9604051928361377d565b828252601f19611ab88461381f565b01855b818110611c3c575050845b60ff811684811015611bb75790611bac82611ae4611bb29489614e00565b868b5260116020526040808c2060009060018060a01b0385168252602052205490878c5260126020528b604080822060009060018060a01b03871682526020522054898252601360205261ffff6040808080862060009060018060a01b038b1682526020522054948d8152601c6020522060009060018060a01b03891682526020522054169360405195611b7787613730565b6001600160a01b03168652602086015260408501526060840152608083015260a0820152611ba58288613869565b5285613869565b50614602565b611ac6565b8387604051918291602083016020845282518091526020604085019301915b818110611be4575050500390f35b91935091602060c060019261ffff60a088518680831b038151168452858101518685015260408101516040850152606081015160608501526080810151608085015201511660a0820152019401910191849392611bd6565b602090604051611c4b81613730565b88815288838201528860408201528860608201528860808201528860a082015282828701015201611abb565b50346102f257806003193601126102f2576040519080600454908160011c91600181168015611d76575b602084108114611d6257838652908115611d3b5750600114611cde575b611cda84611cce8186038261377d565b604051918291826136bb565b0390f35b600481527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b939250905b808210611d2157509091508101602001611cce82611cbe565b919260018160209254838588010152019101909291611d08565b60ff191660208087019190915292151560051b85019092019250611cce9150839050611cbe565b634e487b7160e01b83526022600452602483fd5b92607f1692611ca1565b50346102f25760203660031901126102f2576020906040906001600160a01b03611da8613704565b168152600f83522054604051908152f35b50346102f257806003193601126102f2576020600854604051908152f35b50346102f257806003193601126102f2576005546040516001600160a01b039091168152602090f35b50346102f257806003193601126102f2576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102f257806003193601126102f25760206001600160401b0360095460401c16604051908152f35b50346102f257806003193601126102f2576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102f25760203660031901126102f257600435611ed16144c8565b6008546124c4577f0000000000000000000000000000000000000000000000000000000000000000611f0e8230336001600160a01b038516614568565b600954610ce442018042116124b0576fffffffffffffffffffffffffffffffff19909116426001600160401b031617604091821b67ffffffffffffffff60401b161760095551630b4c774160e11b81523060048201526001600160a01b03828116602483015261271060448301527f0000000000000000000000000000000000000000000000000000000000000000169060208180606481010381855afa9081156124a557859161246b575b506001600160a01b031661245c5760405163a167129560e01b81523060048201526001600160a01b03831660248201526127106044820152906020908290606490829088905af19081156113f3578491612422575b50600780546001600160a01b0319166001600160a01b0383161790557f00000000000000000000000000000000000000000000000000000000000000009081156123e7577f000000000000000000000000000000000000000000000000000000000000000080156123d3576001600160a01b039061209290600160c01b04614cde565b16905b6001600160a01b031690813b156123cf5760405163f637731d60e01b81526001600160a01b039091166004820152858160248183865af18015611172576123bb575b508085913b15610bb9578180916024604051809481936332148f6760e01b835261ffff7f00000000000000000000000000000000000000000000000000000000000000001660048401525af18015610bae576123a6575b505061215a7f000000000000000000000000000000000000000000000000000000000000000084613895565b9061216582306142cf565b80156123a05730925b811561239857915b81156123915780915b1561238c5750835b6040519361016085018581106001600160401b038211176123785760409081526001600160a01b03918216865293811660208601908152612710868601908152620d899f1960608801908152620d89a06080808a0191825260a08a0197885260c08a0196875260e08a018c81526101008b018d8152306101208d01908152426101408e019081529b51634418b22b60e11b81529c51891660048e01529651881660248d0152945162ffffff1660448c01529251600290810b60648c0152915190910b60848a0152955160a4890152935160c4880152925160e4870152915161010486015290518116610124850152915161014484015290829061016490829087907f0000000000000000000000000000000000000000000000000000000000000000165af190811561190257839161230d575b507f4bf60f71216c4f27fc663266fdd59a59dcba5c15a9c784b6996f75ad305099d1916040916008556122eb6144c8565b6122f36144f1565b60075482519182526001600160a01b03166020820152a180f35b90506080813d608011612370575b816123286080938361377d565b8101031261236c577f4bf60f71216c4f27fc663266fdd59a59dcba5c15a9c784b6996f75ad305099d1918161236360206040945192016138ca565b509150916122ba565b8280fd5b3d915061231b565b634e487b7160e01b88526041600452602488fd5b612187565b849161217f565b503091612176565b8261216e565b816123b09161377d565b610c4e57833861212e565b856123c89196929661377d565b93386120d7565b8580fd5b634e487b7160e01b86526012600452602486fd5b6001600160a01b0361241b7f000000000000000000000000000000000000000000000000000000000000000060c01b614cde565b1690612095565b90506020813d602011612454575b8161243d6020938361377d565b81010312610c4e5761244e906138a8565b3861200f565b3d9150612430565b631da01aeb60e11b8452600484fd5b90506020813d60201161249d575b816124866020938361377d565b81010312610baa57612497906138a8565b38611fba565b3d9150612479565b6040513d87823e3d90fd5b634e487b7160e01b85526011600452602485fd5b6332ecf57560e01b8252600482fd5b50346102f25760203660031901126102f2576124ed613665565b63ffffffff81168252601b60205260408220805491908390815b63ffffffff8116858110156125635761252361253b9184614cc6565b905460039190911b1c6001600160a01b031685614535565b61254e575b61254990613808565b612507565b9461255b61254991613808565b959050612540565b5050929363ffffffff16916125778361381f565b92612585604051948561377d565b808452612594601f199161381f565b01366020850137815b63ffffffff81168681101561260c576125b69086614cc6565b905460039190911b1c6001600160a01b03166125d28184614535565b6125e6575b506125e190613808565b61259d565b83612605916125ff63ffffffff6125e195971688613869565b52613808565b92906125d7565b60405180611cda8782613678565b50346102f257806003193601126102f25760206040517f000000000000000000000000000000000000000000000000000000000000000015158152f35b50346102f257806003193601126102f2576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102f257806003193601126102f2576126b56144c8565b6126bd6144f1565b80f35b50346102f25760203660031901126102f2576020906040906001600160a01b036126e8613704565b1681528083522054604051908152f35b50346102f257806003193601126102f2576007546040516001600160a01b039091168152602090f35b50346102f257806003193601126102f25760206001600160401b0360095416604051908152f35b50346102f257806003193601126102f257602060405161ffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b50346102f25760203660031901126102f2576020906040906001600160a01b036127af613704565b168152601083522054604051908152f35b50346102f25760203660031901126102f2576020906001600160a01b036127e5613704565b168152600d8252604060018060a01b0391205416604051908152f35b50346102f257806003193601126102f2576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102f25760203660031901126102f2576020611574612865613665565b61433e565b50346102f257806003193601126102f25760206128856137d8565b60ff60405191168152f35b50346102f25760203660031901126102f2576020906040906001600160a01b036128b8613704565b168152600b83522054604051908152f35b50346102f25760203660031901126102f257604060209163ffffffff6128ed613665565b168152601883522054604051908152f35b50346102f25760403660031901126102f257604060209161291d613665565b63ffffffff61292a61371a565b91168252601184528282206001600160a01b03909116825283522054604051908152f35b50346102f257806003193601126102f257612967614141565b60085415612a4957338152600e60205260408120544210612a3a57338152600b60205260408120548015612a2b57338252600b60205281604081205533825260106020528160408120556129bb81336142cf565b628284804201804211612a1757338352600e602052604083205563ffffffff6129e261396f565b166040519182527f3317998f30c22a741914cbb8b3f65cce45e8817db54aa6509a6ecb004753d05e60203393a3600160065580f35b634e487b7160e01b83526011600452602483fd5b6305950abd60e51b8252600482fd5b6342355f9960e11b8152600490fd5b63b806e7fd60e01b8152600490fd5b50346102f25760403660031901126102f2576040602091612a77613665565b63ffffffff612a8461371a565b91168252601584528282206001600160a01b03909116825283522054604051908152f35b50346102f25760403660031901126102f25763ffffffff6040602092612acc613665565b83612ad561371a565b91168252601485528282206001600160a01b0390911682528452205460405191168152f35b50346102f257806003193601126102f257602060405160128152f35b50346102f25760203660031901126102f25760209063ffffffff612b38613665565b16815260178252604060018060a01b0391205416604051908152f35b50346102f25760203660031901126102f2576020906040906001600160a01b03612b7c613704565b168152600a83522054604051908152f35b50346102f25760203660031901126102f2576020906040906001600160a01b03612bb5613704565b168152600c83522054604051908152f35b50346102f25760603660031901126102f257612be0613704565b612be861371a565b6001600160a01b038216808452600160208181526040808720338852909152852054604435949290918201612c24575b5050611a04935061420a565b848210612c8b578015612c77573315612c63576040868692611a049852600160205281812060018060a01b033316825260205220910390553880612c18565b634a1406b160e11b86526004869052602486fd5b63e602df0560e01b86526004869052602486fd5b6064868684637dc7a0d960e11b835233600452602452604452fd5b50346102f25760a03660031901126102f25760043590612cc461371a565b60643592608435918215158303610c4e57612cdd614141565b60085415610c3f577f0000000000000000000000000000000000000000000000000000000000000000821061339e576001600160a01b0381169233841461338f57838552600d60205260408520546001600160a01b031633146133805785421161337157338552600c602052604085205442106133635784908061334e575b61333e575b612d968330337f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316614568565b612d9e613a54565b916001600160401b0360095416620151808101809111610b815742101561331257612de97f000000000000000000000000000000000000000000000000000000000000000085613895565b945b6044358610610b46576003850285810460031486151715610b3257606490049384670de0b6b3a764000002670de0b6b3a764000081048603610b1e5790612e31916137b8565b958415610b0f578615610afd578798612e4a88306142cf565b612710612e568961387d565b0490612710612e648861387d565b04918a600854937f0000000000000000000000000000000000000000000000000000000000000000908160001461330b578c935b8215613304578b925b80156132fd5781945b50156132f55750925b60405195612ec087613730565b86526020860190815260408601918252606086019283526080860193845260a086019485526040519563219f5d1760e01b87525160048701525160248601525160448501525160648401525160848301525160a482015260608160c4818c60018060a01b037f0000000000000000000000000000000000000000000000000000000000000000165af16132b8575b50338852600a60205260408820612f6682825461379e565b9055612f7061396f565b96612f7d888389336149cf565b929091612f8a838361379e565b338c52600f60205260408c20612fa182825461379e565b9055338c52600d60205260408c20548c978897916001600160a01b0316156132b25750338d52600d60205260408d20546001600160a01b0316905b338e52600d60205260408e20548e906001600160a01b031615806132a9575b613285575b50506001600160a01b0381169c8d908d826130eb575b50505050613026908a338d614c55565b97620151804201804211610a5d5760408e338152600c6020522055338d52600e60205260408d2054156130cc575b9063ffffffff949392916040519a8b5260208b015260408a0152606089015260808801521660a086015260c085015260e084015215156101008301526101208201527f907a4953eafd8d897ea997ad9bfa21da6e8cfbebaa112f8644d5d0820168f94d61014063ffffffff33941692a4600160065580f35b628284804201804211610a5d57338e52600e60205260408e2055613054565b604092939495969798995061311363ffffffff61310c6305f5e1009361433e565b1687613895565b04928152600f6020522054600a810290808204600a1490151715610a39578e8c8f92938f9a99989796959484845260106020526040842054811160001461327d578484526010602052604084205461316a916137ab565b905b818111156132755750935b849a851594851561318d575b9450915050613016565b869798999a9b9c9d50808596979552600e602052604086205415613229575b85816040926131e59852600b6020528282206131c988825461379e565b905581526010602052206131de85825461379e565b9055614b3f565b506021820291820460211417156108b9578c96959493929160406064613026930498338152600b6020522061321b89825461379e565b905590388e8c8f8f81613183565b505092505050628284804201804211613260578f8f928f8f92808689966131e59860409452600e60205283832055915095506131ac565b50634e487b7160e01b8f52601160045260248ffd5b905093613177565b50829061316c565b338152600d6020526040902080546001600160a01b0319169091179055388d613000565b50811515612ffb565b90612fdc565b6060813d6060116132ed575b816132d16060938361377d565b810103126132e9576132e2906138ca565b5038612f4e565b8880fd5b3d91506132c4565b905092612eb3565b8294612eaa565b8d92612ea1565b8a93612e98565b83670de0b6b3a764000002670de0b6b3a764000081048503610b815783613338916137b8565b94612deb565b50613347614163565b6001612d61565b50338552600a60205260408520541515612d5c565b622ddbdd60e51b8552600485fd5b6380040f8d60e01b8552600485fd5b633eb1c49160e21b8552600485fd5b635f4ccded60e11b8552600485fd5b631210e84760e01b8452600484fd5b50346102f25760203660031901126102f257604060209163ffffffff6133d1613665565b168152601983522054604051908152f35b50346102f257806003193601126102f2576020600254604051908152f35b50346102f257806003193601126102f257613419614141565b60085415612a4957613429614163565b600160065580f35b50346102f25760403660031901126102f25761344b613704565b6024359033156134c7576001600160a01b03169182156134b35760408291338152600160205281812085825260205220556040519081527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560203392a3602060405160018152f35b634a1406b160e11b81526004819052602490fd5b63e602df0560e01b83526004839052602483fd5b50346102f257806003193601126102f25760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b50346102f257806003193601126102f2576040519080600354908160011c916001811680156135c9575b602084108114611d6257838652908115611d3b575060011461356c57611cda84611cce8186038261377d565b600381527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b939250905b8082106135af57509091508101602001611cce82611cbe565b919260018160209254838588010152019101909291613596565b92607f1692613540565b50346102f257806003193601126102f2576020610d30613a54565b82346102f25760203660031901126102f25763ffffffff61360d613665565b168152601b602052604081209081548084526020840192825260208220915b81811061364f57611cda856136438187038261377d565b60405191829182613678565b825484526020909301926001928301920161362c565b6004359063ffffffff8216820361116557565b602060408183019282815284518094520192019060005b81811061369c5750505090565b82516001600160a01b031684526020938401939092019160010161368f565b91909160208152825180602083015260005b8181106136ee575060409293506000838284010152601f8019910116010190565b80602080928701015160408286010152016136cd565b600435906001600160a01b038216820361116557565b602435906001600160a01b038216820361116557565b60c081019081106001600160401b0382111761374b57604052565b634e487b7160e01b600052604160045260246000fd5b61042081019081106001600160401b0382111761374b57604052565b90601f801991011681019081106001600160401b0382111761374b57604052565b9190820180921161111457565b9190820391821161111457565b81156137c2570490565b634e487b7160e01b600052601260045260246000fd5b62015180622b81806137f56001600160401b0360095416426137ab565b0604600181018091116111145760ff1690565b63ffffffff1663ffffffff81146111145760010190565b6001600160401b03811161374b5760051b60200190565b8051156138435760200190565b634e487b7160e01b600052603260045260246000fd5b8051600110156138435760400190565b80518210156138435760209160051b010190565b906126ad8202918083046126ad149015171561111457565b8181029291811591840414171561111457565b51906001600160a01b038216820361116557565b51908160020b820361116557565b51906001600160801b038216820361116557565b519061ffff8216820361116557565b908160e091031261116557613901816138a8565b9161390e602083016138bc565b9161391b604082016138de565b91613928606083016138de565b91613935608082016138de565b9160a082015160ff811681036111655760c09092015180151581036111655790565b63ffffffff60019116019063ffffffff821161111457565b61399763ffffffff622b81806139906001600160401b0360095416426137ab565b0416613957565b90565b63ffffffff6000199116019063ffffffff821161111457565b6001600160a01b037f00000000000000000000000000000000000000000000000000000000000000008116907f000000000000000000000000000000000000000000000000000000000000000016819003613a4357803b1561116557600060049160405192838092630d0e30db60e41b825234905af180156117c357613a365750565b6000613a419161377d565b565b63052dd2e760e41b60005260046000fd5b6104416001600160401b0360095416016001600160401b038111611114576001600160401b0316421061410d57604051613a8f60608261377d565b60028152602081016040368237610441613aa883613836565b526000613ab483613859565b5260018060a01b0360075416604051809263883bdbfd60e01b82526024820160206004840152855180915260448301919060005b8181106140ee5750505091818060009403915afa60009181613fdc575b50613b1b576389d9e13d60e01b60005260046000fd5b613b31613b2782613859565b5160060b91613836565b5160060b900390667fffffffffffff198212667fffffffffffff8313176111145763ffffffff613b6082613836565b511660030b9160060b9180156137c257667fffffffffffff19831460001982141661111457820560020b91600081129182613fb2575b5050613f9e575b7f00000000000000000000000000000000000000000000000000000000000000009060020b600080821215613f9857818103915b620d89e883116118b2576001831615613f86576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b169260028116613f6a575b60048116613f4e575b60088116613f32575b60108116613f16575b60208116613efa575b60408116613ede575b60808116613ec2575b6101008116613ea6575b6102008116613e8a575b6104008116613e6e575b6108008116613e52575b6110008116613e36575b6120008116613e1a575b6140008116613dfe575b6180008116613de2575b620100008116613dc6575b620200008116613dab575b620400008116613d90575b6208000016613d77575b8112613d52575b63ffffffff8216613d4957905b60201c60ff91909116016001600160a01b03166001600160801b038111613d1c5780613cf991613895565b906001600160a01b0316301015613d1357613997906151c2565b613997906151ae565b80613d26916150e4565b906001600160a01b0316301015613d405761399790615147565b61399790615133565b50600190613cce565b908015613d63576000190490613cc1565b634e487b7160e01b82526012600452602482fd5b6b048a170391f7dc42444e8fa290920260801c91613cba565b6d2216e584f5fa1ea926041bedfe9890930260801c92613cb0565b926e5d6af8dedb81196699c329225ee6040260801c92613ca5565b926f09aa508b5b7a84e1c677de54f3e99bc90260801c92613c9a565b926f31be135f97d08fd981231505542fcfa60260801c92613c8f565b926f70d869a156d2a1b890bb3df62baf32f70260801c92613c85565b926fa9f746462d870fdf8a65dc1f90e061e50260801c92613c7b565b926fd097f3bdfd2022b8845ad8f792aa58250260801c92613c71565b926fe7159475a2c29b7443b29c7fa6e889d90260801c92613c67565b926ff3392b0822b70005940c7a398e4b70f30260801c92613c5d565b926ff987a7253ac413176f2b074cf7815e540260801c92613c53565b926ffcbe86c7900a88aedcffc83b479aa3a40260801c92613c49565b926ffe5dee046a99a2a811c461f1969c30530260801c92613c3f565b926fff2ea16466c96a3843ec78b326b528610260801c92613c36565b926fff973b41fa98c081472e6896dfb254c00260801c92613c2d565b926fffcb9843d60f6159c9db58835c9266440260801c92613c24565b926fffe5caca7e10e4e61c3624eaa0941cd00260801c92613c1b565b926ffff2e50f5f656932ef12357cf3c7fdcc0260801c92613c12565b926ffff97272373d413259a46990580e213a0260801c92613c09565b6001600160881b03600160801b613bfe565b81613bd1565b627fffff1981146111145760001901613b9d565b63ffffffff919250613fc390613836565b511660060b9081156137c2570760060b15153880613b96565b90913d8082843e613fed818461377d565b8201906040838303126102f25782516001600160401b038111610bb95783019282601f85011215610bb95783516140238161381f565b94614031604051968761377d565b81865260208087019260051b82010190858211610baa57602001915b8183106140d4575050506020810151906001600160401b03821161236c570182601f82011215610bb9578051916020806140868561381f565b614093604051918261377d565b858152019360051b8301019384116102f25750602001905b8282106140bc575050509038613b05565b602080916140c9846138a8565b8152019101906140ab565b82518060060b81036123cf5781526020928301920161404d565b825163ffffffff16845286945060209384019390920191600101613ae8565b7f000000000000000000000000000000000000000000000000000000000000000080156137c257670de0b6b3a76400000490565b600260065414614152576002600655565b633ee5aeb560e01b60005260046000fd5b33600052600c60205260406000205442106141f95733600052600a602052604060002054156141e857336000818152600a602052604081208054919055906141ac9082906142cf565b63ffffffff6141b961396f565b166040519182527fdc8b8058bd26d719cc330a54461930fd9c312dd28447313fd5dc4641513e007460203393a3565b630f4c8e7560e11b60005260046000fd5b630fb9ee4d60e11b60005260046000fd5b6001600160a01b03169081156142b9576001600160a01b03169182156142a35760008281528060205260408120548281106142895791604082827fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef958760209652828652038282205586815280845220818154019055604051908152a3565b916064928463391434e360e21b8452600452602452604452fd5b63ec442f0560e01b600052600060045260246000fd5b634b637e8f60e11b600052600060045260246000fd5b6001600160a01b03169081156142a3576142eb8160025461379e565b6002557fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602060009284845283825260408420818154019055604051908152a3565b9060218110156138435760051b0190565b602163ffffffff8216116144c0576144bb63ffffffff91826144b46040519261436684613761565b6301f78a4084526301d32fcc60208501526301b1753b60408501526301922a0b60608501526301752139608085015263015a310660a085015263014132b260c085015263012a024c60e08501526301147e7c610100850152630100884e61012085015262ee031061014085015262dcd41d61016085015262cce2c061018085015262be180b6101a085015262b05eb86101c085015262a3a30a6101e08501526297d2b2610200850152628cdcb26102208501526282b146610240850152627941cf610260850152627080bb610280850152626861736102a08501526260d8486102c08501526259da646102e085015262535db8610300850152624d58f26103208501526247c36861034085015262429512610360850152623dc67f610380850152623950c26103a085015262352d746103c08501526231569f6103e0850152622dc6c061040085015261399a565b169061432d565b511690565b50622dc6c090565b6005546001600160a01b031633036144dc57565b63118cdaa760e01b6000523360045260246000fd5b600580546001600160a01b031981169091556000906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3565b63ffffffff16600052601c60205260406000209060018060a01b0316600052602052600b61ffff60406000205416101590565b6040516323b872dd60e01b60208083019182526001600160a01b03948516602484015294909316604482015260648082019590955293845292600091906145b060848261377d565b519082855af1156117c3576000513d6145f957506001600160a01b0381163b155b6145d85750565b635274afe760e01b60009081526001600160a01b0391909116600452602490fd5b600114156145d1565b60ff1660ff81146111145760010190565b60ff166001811080156147a3575b61478f576040519061463282613761565b620f423c8252620f423a6020830152620f42376040830152620f42326060830152620f422c6080830152620f422260a0830152620f421360c0830152620f41fd60e0830152620f41dc610100830152620f41ab610120830152620f4162610140830152620f40f4610160830152620f4051610180830152620f3f5e6101a0830152620f3df36101c0830152620f3bd66101e0830152620f38af610200830152620f33fc610220830152620f2cfc610240830152620f228d610260830152620f1307610280830152620efbf06102a0830152620ed9ab6102c0830152620ea6ea6102e0830152620e5c04610300830152620dee11610320830152620d4de6610340830152620c672a610360830152620b201261038083015262095ac16103a08301526206f9e06103c08301526203e9836103e0830152612bc36104008301526000190160ff81116111145763ffffffff9160ff6144bb92169061432d565b6331389cdd60e11b60005260045260246000fd5b5060218111614621565b63ffffffff8116918260005260196020526040600020549182156149305763ffffffff6147d861396f565b1684101561492a578360005260166020526040600020906000948254946000965b60ff88168781101561482a576148249161481661481e9288614e00565b91905061379e565b97614602565b966147f9565b509391959296509360005b60ff8116848110156148de57906148618661485361485c9487614e00565b8a959195613895565b6137b8565b9161486c818b614535565b806148d5575b6148b7575b91614889928161488e575b5050614602565b614835565b60018060a01b0316600052600b6020526148ae604060002091825461379e565b90553880614882565b60678302928084046067149015171561111457606490920491614877565b50821515614872565b5050955050505060207f80560b830a111fea39438824469c6d4c4a3ec5cac1243db582590b83bcb95a019183600052601a82526040600020600160ff19825416179055604051908152a2565b50915050565b50919050600052601a6020526040600020600160ff19825416179055565b6001600160a01b031680156142b9576000918183528260205260408320548181106149b657817fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef926020928587528684520360408620558060025403600255604051908152a3565b6064939263391434e360e21b8452600452602452604452fd5b909392600063ffffffff82169560018714600014614a7d575050506001935b600052601460205260406000209060018060a01b0316600052602052604060002063ffffffff8416908163ffffffff1982541617905560048110614a755780156137c257620f42400462053020039062053020821161111457620f424091614a5591613895565b0433600052600b6020526040600020614a6f82825461379e565b90559190565b505060009190565b63ffffffff614a8b8461399a565b1682526011602081815260408085206001600160a01b038816808752908352818620548b87529383528186209086529091528320549091614acb9161379e565b90808210159182614b25575b505015614b1c57604063ffffffff9182614af3614b169561399a565b168152601460209081528282206001600160a01b03871683529052205416613957565b936149ee565b50506001614b16565b90809250600a0291600a830403612a175711153880614ad7565b63ffffffff811660008181526012602090815260408083206001600160a01b038716845290915290208054939695949193614c239392614b7e9161379e565b9055826000526013602052604060002060018060a01b0387166000526020526040600020614bad85825461379e565b9055614bf7620f4240614bce63ffffffff61310c614bc96137d8565b614613565b04846000526015602052604060002060018060a01b03891660005260205260406000205461379e565b958691846000526015602052604060002060018060a01b03831660005260205282604060002055615229565b600382029180830460031490151715611114576000526019602052614c51606460406000209204825461379e565b9055565b614c23909493929194600063ffffffff82169384825260116020526040822060018060a01b0389168352602052614c916040832091825461379e565b90556001600160a01b038716908190526000848152601360209081526040808320938352929052208054614bad90869061379e565b80548210156138435760005260206000200190600090565b600181111561399757806001600160801b821015614def575b600482600160401b614da1941015614de2575b640100000000811015614dd5575b62010000811015614dc8575b610100811015614dbc575b6010811015614db0575b1015614da8575b60030260011c614d5081846137b8565b0160011c614d5e81846137b8565b0160011c614d6c81846137b8565b0160011c614d7a81846137b8565b0160011c614d8881846137b8565b0160011c614d9681846137b8565b0160011c80926137b8565b8111900390565b60011b614d40565b811c9160021b91614d39565b60081c91811b91614d2f565b60101c9160081b91614d24565b60201c9160101b91614d18565b60401c9160201b91614d0a565b5050608081901c600160401b614cf7565b9190614e0e60029184614cc6565b90549060031b1c9283600052016020526040600020549160018060a01b03169190565b6001600160a01b03918216908216039190821161111457565b613997929091614ea791906001600160a01b0380821690851611614eb8575b6001600160a01b03614e7b8583614e31565b6001600160a01b039092169291169060601b6fffffffffffffffffffffffffffffffff60601b16615043565b6001600160a01b03909116906137b8565b92614e69565b80156137c2576503782dace9d960721b0490565b90606082901b90600019600160601b840992828085109403938085039414614f715783821115614f58578190600160601b9009816000038216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b50634e487b71600052156003026011186020526024601cfd5b509061399792506137b8565b6000908281029260001981830992848085109403938085039414614fd357600160601b841015614fc15750600160601b910990828211900360a01b910360601c1790565b634e487b71905260116020526024601cfd5b5050505060601c90565b6000670de0b6b3a7640000820291600019670de0b6b3a764000082099183808410930392808403931461503a57600160601b831015614fc15750600160601b90670de0b6b3a7640000900990828211900360a01b910360601c1790565b50505060601c90565b9181830291600019818509938380861095039480860395146150d757848311156150be5790829109816000038216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b82634e487b71600052156003026011186020526024601cfd5b50509061399792506137b8565b60009160001981830991818102938480851094039380850394146151295783600160401b11156102f2575090600160401b910990828211900360c01b910360401c1790565b5050505060401c90565b8015611165576503782dace9d960921b0490565b600090600019670de0b6b3a7640000820990670de0b6b3a76400008102928380841093039280840393146151a557600160801b8310156102f25750600160801b90670de0b6b3a7640000900990828211900360801b910360801c1790565b50505060801c90565b8015611165576503782dace9d960d21b0490565b600090600019670de0b6b3a7640000820990670de0b6b3a764000081029283808410930392808403931461522057600160c01b8310156102f25750600160c01b90670de0b6b3a7640000900990828211900360401b910360c01c1790565b50505060c01c90565b63ffffffff909392919316918260005260166020526040600020908154846000526018602052604060002054906021811061538e575083111561538757600094615274848285615494565b615334575b6000199360009584549760005b60ff81168a8110156152c25761529c9088614e00565b8981106152b4575b50506152af90614602565b615286565b90995097506152af386152a4565b5050600082815260186020908152604080832099909955601781529088902080546001600160a01b0319166001600160a01b039a8b16179055965192835293975092861695909116939192507f0b6dc977f9648d4c64075e7b9c7e2a0004fc9580218ffbe2a408cdbcee8747929190a4565b945083600052601760205261536860018060a01b0360406000205416806000526002840160205260006040812055836154b8565b506000848152601760205260409020546001600160a01b031694615279565b9350505050565b956020917f0b6dc977f9648d4c64075e7b9c7e2a0004fc9580218ffbe2a408cdbcee87479293976153c3878460009a98615494565b501590811561541c575b506153e6575b6040519485526001600160a01b031693a4565b83865260188252604080872086905584875260178352862080546001600160a01b0319166001600160a01b0383161790556153d3565b90508510386153cd565b600082815260018201602052604090205461548d57805490600160401b82101561374b578261547661545f846001809601855584614cc6565b819391549060031b91821b91600019901b19161790565b905580549260005201602052604060002055600190565b5050600090565b613997929160018060a01b0316918260005260028201602052604060002055615426565b90600182019181600052826020526040600020548015156000146155825760001981018181116111145782546000198101919082116111145781810361554b575b505050805480156155355760001901906155138282614cc6565b8154906000199060031b1b191690555560005260205260006040812055600190565b634e487b7160e01b600052603160045260246000fd5b61556b61555b61545f9386614cc6565b90549060031b1c92839286614cc6565b9055600052836020526040600020553880806154f9565b5050505060009056fee2fd935c135c640ea42de27d007d425b5fe4d067a6cb7753ad5bb66bc8479357a264697066735822122056712457d6eb1bd4e4d7370885daf61bcd0adab5cdec24957390c0d3cb67c37664736f6c634300081c003300000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000180000000000000000000000000e592427a0aece92de3edee1f18e0157c058615640000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000000000000050910000000000000000000000000000000000000000000000000000000e8d4a5100000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000004554c5449000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004554c544900000000000000000000000000000000000000000000000000000000

Deployed Bytecode

0x6080806040526004361015610028575b5036156100205761001e6139b3565b005b61001e6139b3565b600090813560e01c9081621cf236146135ee5750806305ecd003146135d357806306fdde0314613516578063080c279a146134db578063095ea7b3146134315780631296afb61461340057806318160ddd146133e2578063218acfd2146133ad5780632299e86214612ca657806323b872dd14612bc657806324ac0a9314612b8d5780632554447f14612b545780632959539014612b16578063313ce56714612afa5780633725597714612aa857806337bdb73014612a5857806339fb339e1461294e5780633ad863b5146128fe5780633e29da71146128c957806341161da11461289057806346ef64c41461286a57806348c56b971461284657806349401a3c146128015780634a3b68cc146127c057806359d7fff514612787578063647d153d1461274857806365cf7c9b14612721578063665a11ca146126f857806370a08231146126c0578063715018a61461269c578063735de9f71461265757806380ad62a21461261a57806382969bc3146124d357806385b12c7c14611eb45780638b99610014611e6f5780638bbcc07b14611e455780638bdb2afa14611e005780638da5cb5b14611dd757806391eb4bd614611db957806393b8898f14611d8057806395d89b4114611c7757806397d088f814611a62578063a7e0c60414611a0f578063a9059cbb146119dd578063b30d0aa2146115e2578063b44a27221461159d578063be26ed7f14611582578063c9c44de214611549578063caa18928146114f6578063d1ea4054146114bd578063d4611ec214611482578063dbd5ac6214610d84578063dc76fabc14610ca7578063dd62ed3e14610c52578063e0770b3e1461043a578063e4ec10d6146103d5578063f20eeb551461037e578063f2fde38b146102f55763f628e49f0361000f57346102f25760203660031901126102f25760ff604060209263ffffffff6102de613665565b168152601a84522054166040519015158152f35b80fd5b50346102f25760203660031901126102f25761030f613704565b6103176144c8565b6001600160a01b0316801561036a57600580546001600160a01b0319811683179091556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b631e4fbdf760e01b82526004829052602482fd5b50346102f25760403660031901126102f257604061039a613665565b9163ffffffff6103a861371a565b93168152601c602052209060018060a01b0316600052602052602061ffff60406000205416604051908152f35b50346102f25760403660031901126102f25761043060209160406103f7613665565b9163ffffffff61040561371a565b9316815260168552206001600160a01b03909116600090815260019091016020526040902054151590565b6040519015158152f35b5060803660031901126102f25761044f613704565b604435906064358015158103610c4e57610467614141565b60085415610c3f576001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811693907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216849003610c30577f000000000000000000000000000000000000000000000000000000e8d4a510003410610c21576001600160a01b03831693338514610c1257848652600d60205260408620546001600160a01b03163314610c0357814211610bf457338652600c60205260408620544210610be6578590819380610bd1575b610bbd575b803b15610bb9578160049160405192838092630d0e30db60e41b825234905af18015610bae57610b95575b5050610578613a54565b916001600160401b0360095416620151808101809111610b8157421015610b55576105c37f000000000000000000000000000000000000000000000000000000000005091034613895565b935b6024358510610b46576003340234810460031434151715610b3257606490049384670de0b6b3a764000002670de0b6b3a764000081048603610b1e579061060b916137b8565b928415610b0f578315610afd5761062284306142cf565b61271061062e8561387d565b049061271061063c8761387d565b049189600854937f00000000000000000000000000000000000000000000000000000000000000009081600014610af65788935b8215610aef578a925b8015610ae85781945b5015610ae05750925b6040519561069887613730565b86526020860190815260408601918252606086019283526080860193845260a086019485526040519563219f5d1760e01b87525160048701525160248601525160448501525160648401525160848301525160a482015260608160c4818b60018060a01b037f000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88165af1610aa3575b50338752600a6020526040872061073e86825461379e565b905561074861396f565b94610755868234336149cf565b90610760818461379e565b92338b52600f60205260408b2061077885825461379e565b9055338b52600d60205260408b20548b958695916001600160a01b031615610a9d5750338c52600d60205260408c20546001600160a01b03169a5b338d52600d60205260408d20546001600160a01b03161580610a94575b610a71575b506001600160a01b038b169a8b6108cd575b506107f49034338c614c55565b966201518042018042116108b957338d52600c60205260408d2055338c52600e60205260408c20541561089a575b9063ffffffff93929160405199348b5260208b015260408a0152606089015260808801521660a086015260c085015260e084015215156101008301526101208201527f907a4953eafd8d897ea997ad9bfa21da6e8cfbebaa112f8644d5d0820168f94d61014063ffffffff33941692a4600160065580f35b6282848042018042116108b957338d52600e60205260408d2055610822565b634e487b7160e01b8d52601160045260248dfd5b9091929394506305f5e1006108f063ffffffff6108e98d61433e565b1684613895565b048b8d52600f60205260408d2054600a810290808204600a1490151715610a5d578d9695949392918d91828952601060205260408920548111600014610a555782895260106020526040892054610946916137ab565b905b81811115610a4d5750915b8c8398841593841561096a575b50505050506107e7565b85969b5080829694959652600e602052604082205415610a12575b81816040926109c1979452600b6020528282206109a387825461379e565b905581526010602052206109b884825461379e565b90553491614b3f565b506021820291820460211417156109fe5760646107f4910495338d52600b60205260408d206109f188825461379e565b90559038808c8f8f610960565b634e487b7160e01b8c52601160045260248cfd5b50505050628284804201804211610a39578d8f52600e60205260408f2055828c8f8f610985565b634e487b7160e01b8f52601160045260248ffd5b905091610953565b508790610948565b634e487b7160e01b8e52601160045260248efd5b338d52600d60205260408d2080546001600160a01b0319169091179055386107d5565b508015156107d0565b9a6107b3565b6060813d606011610ad8575b81610abc6060938361377d565b81010312610ad457610acd906138ca565b5038610726565b8780fd5b3d9150610aaf565b90509261068b565b8294610682565b8992610679565b8993610670565b600162292fd760e11b03198852600488fd5b630531ac1760e11b8852600488fd5b634e487b7160e01b89526011600452602489fd5b634e487b7160e01b88526011600452602488fd5b63b9c5901b60e01b8752600487fd5b34670de0b6b3a764000002670de0b6b3a764000081043403610b815783610b7b916137b8565b936105c5565b634e487b7160e01b87526011600452602487fd5b81610b9f9161377d565b610baa57843861056e565b8480fd5b6040513d84823e3d90fd5b5080fd5b925050610bc8614163565b84600192610543565b50338252600a6020526040822054151561053e565b622ddbdd60e51b8652600486fd5b6380040f8d60e01b8652600486fd5b633eb1c49160e21b8652600486fd5b635f4ccded60e11b8652600486fd5b631210e84760e01b8552600485fd5b63052dd2e760e41b8552600485fd5b63b806e7fd60e01b8452600484fd5b8380fd5b50346102f25760403660031901126102f2576040610c6e613704565b91610c7761371a565b9260018060a01b031681526001602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102f257806003193601126102f257600754604051633850c7bd60e01b81529060e090829060049082906001600160a01b03165afa908115610bae5760209291610d4f575b506001600160a01b03167f000000000000000000000000000000000000000000000000000000000000000015610d3857610d2b81610d3092614f7d565b614fdd565b604051908152f35b80610d45610d4a92614ebe565b614ed2565b610d30565b610d71915060e03d60e011610d7d575b610d69818361377d565b8101906138ed565b50505050505038610cee565b503d610d5f565b50346102f25760403660031901126102f257602435610da1614141565b6008541561147357804211611464576001600160401b0360095460401c16421061145557610dcd61396f565b63ffffffff8116908184526016602052610dfb60408520339060019160005201602052604060002054151590565b1561144657818452601c6020526040842060018060a01b033316600052602052602161ffff604060002054161015611437576001821180611412575b6111fd575b50610e45613a54565b6040516370a0823160e01b81523060048201527f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b03169290602081602481875afa9081156111725786916111cb575b50620664f5810290808204620664f514901517156111b7576402540be400900493670de0b6b3a76400008502851590868104670de0b6b3a764000014821715610b3257610eea600435826137b8565b916111a85781156111995784610eff916137b8565b61268c81029080820461268c1490151715610b32576127109004808211156111915750905b6040519461010086018681106001600160401b0382111761117d5760409081529086523060208088019182526127108884019081523360608a0190815260808a0195865260a08a018b815260c08b0188815260e08c018e8152965163414bf38960e01b81529b516001600160a01b0390811660048e01529551861660248d0152925162ffffff1660448c01529051841660648b0152945160848a0152935160a4890152925160c48801529051811660e487015285906101049082908a907f000000000000000000000000e592427a0aece92de3edee1f18e0157c05861564165af1938415611172578694611139575b50831061112a57611024833361494e565b808552601b6020526110393360408720615426565b50808552601c6020526040852060018060a01b0333166000526020526040600020805461ffff600181831601169061ffff1916179055610ce4420180421161111457604095869167ffffffffffffffff60401b60095491841b169067ffffffffffffffff60401b191617600955828152601c6020522060018060a01b03331660005260205261ffff856000205416918551928584528460208501528684015260608301527fef77962ab378257316a9b3549cbb270fce18ce65180332939e21bda117ed149260803393a3600160065582519182526020820152f35b634e487b7160e01b600052601160045260246000fd5b633aee2ed960e21b8552600485fd5b9093506020813d60201161116a575b816111556020938361377d565b8101031261116557519238611013565b600080fd5b3d9150611148565b6040513d88823e3d90fd5b634e487b7160e01b89526041600452602489fd5b905090610f24565b638abef0a560e01b8852600488fd5b633ff4ef4360e01b8852600488fd5b634e487b7160e01b86526011600452602486fd5b90506020813d6020116111f5575b816111e66020938361377d565b81010312611165575138610e9b565b3d91506111d9565b61120961120e9161399a565b6147ad565b60085460405190608082018281106001600160401b038211176113fe57604090815290825230602083019081526001600160801b0383830181815260608501828152845163fc6f786560e01b81529551600487015292516001600160a01b03908116602487015290518216604486015291511660648401528290608490829088907f000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88165af180156113f357849185916113ba575b50849085927f00000000000000000000000000000000000000000000000000000000000000006000146113625780611339575b5060008051602061558c8339815191529181604092611331575b505b63ffffffff61131e61396f565b169382519182526020820152a238610e3c565b90503861130f565b6040919350918261135960008051602061558c833981519152943061494e565b939150916112f5565b9080611391575b5060008051602061558c8339815191529181604092611389575b50611311565b905038611383565b604091935091826113b160008051602061558c833981519152943061494e565b93915091611369565b9150506040813d6040116113eb575b816113d66040938361377d565b81010312610c4e5760208151910151386112c2565b3d91506113c9565b6040513d86823e3d90fd5b634e487b7160e01b86526041600452602486fd5b5063ffffffff6114218261399a565b168452601a60205260ff60408520541615610e37565b631dcf30bf60e11b8452600484fd5b633800201960e01b8452600484fd5b63df74c15f60e01b8252600482fd5b637ea1c91b60e11b8252600482fd5b63b806e7fd60e01b8252600482fd5b50346102f257806003193601126102f25760206040517f00000000000000000000000000000000000000000000000000000000000509108152f35b50346102f25760203660031901126102f2576020906040906001600160a01b036114e5613704565b168152600e83522054604051908152f35b50346102f25760403660031901126102f2576040611512613665565b9163ffffffff61152061371a565b931681526012602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102f25760203660031901126102f2576004359060ff821682036102f257602061157483614613565b63ffffffff60405191168152f35b50346102f257806003193601126102f257602061157461396f565b50346102f257806003193601126102f2576040517f000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe886001600160a01b03168152602090f35b50346102f257806003193601126102f25760085460405163133f757160e31b8152600481019190915290610180826024817f000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe886001600160a01b03165afa9182156119d057819261190d575b50600754604051633850c7bd60e01b81526001600160a01b039091169260e082600481875afa9182156119025783926118db575b50620d89a0926118b257640100eed0b4925060009173ff120d460d67f1db5b71087bd404babb342b5987906001600160a01b03811684868211611807575050506116cb9293614e4a565b7f000000000000000000000000000000000000000000000000000000000000000015611801575b6040516370a0823160e01b8152600481018490526020816024817f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b03165afa9081156117c3576000916117cf575b50604051936370a0823160e01b85526004850152602084602481305afa9182156117c35760009261178e575b60809450604051938452602084015260408301526060820152f35b91506020843d6020116117bb575b816117a96020938361377d565b81010312611165576080935191611773565b3d915061179c565b6040513d6000823e3d90fd5b90506020813d6020116117f9575b816117ea6020938361377d565b81010312611165575138611747565b3d91506117dd565b906116f2565b90929194828410600014611877575050936001600160801b039161183084869761186497614e4a565b959190829082906001600160a01b0382161161186a575b506001600160a01b039261185c929150614e31565b169116614f7d565b906116cb565b9250905061185c38611847565b509461186494506001600160801b03925081816001600160a01b038083169082161161186a57506001600160a01b039261185c929150614e31565b60405162461bcd60e51b81526020600482015260016024820152601560fa1b6044820152606490fd5b6118f591925060e03d60e011610d7d57610d69818361377d565b5050505050509038611681565b6040513d85823e3d90fd5b909150610180813d82116119c8575b8161192a610180938361377d565b81010312610bb95780516bffffffffffffffffffffffff811603610bb957611954602082016138a8565b50611961604082016138a8565b5061196e606082016138a8565b50608081015162ffffff811603610bb95761198b60a082016138bc565b5061199860c082016138bc565b506119c06101606119ab60e084016138ca565b926119b961014082016138ca565b50016138ca565b50903861164d565b3d915061191c565b50604051903d90823e3d90fd5b50346102f25760403660031901126102f257611a046119fa613704565b602435903361420a565b602060405160018152f35b50346102f25760403660031901126102f2576040611a2b613665565b9163ffffffff611a3961371a565b931681526013602052209060018060a01b03166000526020526020604060002054604051908152f35b50346102f25760203660031901126102f25763ffffffff611a81613665565b1680825260166020526040822090815490611a9b8261381f565b90611aa9604051928361377d565b828252601f19611ab88461381f565b01855b818110611c3c575050845b60ff811684811015611bb75790611bac82611ae4611bb29489614e00565b868b5260116020526040808c2060009060018060a01b0385168252602052205490878c5260126020528b604080822060009060018060a01b03871682526020522054898252601360205261ffff6040808080862060009060018060a01b038b1682526020522054948d8152601c6020522060009060018060a01b03891682526020522054169360405195611b7787613730565b6001600160a01b03168652602086015260408501526060840152608083015260a0820152611ba58288613869565b5285613869565b50614602565b611ac6565b8387604051918291602083016020845282518091526020604085019301915b818110611be4575050500390f35b91935091602060c060019261ffff60a088518680831b038151168452858101518685015260408101516040850152606081015160608501526080810151608085015201511660a0820152019401910191849392611bd6565b602090604051611c4b81613730565b88815288838201528860408201528860608201528860808201528860a082015282828701015201611abb565b50346102f257806003193601126102f2576040519080600454908160011c91600181168015611d76575b602084108114611d6257838652908115611d3b5750600114611cde575b611cda84611cce8186038261377d565b604051918291826136bb565b0390f35b600481527f8a35acfbc15ff81a39ae7d344fd709f28e8600b4aa8c65c6b64bfe7fe36bd19b939250905b808210611d2157509091508101602001611cce82611cbe565b919260018160209254838588010152019101909291611d08565b60ff191660208087019190915292151560051b85019092019250611cce9150839050611cbe565b634e487b7160e01b83526022600452602483fd5b92607f1692611ca1565b50346102f25760203660031901126102f2576020906040906001600160a01b03611da8613704565b168152600f83522054604051908152f35b50346102f257806003193601126102f2576020600854604051908152f35b50346102f257806003193601126102f2576005546040516001600160a01b039091168152602090f35b50346102f257806003193601126102f2576040517f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f9846001600160a01b03168152602090f35b50346102f257806003193601126102f25760206001600160401b0360095460401c16604051908152f35b50346102f257806003193601126102f2576040517f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b03168152602090f35b50346102f25760203660031901126102f257600435611ed16144c8565b6008546124c4577f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2611f0e8230336001600160a01b038516614568565b600954610ce442018042116124b0576fffffffffffffffffffffffffffffffff19909116426001600160401b031617604091821b67ffffffffffffffff60401b161760095551630b4c774160e11b81523060048201526001600160a01b03828116602483015261271060448301527f0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984169060208180606481010381855afa9081156124a557859161246b575b506001600160a01b031661245c5760405163a167129560e01b81523060048201526001600160a01b03831660248201526127106044820152906020908290606490829088905af19081156113f3578491612422575b50600780546001600160a01b0319166001600160a01b0383161790557f00000000000000000000000000000000000000000000000000000000000000009081156123e7577f000000000000000000000000000000000000000000000000000000000005091080156123d3576001600160a01b039061209290600160c01b04614cde565b16905b6001600160a01b031690813b156123cf5760405163f637731d60e01b81526001600160a01b039091166004820152858160248183865af18015611172576123bb575b508085913b15610bb9578180916024604051809481936332148f6760e01b835261ffff7f00000000000000000000000000000000000000000000000000000000000000601660048401525af18015610bae576123a6575b505061215a7f000000000000000000000000000000000000000000000000000000000005091084613895565b9061216582306142cf565b80156123a05730925b811561239857915b81156123915780915b1561238c5750835b6040519361016085018581106001600160401b038211176123785760409081526001600160a01b03918216865293811660208601908152612710868601908152620d899f1960608801908152620d89a06080808a0191825260a08a0197885260c08a0196875260e08a018c81526101008b018d8152306101208d01908152426101408e019081529b51634418b22b60e11b81529c51891660048e01529651881660248d0152945162ffffff1660448c01529251600290810b60648c0152915190910b60848a0152955160a4890152935160c4880152925160e4870152915161010486015290518116610124850152915161014484015290829061016490829087907f000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88165af190811561190257839161230d575b507f4bf60f71216c4f27fc663266fdd59a59dcba5c15a9c784b6996f75ad305099d1916040916008556122eb6144c8565b6122f36144f1565b60075482519182526001600160a01b03166020820152a180f35b90506080813d608011612370575b816123286080938361377d565b8101031261236c577f4bf60f71216c4f27fc663266fdd59a59dcba5c15a9c784b6996f75ad305099d1918161236360206040945192016138ca565b509150916122ba565b8280fd5b3d915061231b565b634e487b7160e01b88526041600452602488fd5b612187565b849161217f565b503091612176565b8261216e565b816123b09161377d565b610c4e57833861212e565b856123c89196929661377d565b93386120d7565b8580fd5b634e487b7160e01b86526012600452602486fd5b6001600160a01b0361241b7f000000000000000000000000000000000000000000000000000000000005091060c01b614cde565b1690612095565b90506020813d602011612454575b8161243d6020938361377d565b81010312610c4e5761244e906138a8565b3861200f565b3d9150612430565b631da01aeb60e11b8452600484fd5b90506020813d60201161249d575b816124866020938361377d565b81010312610baa57612497906138a8565b38611fba565b3d9150612479565b6040513d87823e3d90fd5b634e487b7160e01b85526011600452602485fd5b6332ecf57560e01b8252600482fd5b50346102f25760203660031901126102f2576124ed613665565b63ffffffff81168252601b60205260408220805491908390815b63ffffffff8116858110156125635761252361253b9184614cc6565b905460039190911b1c6001600160a01b031685614535565b61254e575b61254990613808565b612507565b9461255b61254991613808565b959050612540565b5050929363ffffffff16916125778361381f565b92612585604051948561377d565b808452612594601f199161381f565b01366020850137815b63ffffffff81168681101561260c576125b69086614cc6565b905460039190911b1c6001600160a01b03166125d28184614535565b6125e6575b506125e190613808565b61259d565b83612605916125ff63ffffffff6125e195971688613869565b52613808565b92906125d7565b60405180611cda8782613678565b50346102f257806003193601126102f25760206040517f000000000000000000000000000000000000000000000000000000000000000015158152f35b50346102f257806003193601126102f2576040517f000000000000000000000000e592427a0aece92de3edee1f18e0157c058615646001600160a01b03168152602090f35b50346102f257806003193601126102f2576126b56144c8565b6126bd6144f1565b80f35b50346102f25760203660031901126102f2576020906040906001600160a01b036126e8613704565b1681528083522054604051908152f35b50346102f257806003193601126102f2576007546040516001600160a01b039091168152602090f35b50346102f257806003193601126102f25760206001600160401b0360095416604051908152f35b50346102f257806003193601126102f257602060405161ffff7f0000000000000000000000000000000000000000000000000000000000000060168152f35b50346102f25760203660031901126102f2576020906040906001600160a01b036127af613704565b168152601083522054604051908152f35b50346102f25760203660031901126102f2576020906001600160a01b036127e5613704565b168152600d8252604060018060a01b0391205416604051908152f35b50346102f257806003193601126102f2576040517f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b03168152602090f35b50346102f25760203660031901126102f2576020611574612865613665565b61433e565b50346102f257806003193601126102f25760206128856137d8565b60ff60405191168152f35b50346102f25760203660031901126102f2576020906040906001600160a01b036128b8613704565b168152600b83522054604051908152f35b50346102f25760203660031901126102f257604060209163ffffffff6128ed613665565b168152601883522054604051908152f35b50346102f25760403660031901126102f257604060209161291d613665565b63ffffffff61292a61371a565b91168252601184528282206001600160a01b03909116825283522054604051908152f35b50346102f257806003193601126102f257612967614141565b60085415612a4957338152600e60205260408120544210612a3a57338152600b60205260408120548015612a2b57338252600b60205281604081205533825260106020528160408120556129bb81336142cf565b628284804201804211612a1757338352600e602052604083205563ffffffff6129e261396f565b166040519182527f3317998f30c22a741914cbb8b3f65cce45e8817db54aa6509a6ecb004753d05e60203393a3600160065580f35b634e487b7160e01b83526011600452602483fd5b6305950abd60e51b8252600482fd5b6342355f9960e11b8152600490fd5b63b806e7fd60e01b8152600490fd5b50346102f25760403660031901126102f2576040602091612a77613665565b63ffffffff612a8461371a565b91168252601584528282206001600160a01b03909116825283522054604051908152f35b50346102f25760403660031901126102f25763ffffffff6040602092612acc613665565b83612ad561371a565b91168252601485528282206001600160a01b0390911682528452205460405191168152f35b50346102f257806003193601126102f257602060405160128152f35b50346102f25760203660031901126102f25760209063ffffffff612b38613665565b16815260178252604060018060a01b0391205416604051908152f35b50346102f25760203660031901126102f2576020906040906001600160a01b03612b7c613704565b168152600a83522054604051908152f35b50346102f25760203660031901126102f2576020906040906001600160a01b03612bb5613704565b168152600c83522054604051908152f35b50346102f25760603660031901126102f257612be0613704565b612be861371a565b6001600160a01b038216808452600160208181526040808720338852909152852054604435949290918201612c24575b5050611a04935061420a565b848210612c8b578015612c77573315612c63576040868692611a049852600160205281812060018060a01b033316825260205220910390553880612c18565b634a1406b160e11b86526004869052602486fd5b63e602df0560e01b86526004869052602486fd5b6064868684637dc7a0d960e11b835233600452602452604452fd5b50346102f25760a03660031901126102f25760043590612cc461371a565b60643592608435918215158303610c4e57612cdd614141565b60085415610c3f577f000000000000000000000000000000000000000000000000000000e8d4a51000821061339e576001600160a01b0381169233841461338f57838552600d60205260408520546001600160a01b031633146133805785421161337157338552600c602052604085205442106133635784908061334e575b61333e575b612d968330337f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316614568565b612d9e613a54565b916001600160401b0360095416620151808101809111610b815742101561331257612de97f000000000000000000000000000000000000000000000000000000000005091085613895565b945b6044358610610b46576003850285810460031486151715610b3257606490049384670de0b6b3a764000002670de0b6b3a764000081048603610b1e5790612e31916137b8565b958415610b0f578615610afd578798612e4a88306142cf565b612710612e568961387d565b0490612710612e648861387d565b04918a600854937f0000000000000000000000000000000000000000000000000000000000000000908160001461330b578c935b8215613304578b925b80156132fd5781945b50156132f55750925b60405195612ec087613730565b86526020860190815260408601918252606086019283526080860193845260a086019485526040519563219f5d1760e01b87525160048701525160248601525160448501525160648401525160848301525160a482015260608160c4818c60018060a01b037f000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88165af16132b8575b50338852600a60205260408820612f6682825461379e565b9055612f7061396f565b96612f7d888389336149cf565b929091612f8a838361379e565b338c52600f60205260408c20612fa182825461379e565b9055338c52600d60205260408c20548c978897916001600160a01b0316156132b25750338d52600d60205260408d20546001600160a01b0316905b338e52600d60205260408e20548e906001600160a01b031615806132a9575b613285575b50506001600160a01b0381169c8d908d826130eb575b50505050613026908a338d614c55565b97620151804201804211610a5d5760408e338152600c6020522055338d52600e60205260408d2054156130cc575b9063ffffffff949392916040519a8b5260208b015260408a0152606089015260808801521660a086015260c085015260e084015215156101008301526101208201527f907a4953eafd8d897ea997ad9bfa21da6e8cfbebaa112f8644d5d0820168f94d61014063ffffffff33941692a4600160065580f35b628284804201804211610a5d57338e52600e60205260408e2055613054565b604092939495969798995061311363ffffffff61310c6305f5e1009361433e565b1687613895565b04928152600f6020522054600a810290808204600a1490151715610a39578e8c8f92938f9a99989796959484845260106020526040842054811160001461327d578484526010602052604084205461316a916137ab565b905b818111156132755750935b849a851594851561318d575b9450915050613016565b869798999a9b9c9d50808596979552600e602052604086205415613229575b85816040926131e59852600b6020528282206131c988825461379e565b905581526010602052206131de85825461379e565b9055614b3f565b506021820291820460211417156108b9578c96959493929160406064613026930498338152600b6020522061321b89825461379e565b905590388e8c8f8f81613183565b505092505050628284804201804211613260578f8f928f8f92808689966131e59860409452600e60205283832055915095506131ac565b50634e487b7160e01b8f52601160045260248ffd5b905093613177565b50829061316c565b338152600d6020526040902080546001600160a01b0319169091179055388d613000565b50811515612ffb565b90612fdc565b6060813d6060116132ed575b816132d16060938361377d565b810103126132e9576132e2906138ca565b5038612f4e565b8880fd5b3d91506132c4565b905092612eb3565b8294612eaa565b8d92612ea1565b8a93612e98565b83670de0b6b3a764000002670de0b6b3a764000081048503610b815783613338916137b8565b94612deb565b50613347614163565b6001612d61565b50338552600a60205260408520541515612d5c565b622ddbdd60e51b8552600485fd5b6380040f8d60e01b8552600485fd5b633eb1c49160e21b8552600485fd5b635f4ccded60e11b8552600485fd5b631210e84760e01b8452600484fd5b50346102f25760203660031901126102f257604060209163ffffffff6133d1613665565b168152601983522054604051908152f35b50346102f257806003193601126102f2576020600254604051908152f35b50346102f257806003193601126102f257613419614141565b60085415612a4957613429614163565b600160065580f35b50346102f25760403660031901126102f25761344b613704565b6024359033156134c7576001600160a01b03169182156134b35760408291338152600160205281812085825260205220556040519081527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560203392a3602060405160018152f35b634a1406b160e11b81526004819052602490fd5b63e602df0560e01b83526004839052602483fd5b50346102f257806003193601126102f25760206040517f000000000000000000000000000000000000000000000000000000e8d4a510008152f35b50346102f257806003193601126102f2576040519080600354908160011c916001811680156135c9575b602084108114611d6257838652908115611d3b575060011461356c57611cda84611cce8186038261377d565b600381527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b939250905b8082106135af57509091508101602001611cce82611cbe565b919260018160209254838588010152019101909291613596565b92607f1692613540565b50346102f257806003193601126102f2576020610d30613a54565b82346102f25760203660031901126102f25763ffffffff61360d613665565b168152601b602052604081209081548084526020840192825260208220915b81811061364f57611cda856136438187038261377d565b60405191829182613678565b825484526020909301926001928301920161362c565b6004359063ffffffff8216820361116557565b602060408183019282815284518094520192019060005b81811061369c5750505090565b82516001600160a01b031684526020938401939092019160010161368f565b91909160208152825180602083015260005b8181106136ee575060409293506000838284010152601f8019910116010190565b80602080928701015160408286010152016136cd565b600435906001600160a01b038216820361116557565b602435906001600160a01b038216820361116557565b60c081019081106001600160401b0382111761374b57604052565b634e487b7160e01b600052604160045260246000fd5b61042081019081106001600160401b0382111761374b57604052565b90601f801991011681019081106001600160401b0382111761374b57604052565b9190820180921161111457565b9190820391821161111457565b81156137c2570490565b634e487b7160e01b600052601260045260246000fd5b62015180622b81806137f56001600160401b0360095416426137ab565b0604600181018091116111145760ff1690565b63ffffffff1663ffffffff81146111145760010190565b6001600160401b03811161374b5760051b60200190565b8051156138435760200190565b634e487b7160e01b600052603260045260246000fd5b8051600110156138435760400190565b80518210156138435760209160051b010190565b906126ad8202918083046126ad149015171561111457565b8181029291811591840414171561111457565b51906001600160a01b038216820361116557565b51908160020b820361116557565b51906001600160801b038216820361116557565b519061ffff8216820361116557565b908160e091031261116557613901816138a8565b9161390e602083016138bc565b9161391b604082016138de565b91613928606083016138de565b91613935608082016138de565b9160a082015160ff811681036111655760c09092015180151581036111655790565b63ffffffff60019116019063ffffffff821161111457565b61399763ffffffff622b81806139906001600160401b0360095416426137ab565b0416613957565b90565b63ffffffff6000199116019063ffffffff821161111457565b6001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28116907f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216819003613a4357803b1561116557600060049160405192838092630d0e30db60e41b825234905af180156117c357613a365750565b6000613a419161377d565b565b63052dd2e760e41b60005260046000fd5b6104416001600160401b0360095416016001600160401b038111611114576001600160401b0316421061410d57604051613a8f60608261377d565b60028152602081016040368237610441613aa883613836565b526000613ab483613859565b5260018060a01b0360075416604051809263883bdbfd60e01b82526024820160206004840152855180915260448301919060005b8181106140ee5750505091818060009403915afa60009181613fdc575b50613b1b576389d9e13d60e01b60005260046000fd5b613b31613b2782613859565b5160060b91613836565b5160060b900390667fffffffffffff198212667fffffffffffff8313176111145763ffffffff613b6082613836565b511660030b9160060b9180156137c257667fffffffffffff19831460001982141661111457820560020b91600081129182613fb2575b5050613f9e575b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29060020b600080821215613f9857818103915b620d89e883116118b2576001831615613f86576001600160881b036ffffcb933bd6fad37aa2d162d1a5940015b169260028116613f6a575b60048116613f4e575b60088116613f32575b60108116613f16575b60208116613efa575b60408116613ede575b60808116613ec2575b6101008116613ea6575b6102008116613e8a575b6104008116613e6e575b6108008116613e52575b6110008116613e36575b6120008116613e1a575b6140008116613dfe575b6180008116613de2575b620100008116613dc6575b620200008116613dab575b620400008116613d90575b6208000016613d77575b8112613d52575b63ffffffff8216613d4957905b60201c60ff91909116016001600160a01b03166001600160801b038111613d1c5780613cf991613895565b906001600160a01b0316301015613d1357613997906151c2565b613997906151ae565b80613d26916150e4565b906001600160a01b0316301015613d405761399790615147565b61399790615133565b50600190613cce565b908015613d63576000190490613cc1565b634e487b7160e01b82526012600452602482fd5b6b048a170391f7dc42444e8fa290920260801c91613cba565b6d2216e584f5fa1ea926041bedfe9890930260801c92613cb0565b926e5d6af8dedb81196699c329225ee6040260801c92613ca5565b926f09aa508b5b7a84e1c677de54f3e99bc90260801c92613c9a565b926f31be135f97d08fd981231505542fcfa60260801c92613c8f565b926f70d869a156d2a1b890bb3df62baf32f70260801c92613c85565b926fa9f746462d870fdf8a65dc1f90e061e50260801c92613c7b565b926fd097f3bdfd2022b8845ad8f792aa58250260801c92613c71565b926fe7159475a2c29b7443b29c7fa6e889d90260801c92613c67565b926ff3392b0822b70005940c7a398e4b70f30260801c92613c5d565b926ff987a7253ac413176f2b074cf7815e540260801c92613c53565b926ffcbe86c7900a88aedcffc83b479aa3a40260801c92613c49565b926ffe5dee046a99a2a811c461f1969c30530260801c92613c3f565b926fff2ea16466c96a3843ec78b326b528610260801c92613c36565b926fff973b41fa98c081472e6896dfb254c00260801c92613c2d565b926fffcb9843d60f6159c9db58835c9266440260801c92613c24565b926fffe5caca7e10e4e61c3624eaa0941cd00260801c92613c1b565b926ffff2e50f5f656932ef12357cf3c7fdcc0260801c92613c12565b926ffff97272373d413259a46990580e213a0260801c92613c09565b6001600160881b03600160801b613bfe565b81613bd1565b627fffff1981146111145760001901613b9d565b63ffffffff919250613fc390613836565b511660060b9081156137c2570760060b15153880613b96565b90913d8082843e613fed818461377d565b8201906040838303126102f25782516001600160401b038111610bb95783019282601f85011215610bb95783516140238161381f565b94614031604051968761377d565b81865260208087019260051b82010190858211610baa57602001915b8183106140d4575050506020810151906001600160401b03821161236c570182601f82011215610bb9578051916020806140868561381f565b614093604051918261377d565b858152019360051b8301019384116102f25750602001905b8282106140bc575050509038613b05565b602080916140c9846138a8565b8152019101906140ab565b82518060060b81036123cf5781526020928301920161404d565b825163ffffffff16845286945060209384019390920191600101613ae8565b7f000000000000000000000000000000000000000000000000000000000005091080156137c257670de0b6b3a76400000490565b600260065414614152576002600655565b633ee5aeb560e01b60005260046000fd5b33600052600c60205260406000205442106141f95733600052600a602052604060002054156141e857336000818152600a602052604081208054919055906141ac9082906142cf565b63ffffffff6141b961396f565b166040519182527fdc8b8058bd26d719cc330a54461930fd9c312dd28447313fd5dc4641513e007460203393a3565b630f4c8e7560e11b60005260046000fd5b630fb9ee4d60e11b60005260046000fd5b6001600160a01b03169081156142b9576001600160a01b03169182156142a35760008281528060205260408120548281106142895791604082827fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef958760209652828652038282205586815280845220818154019055604051908152a3565b916064928463391434e360e21b8452600452602452604452fd5b63ec442f0560e01b600052600060045260246000fd5b634b637e8f60e11b600052600060045260246000fd5b6001600160a01b03169081156142a3576142eb8160025461379e565b6002557fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef602060009284845283825260408420818154019055604051908152a3565b9060218110156138435760051b0190565b602163ffffffff8216116144c0576144bb63ffffffff91826144b46040519261436684613761565b6301f78a4084526301d32fcc60208501526301b1753b60408501526301922a0b60608501526301752139608085015263015a310660a085015263014132b260c085015263012a024c60e08501526301147e7c610100850152630100884e61012085015262ee031061014085015262dcd41d61016085015262cce2c061018085015262be180b6101a085015262b05eb86101c085015262a3a30a6101e08501526297d2b2610200850152628cdcb26102208501526282b146610240850152627941cf610260850152627080bb610280850152626861736102a08501526260d8486102c08501526259da646102e085015262535db8610300850152624d58f26103208501526247c36861034085015262429512610360850152623dc67f610380850152623950c26103a085015262352d746103c08501526231569f6103e0850152622dc6c061040085015261399a565b169061432d565b511690565b50622dc6c090565b6005546001600160a01b031633036144dc57565b63118cdaa760e01b6000523360045260246000fd5b600580546001600160a01b031981169091556000906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3565b63ffffffff16600052601c60205260406000209060018060a01b0316600052602052600b61ffff60406000205416101590565b6040516323b872dd60e01b60208083019182526001600160a01b03948516602484015294909316604482015260648082019590955293845292600091906145b060848261377d565b519082855af1156117c3576000513d6145f957506001600160a01b0381163b155b6145d85750565b635274afe760e01b60009081526001600160a01b0391909116600452602490fd5b600114156145d1565b60ff1660ff81146111145760010190565b60ff166001811080156147a3575b61478f576040519061463282613761565b620f423c8252620f423a6020830152620f42376040830152620f42326060830152620f422c6080830152620f422260a0830152620f421360c0830152620f41fd60e0830152620f41dc610100830152620f41ab610120830152620f4162610140830152620f40f4610160830152620f4051610180830152620f3f5e6101a0830152620f3df36101c0830152620f3bd66101e0830152620f38af610200830152620f33fc610220830152620f2cfc610240830152620f228d610260830152620f1307610280830152620efbf06102a0830152620ed9ab6102c0830152620ea6ea6102e0830152620e5c04610300830152620dee11610320830152620d4de6610340830152620c672a610360830152620b201261038083015262095ac16103a08301526206f9e06103c08301526203e9836103e0830152612bc36104008301526000190160ff81116111145763ffffffff9160ff6144bb92169061432d565b6331389cdd60e11b60005260045260246000fd5b5060218111614621565b63ffffffff8116918260005260196020526040600020549182156149305763ffffffff6147d861396f565b1684101561492a578360005260166020526040600020906000948254946000965b60ff88168781101561482a576148249161481661481e9288614e00565b91905061379e565b97614602565b966147f9565b509391959296509360005b60ff8116848110156148de57906148618661485361485c9487614e00565b8a959195613895565b6137b8565b9161486c818b614535565b806148d5575b6148b7575b91614889928161488e575b5050614602565b614835565b60018060a01b0316600052600b6020526148ae604060002091825461379e565b90553880614882565b60678302928084046067149015171561111457606490920491614877565b50821515614872565b5050955050505060207f80560b830a111fea39438824469c6d4c4a3ec5cac1243db582590b83bcb95a019183600052601a82526040600020600160ff19825416179055604051908152a2565b50915050565b50919050600052601a6020526040600020600160ff19825416179055565b6001600160a01b031680156142b9576000918183528260205260408320548181106149b657817fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef926020928587528684520360408620558060025403600255604051908152a3565b6064939263391434e360e21b8452600452602452604452fd5b909392600063ffffffff82169560018714600014614a7d575050506001935b600052601460205260406000209060018060a01b0316600052602052604060002063ffffffff8416908163ffffffff1982541617905560048110614a755780156137c257620f42400462053020039062053020821161111457620f424091614a5591613895565b0433600052600b6020526040600020614a6f82825461379e565b90559190565b505060009190565b63ffffffff614a8b8461399a565b1682526011602081815260408085206001600160a01b038816808752908352818620548b87529383528186209086529091528320549091614acb9161379e565b90808210159182614b25575b505015614b1c57604063ffffffff9182614af3614b169561399a565b168152601460209081528282206001600160a01b03871683529052205416613957565b936149ee565b50506001614b16565b90809250600a0291600a830403612a175711153880614ad7565b63ffffffff811660008181526012602090815260408083206001600160a01b038716845290915290208054939695949193614c239392614b7e9161379e565b9055826000526013602052604060002060018060a01b0387166000526020526040600020614bad85825461379e565b9055614bf7620f4240614bce63ffffffff61310c614bc96137d8565b614613565b04846000526015602052604060002060018060a01b03891660005260205260406000205461379e565b958691846000526015602052604060002060018060a01b03831660005260205282604060002055615229565b600382029180830460031490151715611114576000526019602052614c51606460406000209204825461379e565b9055565b614c23909493929194600063ffffffff82169384825260116020526040822060018060a01b0389168352602052614c916040832091825461379e565b90556001600160a01b038716908190526000848152601360209081526040808320938352929052208054614bad90869061379e565b80548210156138435760005260206000200190600090565b600181111561399757806001600160801b821015614def575b600482600160401b614da1941015614de2575b640100000000811015614dd5575b62010000811015614dc8575b610100811015614dbc575b6010811015614db0575b1015614da8575b60030260011c614d5081846137b8565b0160011c614d5e81846137b8565b0160011c614d6c81846137b8565b0160011c614d7a81846137b8565b0160011c614d8881846137b8565b0160011c614d9681846137b8565b0160011c80926137b8565b8111900390565b60011b614d40565b811c9160021b91614d39565b60081c91811b91614d2f565b60101c9160081b91614d24565b60201c9160101b91614d18565b60401c9160201b91614d0a565b5050608081901c600160401b614cf7565b9190614e0e60029184614cc6565b90549060031b1c9283600052016020526040600020549160018060a01b03169190565b6001600160a01b03918216908216039190821161111457565b613997929091614ea791906001600160a01b0380821690851611614eb8575b6001600160a01b03614e7b8583614e31565b6001600160a01b039092169291169060601b6fffffffffffffffffffffffffffffffff60601b16615043565b6001600160a01b03909116906137b8565b92614e69565b80156137c2576503782dace9d960721b0490565b90606082901b90600019600160601b840992828085109403938085039414614f715783821115614f58578190600160601b9009816000038216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b50634e487b71600052156003026011186020526024601cfd5b509061399792506137b8565b6000908281029260001981830992848085109403938085039414614fd357600160601b841015614fc15750600160601b910990828211900360a01b910360601c1790565b634e487b71905260116020526024601cfd5b5050505060601c90565b6000670de0b6b3a7640000820291600019670de0b6b3a764000082099183808410930392808403931461503a57600160601b831015614fc15750600160601b90670de0b6b3a7640000900990828211900360a01b910360601c1790565b50505060601c90565b9181830291600019818509938380861095039480860395146150d757848311156150be5790829109816000038216809204600281600302188082026002030280820260020302808202600203028082026002030280820260020302809102600203029360018380600003040190848311900302920304170290565b82634e487b71600052156003026011186020526024601cfd5b50509061399792506137b8565b60009160001981830991818102938480851094039380850394146151295783600160401b11156102f2575090600160401b910990828211900360c01b910360401c1790565b5050505060401c90565b8015611165576503782dace9d960921b0490565b600090600019670de0b6b3a7640000820990670de0b6b3a76400008102928380841093039280840393146151a557600160801b8310156102f25750600160801b90670de0b6b3a7640000900990828211900360801b910360801c1790565b50505060801c90565b8015611165576503782dace9d960d21b0490565b600090600019670de0b6b3a7640000820990670de0b6b3a764000081029283808410930392808403931461522057600160c01b8310156102f25750600160c01b90670de0b6b3a7640000900990828211900360401b910360c01c1790565b50505060c01c90565b63ffffffff909392919316918260005260166020526040600020908154846000526018602052604060002054906021811061538e575083111561538757600094615274848285615494565b615334575b6000199360009584549760005b60ff81168a8110156152c25761529c9088614e00565b8981106152b4575b50506152af90614602565b615286565b90995097506152af386152a4565b5050600082815260186020908152604080832099909955601781529088902080546001600160a01b0319166001600160a01b039a8b16179055965192835293975092861695909116939192507f0b6dc977f9648d4c64075e7b9c7e2a0004fc9580218ffbe2a408cdbcee8747929190a4565b945083600052601760205261536860018060a01b0360406000205416806000526002840160205260006040812055836154b8565b506000848152601760205260409020546001600160a01b031694615279565b9350505050565b956020917f0b6dc977f9648d4c64075e7b9c7e2a0004fc9580218ffbe2a408cdbcee87479293976153c3878460009a98615494565b501590811561541c575b506153e6575b6040519485526001600160a01b031693a4565b83865260188252604080872086905584875260178352862080546001600160a01b0319166001600160a01b0383161790556153d3565b90508510386153cd565b600082815260018201602052604090205461548d57805490600160401b82101561374b578261547661545f846001809601855584614cc6565b819391549060031b91821b91600019901b19161790565b905580549260005201602052604060002055600190565b5050600090565b613997929160018060a01b0316918260005260028201602052604060002055615426565b90600182019181600052826020526040600020548015156000146155825760001981018181116111145782546000198101919082116111145781810361554b575b505050805480156155355760001901906155138282614cc6565b8154906000199060031b1b191690555560005260205260006040812055600190565b634e487b7160e01b600052603160045260246000fd5b61556b61555b61545f9386614cc6565b90549060031b1c92839286614cc6565b9055600052836020526040600020553880806154f9565b5050505060009056fee2fd935c135c640ea42de27d007d425b5fe4d067a6cb7753ad5bb66bc8479357a264697066735822122056712457d6eb1bd4e4d7370885daf61bcd0adab5cdec24957390c0d3cb67c37664736f6c634300081c0033

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

00000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000180000000000000000000000000e592427a0aece92de3edee1f18e0157c058615640000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc20000000000000000000000000000000000000000000000000000000000050910000000000000000000000000000000000000000000000000000000e8d4a5100000000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000004554c5449000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004554c544900000000000000000000000000000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _name (string): ULTI
Arg [1] : _symbol (string): ULTI
Arg [2] : uniswapRouterAddress (address): 0xE592427A0AEce92De3Edee1F18E0157C05861564
Arg [3] : uniswapFactoryAddress (address): 0x1F98431c8aD98523631AE4a59f267346ea31F984
Arg [4] : nonfungiblePositionManagerAddress (address): 0xC36442b4a4522E871399CD717aBDD847Ab11FE88
Arg [5] : _inputTokenAddress (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [6] : _wrappedNativeTokenAddress (address): 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
Arg [7] : _initialRatio (uint256): 330000
Arg [8] : _minimumDepositAmount (uint256): 1000000000000
Arg [9] : _minimumTwapObservations (uint16): 96

-----Encoded View---------------
14 Constructor Arguments found :
Arg [0] : 0000000000000000000000000000000000000000000000000000000000000140
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [2] : 000000000000000000000000e592427a0aece92de3edee1f18e0157c05861564
Arg [3] : 0000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f984
Arg [4] : 000000000000000000000000c36442b4a4522e871399cd717abdd847ab11fe88
Arg [5] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [6] : 000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
Arg [7] : 0000000000000000000000000000000000000000000000000000000000050910
Arg [8] : 000000000000000000000000000000000000000000000000000000e8d4a51000
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000060
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000004
Arg [11] : 554c544900000000000000000000000000000000000000000000000000000000
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000004
Arg [13] : 554c544900000000000000000000000000000000000000000000000000000000


Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.