ETH Price: $1,860.00 (-4.25%)
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Purchase Tokens218168952025-02-10 15:04:23378 days ago1739199863IN
0xAB8b4d0A...FBc48B9BF
0 ETH0.00033792.17246569
Purchase Tokens218125802025-02-10 0:36:35378 days ago1739147795IN
0xAB8b4d0A...FBc48B9BF
0 ETH0.000377931.82717099
Purchase Tokens218118082025-02-09 22:01:35378 days ago1739138495IN
0xAB8b4d0A...FBc48B9BF
0 ETH0.000936433.88518099
Purchase Tokens218114832025-02-09 20:56:23378 days ago1739134583IN
0xAB8b4d0A...FBc48B9BF
0.02 ETH0.000323841.90744479
Purchase Tokens218114392025-02-09 20:47:35378 days ago1739134055IN
0xAB8b4d0A...FBc48B9BF
1.11 ETH0.000446122.01876457
Purchase Tokens218112512025-02-09 20:09:47378 days ago1739131787IN
0xAB8b4d0A...FBc48B9BF
0.02 ETH0.000368441.6665807
Purchase Tokens218112012025-02-09 19:59:47378 days ago1739131187IN
0xAB8b4d0A...FBc48B9BF
0.08 ETH0.000394111.78267541
Purchase Tokens217762362025-02-04 22:52:11383 days ago1738709531IN
0xAB8b4d0A...FBc48B9BF
0.052 ETH0.000389231.76060416
Purchase Tokens217466392025-01-31 19:37:11387 days ago1738352231IN
0xAB8b4d0A...FBc48B9BF
0.6748 ETH0.002448446.02581462
Purchase Tokens217402232025-01-30 22:05:47388 days ago1738274747IN
0xAB8b4d0A...FBc48B9BF
0.016 ETH0.000772624.5507493
Purchase Tokens217402042025-01-30 22:01:47388 days ago1738274507IN
0xAB8b4d0A...FBc48B9BF
0.0554 ETH0.000984394.45269262
Purchase Tokens217339482025-01-30 1:04:35389 days ago1738199075IN
0xAB8b4d0A...FBc48B9BF
0.2 ETH0.000542542.45481404
Purchase Tokens217180302025-01-27 19:44:35391 days ago1738007075IN
0xAB8b4d0A...FBc48B9BF
0.077 ETH0.003465568.18287708
Purchase Tokens217178192025-01-27 19:02:23391 days ago1738004543IN
0xAB8b4d0A...FBc48B9BF
0.04 ETH0.0028220112.76473369
Purchase Tokens217161562025-01-27 13:27:47392 days ago1737984467IN
0xAB8b4d0A...FBc48B9BF
0.1442 ETH0.0031143414.08968603
Purchase Tokens216952442025-01-24 15:25:35395 days ago1737732335IN
0xAB8b4d0A...FBc48B9BF
0.08 ETH0.0037834917.11701265
Purchase Tokens216848352025-01-23 4:34:47396 days ago1737606887IN
0xAB8b4d0A...FBc48B9BF
0.016 ETH0.001183525.3534159
Purchase Tokens216756442025-01-21 21:46:59397 days ago1737496019IN
0xAB8b4d0A...FBc48B9BF
0.0543 ETH0.003240114.65585363
Purchase Tokens216731222025-01-21 13:20:35398 days ago1737465635IN
0xAB8b4d0A...FBc48B9BF
0.04 ETH0.0029291613.24941757
Purchase Tokens216730442025-01-21 13:04:47398 days ago1737464687IN
0xAB8b4d0A...FBc48B9BF
0.25 ETH0.0030153313.64318389
Purchase Tokens216711142025-01-21 6:36:23398 days ago1737441383IN
0xAB8b4d0A...FBc48B9BF
0.1 ETH0.001623097.34310402
Purchase Tokens216691382025-01-20 23:58:23398 days ago1737417503IN
0xAB8b4d0A...FBc48B9BF
0.02 ETH0.0026006815.31807719
Purchase Tokens216682842025-01-20 21:06:47398 days ago1737407207IN
0xAB8b4d0A...FBc48B9BF
0.055 ETH0.0049608722.43937543
Purchase Tokens216669702025-01-20 16:42:59399 days ago1737391379IN
0xAB8b4d0A...FBc48B9BF
0.06 ETH0.0074974633.91303834
Purchase Tokens216664702025-01-20 15:02:35399 days ago1737385355IN
0xAB8b4d0A...FBc48B9BF
0.0297 ETH0.0074915333.88623283
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Method Block
From
To
Transfer218114832025-02-09 20:56:23378 days ago1739134583
0xAB8b4d0A...FBc48B9BF
0.02 ETH
Transfer218114392025-02-09 20:47:35378 days ago1739134055
0xAB8b4d0A...FBc48B9BF
1.11 ETH
Transfer218112512025-02-09 20:09:47378 days ago1739131787
0xAB8b4d0A...FBc48B9BF
0.02 ETH
Transfer218112012025-02-09 19:59:47378 days ago1739131187
0xAB8b4d0A...FBc48B9BF
0.08 ETH
Transfer217762362025-02-04 22:52:11383 days ago1738709531
0xAB8b4d0A...FBc48B9BF
0.052 ETH
Transfer217466392025-01-31 19:37:11387 days ago1738352231
0xAB8b4d0A...FBc48B9BF
0.10122 ETH
Transfer217466392025-01-31 19:37:11387 days ago1738352231
0xAB8b4d0A...FBc48B9BF
0.57358 ETH
Transfer217402232025-01-30 22:05:47388 days ago1738274747
0xAB8b4d0A...FBc48B9BF
0.016 ETH
Transfer217402042025-01-30 22:01:47388 days ago1738274507
0xAB8b4d0A...FBc48B9BF
0.0554 ETH
Transfer217339482025-01-30 1:04:35389 days ago1738199075
0xAB8b4d0A...FBc48B9BF
0.2 ETH
Transfer217180302025-01-27 19:44:35391 days ago1738007075
0xAB8b4d0A...FBc48B9BF
0.01155 ETH
Transfer217180302025-01-27 19:44:35391 days ago1738007075
0xAB8b4d0A...FBc48B9BF
0.06545 ETH
Transfer217178192025-01-27 19:02:23391 days ago1738004543
0xAB8b4d0A...FBc48B9BF
0.04 ETH
Transfer217161562025-01-27 13:27:47392 days ago1737984467
0xAB8b4d0A...FBc48B9BF
0.1442 ETH
Transfer216952442025-01-24 15:25:35395 days ago1737732335
0xAB8b4d0A...FBc48B9BF
0.08 ETH
Transfer216848352025-01-23 4:34:47396 days ago1737606887
0xAB8b4d0A...FBc48B9BF
0.016 ETH
Transfer216756442025-01-21 21:46:59397 days ago1737496019
0xAB8b4d0A...FBc48B9BF
0.0543 ETH
Transfer216731222025-01-21 13:20:35398 days ago1737465635
0xAB8b4d0A...FBc48B9BF
0.04 ETH
Transfer216730442025-01-21 13:04:47398 days ago1737464687
0xAB8b4d0A...FBc48B9BF
0.25 ETH
Transfer216711142025-01-21 6:36:23398 days ago1737441383
0xAB8b4d0A...FBc48B9BF
0.1 ETH
Transfer216691382025-01-20 23:58:23398 days ago1737417503
0xAB8b4d0A...FBc48B9BF
0.02 ETH
Transfer216682842025-01-20 21:06:47398 days ago1737407207
0xAB8b4d0A...FBc48B9BF
0.055 ETH
Transfer216669702025-01-20 16:42:59399 days ago1737391379
0xAB8b4d0A...FBc48B9BF
0.06 ETH
Transfer216664702025-01-20 15:02:35399 days ago1737385355
0xAB8b4d0A...FBc48B9BF
0.0297 ETH
Transfer216664602025-01-20 15:00:35399 days ago1737385235
0xAB8b4d0A...FBc48B9BF
0.02 ETH
View All Internal Transactions
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

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

Contract Source Code Verified (Exact Match)

Contract Name:
PresaleSNOVA

Compiler Version
v0.8.24+commit.e11b9ed9

Optimization Enabled:
Yes with 200 runs

Other Settings:
paris EvmVersion
File 1 of 20 : PresaleSNOVA.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {TokenSaleRegistry} from "./TokenSaleRegistry.sol";

/**
 * @title Pre-sale Contract for SNOVA Tokens
 * @dev Manages the pre-sale phase of SNOVA tokens, incorporating price feeds for dynamic pricing and allowing for contributions
 * in the native currency and other stablecoins (USDT, USDC, DAI). This contract leverages the OpenZeppelin library for role management,
 * token safety, reentrancy checks, and operational controls (pause/unpause). It is closely tied to the TokenSaleRegistry, from which
 * it retrieves information about token sale rounds and referral incentives, ensuring consistent and secure transaction processing.
 *
 * Key functionalities include token purchasing, token and native currency recovery, and configuration of operational parameters.
 */
contract PresaleSNOVA is AccessControl, ReentrancyGuard, Pausable {
    using SafeERC20 for IERC20;
    using Address for address payable;

    bytes32 public constant PURCHASE_AGENT_ROLE = keccak256("PURCHASE_AGENT_ROLE");
    address internal constant NATIVE_CURRENCY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    struct Currency {
        AggregatorV3Interface priceFeed;
        uint256 decimals; // 18 or 6 depends on token and network
        bool useStaticPrice; // If true, use a static price of $1
        uint256 totalCollected; // Total collected amount of the currency
    }

    TokenSaleRegistry private _presaleStorage;
    mapping(address => Currency) private _currencies; // Mapping to store whitelisted currencies for purchase
    mapping(address => uint256) private _novaPoints; // Mapping to store Nova Points for each user
    mapping(address => uint256) private _referralCount; // Mapping to store referral count for each user
    mapping(address => bool) private _hasPurchased; // Mapping to track if a user has already made a purchase
    mapping(address => address) private _referrer; // Mapping to track referrer for each user
    uint256 private _priceThresholdSeconds;

    /**
     * @notice Emitted when the price threshold time is updated.
     * @param priceFeedTimeThreshold New threshold in seconds for price feed update times.
     */
    event PriceThresholdUpdated(uint256 priceFeedTimeThreshold);

    /**
     * @notice Emitted when native currency is retrieved from the contract.
     * @param amount The amount of native currency retrieved.
     */
    event NativeCurrencyRetrieved(uint256 amount);

    /**
     * @notice Emitted when ERC20 tokens are retrieved from the contract.
     * @param token The address of the ERC20 token retrieved.
     * @param amount The amount of tokens retrieved.
     */
    event TokensRetrieved(address token, uint256 amount);

    /**
     * @notice Emitted when tokens are purchased during the pre-sale.
     * @param user The address of the user who purchased the tokens.
     * @param ref The referral address provided.
     * @param amount The amount of native currency used for the purchase.
     * @param price The price of the token at the moment of purchase.
     * @param sold The number of tokens sold in the transaction.
     * @param round The current round of the sale during which the purchase was made.
     * @param investmentUSD The amount the user invested in USD.
     * @param currencyPrice The price of the currency during the purchase.
     * @param novaPoints The number of Nova Points awarded.
     */
    event TokensPurchased(
        address indexed user,
        address indexed ref,
        uint256 amount,
        uint256 price,
        uint256 sold,
        uint256 round,
        uint256 investmentUSD,
        int256 currencyPrice,
        uint256 novaPoints
    );

    /**
     * @notice Emitted when Nova Points are awarded to a user or referrer.
     * @param user The address of the user receiving the Nova Points.
     * @param points The number of Nova Points awarded.
     */
    event NovaPointsAwarded(address indexed user, uint256 points);

    /**
     * @notice Emitted when a referral is registered.
     * @param referrer The address of the referrer.
     */
    event ReferralRegistered(address indexed referrer);

    /**
     * @notice Thrown when trying to purchase with a currency that is not whitelisted.
     */
    error ErrCurrencyNotWhitelisted();

    /**
     * @notice Thrown when attempting an operation while the sale is not active.
     */
    error ErrSaleNotActive();

    /**
     * @notice Thrown when attempting to interact with a sale round that is closed.
     */
    error ErrRoundClosed();

    /**
     * @notice Thrown when a null address is provided where a valid address is required.
     */
    error ErrNullAddress();

    /**
     * @notice Thrown when an invalid decimals value is provided.
     */
    error ErrInvalidDecimals();

    /**
     * @notice Thrown when the `amount_` parameter is not 0 for native currency purchases.
     */
    error ErrAmountValidation();

    /**
     * @notice Thrown when `msg.value` is not 0 for ERC20 token purchases.
     */
    error ErrValueValidation();

    /**
     * @notice Thrown when the price threshold is set to an invalid value.
     */
    error ErrInvalidPriceThreshold();

    /**
     * @notice Thrown when the presale price is invalid (e.g., zero).
     */
    error ErrInvalidPrice();

    /**
     * @notice Thrown when an allocation error occurs in a sale round due to supply limits.
     */
    error ErrRoundAllocation();

    /**
     * @notice Thrown when the price feed update is beyond the acceptable time threshold.
     */
    error ErrPriceThreshold();

    /**
     * @notice Thrown when a user address provided is a null address.
     */
    error ErrUserNullAddress();

    /**
     * @notice Thrown when the native currency amount for a purchase is zero.
     */
    error ErrAmountZero();

    /**
     * @notice Thrown when an invalid referral is used.
     */
    error ErrReferral();

    /**
     * @notice Thrown when a transfer of funds fails.
     */
    error ErrTransferFailure();

    /**
     * @notice Thrown when the amount provided is below the minimum required.
     * @param amount_ The amount provided.
     * @param min_ The minimum required amount.
     */
    error ErrMin(uint256 amount_, uint256 min_);

    /**
     * @notice Thrown when the amount provided exceeds the maximum allowed.
     * @param amount_ The amount provided.
     * @param max_ The maximum allowed amount.
     */
    error ErrMax(uint256 amount_, uint256 max_);

    /**
     * @notice Initializes a new PresaleSNOVA contract with necessary configuration.
     * @dev Sets up roles, price feed interface, and initial thresholds.
     * Assigns the DEFAULT_ADMIN_ROLE to the deployer, ensuring control over critical functions.
     * @param storage_ Address of the TokenSaleRegistry, storing sale rounds and referral details.
     * @param priceThresholdSeconds_ Time threshold to validate the recency of price updates.
     */
    constructor(address payable storage_, uint256 priceThresholdSeconds_) {
        if (storage_ == address(0)) {
            revert ErrNullAddress();
        }
        if (priceThresholdSeconds_ == 0) {
            revert ErrInvalidPriceThreshold();
        }

        _presaleStorage = TokenSaleRegistry(storage_);
        _priceThresholdSeconds = priceThresholdSeconds_;

        _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
    }

    /**
     * @notice Adds a new currency and its associated price feed.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * Validates the `tokenAddress_` and `decimals_`.
     * @param tokenAddress_ The address of the ERC20 token.  Use `NATIVE_CURRENCY_ADDRESS` (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) to represent the native currency.
     * @param priceFeed_ The address of the new price feed, or zero address for static price.
     * @param decimals_ The decimals used by the currency.
     * @param useStaticPrice_ If true, use a static price of $1 instead of a price feed.
     * Reverts with `ErrNullAddress` if `tokenAddress_` is zero.
     * Reverts with `ErrInvalidDecimals` if `decimals_` is zero or greater than 18.
     */
    function addCurrency(
        address tokenAddress_,
        address priceFeed_,
        uint256 decimals_,
        bool useStaticPrice_
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (tokenAddress_ == address(0)) {
            revert ErrNullAddress();
        }
        if (decimals_ == 0 || decimals_ > 18) {
            revert ErrInvalidDecimals();
        }
        _addCurrency(tokenAddress_, priceFeed_, decimals_, useStaticPrice_);
    }

    /**
     * @notice Pauses the contract, preventing operations like token purchase.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     */
    function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _pause();
    }

    /**
     * @notice Unpauses the contract, allowing operations like token purchase to resume.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     */
    function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
        _unpause();
    }

    /**
     * @notice Purchases tokens using the specified currency directly sent to the contract.
     * @dev Validates the `tokenAddress_` to ensure it is not the zero address unless it's the native currency address.
     * @param ref_ Optional referral address provided by the user to potentially earn referral bonuses.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or the native currency address.
     * @param amount_ The amount of currency to be used for purchase. For native currency, this should be 0 as `msg.value` is used.
     * @notice Reverts with `ErrNullAddress` if `tokenAddress_` is the zero address and not the native currency address.
     * Reverts if the currency is not whitelisted, the sale is not active, or the round is closed.
     */
    function purchaseTokens(address ref_, address tokenAddress_, uint256 amount_) external payable nonReentrant {
        if (tokenAddress_ == address(0)) {
            revert ErrNullAddress();
        }
        if (_currencies[tokenAddress_].decimals == 0) {
            revert ErrCurrencyNotWhitelisted();
        }
        if (tokenAddress_ == NATIVE_CURRENCY_ADDRESS) {
            if (amount_ != 0) {
                revert ErrAmountValidation();
            }
            _processPurchase(_msgSender(), ref_, tokenAddress_, msg.value, false);
        } else {
            if (msg.value != 0) {
                revert ErrValueValidation();
            }
            _processPurchase(_msgSender(), ref_, tokenAddress_, amount_, false);
        }
    }

    /**
     * @notice Enables a designated purchase agent to buy tokens on behalf of another user using the specified currency sent with the transaction.
     * This action must comply with the terms set for the current sale round in the TokenSaleRegistry.
     * @dev This function can be invoked by any user possessing the `PURCHASE_AGENT_ROLE` when the contract is not paused.
     * It is designed to facilitate purchases where the actual buyer cannot interact directly with the contract.
     * @param user_ The address of the user for whom the tokens are being purchased.
     * @param ref_ Optional referral address provided to potentially earn referral bonuses.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or zero address for native currency.
     * @param amount_ The amount of currency to be used for purchase. For native currency, this should be 0 as `msg.value` is used.
     * @notice Reverts if the currency is not whitelisted, the sale is not active, or the round is closed.
     */
    function purchaseTokensFor(
        address user_,
        address ref_,
        address tokenAddress_,
        uint256 amount_
    ) external payable onlyRole(PURCHASE_AGENT_ROLE) nonReentrant {
        if (_currencies[tokenAddress_].decimals == 0) {
            revert ErrCurrencyNotWhitelisted();
        }

        if (tokenAddress_ == NATIVE_CURRENCY_ADDRESS) {
            if (amount_ != 0) {
                revert ErrAmountValidation();
            }
            _processPurchase(user_, ref_, tokenAddress_, msg.value, true);
        } else {
            if (msg.value != 0) {
                revert ErrValueValidation();
            }
            _processPurchase(user_, ref_, tokenAddress_, amount_, true);
        }
    }

    /**
     * @notice Updates the time threshold for considering the price feed valid.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param priceThresholdSeconds_ The new time threshold in seconds.
     * Emits a {PriceThresholdUpdated} event on successful update.
     */
    function setPriceThreshold(uint256 priceThresholdSeconds_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (priceThresholdSeconds_ == 0) {
            revert ErrInvalidPriceThreshold();
        }
        _priceThresholdSeconds = priceThresholdSeconds_;
        emit PriceThresholdUpdated(priceThresholdSeconds_);
    }

    /**
     * @notice Retrieves native currency sent to the contract.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @notice Requires successful transfer to the caller.
     * Emits a {NativeCurrencyRetrieved} event on successful retrieval.
     */
    function retrieveNativeCurrency() external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
        uint256 balance = address(this).balance;
        Address.sendValue(payable(_msgSender()), balance);
        emit NativeCurrencyRetrieved(balance);
    }

    /**
     * @notice Retrieves ERC20 tokens sent to the contract.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param token_ The address of the ERC20 token to retrieve.
     * @param amount_ The amount of tokens to retrieve.
     * Emits a {TokensRetrieved} event on successful retrieval.
     */
    function retrieveTokens(address token_, uint256 amount_) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
        IERC20(token_).safeTransfer(_msgSender(), amount_);
        emit TokensRetrieved(token_, amount_);
    }

    /**
     * @notice Retrieves the address of the token sale storage contract.
     * @dev Returns the current address stored in `_presaleStorage`.
     * @return address The address of the token sale registry.
     */
    function getStorage() external view returns (address) {
        return address(_presaleStorage);
    }

    /**
     * @notice Returns the total amount of token or native currency collected through sales.
     * @dev Accesses the Currency from `_currencies` to provide the total collected funds.
     * @return uint256 The total amount of token or native currency collected.
     */
    function getTotalCollected(address tokenAddress_) external view returns (uint256) {
        Currency memory currency = _currencies[tokenAddress_];
        return currency.totalCollected;
    }

    /**
     * @notice Gets the current threshold for price updates, in seconds.
     * @dev Returns the time period in seconds that is considered acceptable for a price update delay.
     * @return uint256 The current price update threshold in seconds.
     */
    function getPriceThreshold() external view returns (uint256) {
        return _priceThresholdSeconds;
    }

    /**
     * @notice Returns the referral count for a user.
     * @param user_ The address of the user to retrieve the referral count for.
     * @return uint256 The referral count for the specified user.
     */
    function getReferralCount(address user_) external view returns (uint256) {
        return _referralCount[user_];
    }

    /**
     * @notice Retrieves the address of the price feed contract used for pricing information.
     * @dev Returns the current address stored in `_currencies`.
     * @param tokenAddress_ The address of the ERC20 token used for price feed, or zero address for native currency.
     * @return address The address of the price feed contract.
     */
    function getPriceFeed(address tokenAddress_) external view returns (address) {
        return address(_currencies[tokenAddress_].priceFeed);
    }

    /**
     * @notice Returns the Nova Points balance for a user.
     * @param user_ The address of the user to retrieve the Nova Points balance for.
     * @return uint256 The Nova Points balance for the specified user.
     */
    function getNovaPoints(address user_) external view returns (uint256) {
        return _novaPoints[user_];
    }

    /**
     * @notice Adds a new currency and its associated price feed to the internal storage.
     * @param tokenAddress_ The address of the ERC20 token to be added as a new currency.
     *                      Use `NATIVE_CURRENCY_ADDRESS` (0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) to represent the native currency.
     * @param priceFeed_ The address of the `AggregatorV3Interface` price feed contract.
     *                    If `useStaticPrice_` is `true`, this can be the zero address.
     *                    For the native currency, a valid price feed should be provided unless `useStaticPrice_` is `true`.
     * @param decimals_ The number of decimals the currency uses. Typically aligns with the ERC20 token's decimals.
     *                  For the native currency, use the standard decimal representation (e.g., 18 for Ether).
     * @param useStaticPrice_ Determines whether to use a static price of $1 for the currency instead of fetching from a price feed.
     */
    function _addCurrency(address tokenAddress_, address priceFeed_, uint256 decimals_, bool useStaticPrice_) internal {
        _currencies[tokenAddress_] = Currency(AggregatorV3Interface(priceFeed_), decimals_, useStaticPrice_, 0);
    }

    /**
     * @dev Internal function to handle the purchase of tokens during the pre-sale.
     * This function orchestrates several key operations:
     * - Validation of the input parameters and state conditions to ensure the purchase can proceed.
     * - Interaction with the TokenSaleRegistry to retrieve and validate the current sale round.
     * - Calculation of the number of tokens that can be bought based on the native currency provided and the current token price.
     * - Handling of referral rewards if a valid referral is provided.
     * - Transfer of funds to the treasury and issuance of tokens and referral rewards.
     * - Calculation and awarding of Nova Points to the user.
     * - Calculation and awarding of Nova Points to the referrer, if applicable.
     * Each step involves checks and balances to ensure transaction integrity and security.
     * @param user_ The address of the user who is making the purchase.
     * @param ref_ Optional referral address that may entitle the referrer to rewards, if applicable.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or zero address for native currency.
     * @param amount_ The amount of currency to be used for purchase.
     * @param max_ Indicates whether the transaction should respect the maximum limit for contributions.
     * @return uint256 The number of tokens that were sold to the user.
     * Emits a {TokensPurchased} event upon successful completion of the purchase.
     * Emits a {NovaPointsAwarded} event when Nova Points are awarded to the user and the referrer.
     * @notice Reverts if the contract is paused, `user_` is a null address, the amount is zero, the sale is not active,
     * the sale round is closed, or the funds transfer fails.
     */
    function _processPurchase(
        address user_,
        address ref_,
        address tokenAddress_,
        uint256 amount_,
        bool max_
    ) internal whenNotPaused returns (uint256) {
        _validatePurchaseParameters(user_, ref_, amount_);
        TokenSaleRegistry.Round memory round = _getAndValidateSaleRound();
        uint256 tokensToSell = _calculateTokensToSell(amount_, tokenAddress_, round);
        uint256 funds = _calculateFundsInUSD(tokenAddress_, amount_);
        _validateFundsAndLimits(user_, funds, max_);

        ref_ = _handleReferral(user_, ref_);

        Currency storage currency = _currencies[tokenAddress_];
        int256 currencyPrice = _getCurrencyPrice(currency);

        (address ref, uint256 coinFunds, uint256 tokenFunds) = _calculateReferralRewards(
            user_,
            ref_,
            amount_,
            tokenAddress_
        );
        _transferPurchaseFunds(tokenAddress_, amount_, coinFunds);

        _recordSale(user_, tokenAddress_, funds, tokensToSell, ref_, coinFunds, tokenFunds);
        uint256 novaPoints = _awardNovaPoints(user_, funds);

        _updateCurrencyCollectedAmount(currency, amount_);

        _emitTokensPurchased(user_, ref, amount_, tokensToSell, funds, currencyPrice, novaPoints);
        _handleReferrerRewards(user_, ref, novaPoints);

        return tokensToSell;
    }

    /**
     * @dev Validates the input parameters for the purchase.
     * @param user_ The address of the user who is making the purchase.
     * @param ref_ The referral address provided by the user.
     * @param amount_ The amount of currency to be used for purchase.
     * @notice Reverts if the user address is null, user address equals referral address,
     * the amount is zero, or the sale is not active.
     */
    function _validatePurchaseParameters(address user_, address ref_, uint256 amount_) internal view {
        if (user_ == address(0)) revert ErrUserNullAddress();
        if (user_ == ref_) revert ErrReferral();
        if (amount_ == 0) revert ErrAmountZero();
        if (!_presaleStorage.isActive()) revert ErrSaleNotActive();
    }

    /**
     * @dev Retrieves and validates the current sale round from the TokenSaleRegistry.
     * @return TokenSaleRegistry.Round memory The current sale round.
     * @notice Reverts if the sale round is not started.
     */
    function _getAndValidateSaleRound() internal view returns (TokenSaleRegistry.Round memory) {
        TokenSaleRegistry.Round memory round = _presaleStorage.getRound(_presaleStorage.getCurrentRound());
        if (round.state != TokenSaleRegistry.State.Started) revert ErrRoundClosed();
        return round;
    }

    /**
     * @dev Calculates the number of tokens to sell based on the provided amount and token address.
     * @param amount_ The amount of currency to be used for purchase.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or zero address for native currency.
     * @param round The current sale round information.
     * @return uint256 The number of tokens to sell.
     * @notice Reverts if the round allocation is insufficient.
     */
    function _calculateTokensToSell(
        uint256 amount_,
        address tokenAddress_,
        TokenSaleRegistry.Round memory round
    ) internal view returns (uint256) {
        uint256 tokensToSell = _calculateTokensSold(amount_, tokenAddress_);
        if (round.supply < round.sold + tokensToSell) revert ErrRoundAllocation();
        return tokensToSell;
    }

    /**
     * @dev Validates the provided funds against the minimum and maximum limits.
     * @param user_ The address of the user who is making the purchase.
     * @param funds The amount of funds calculated in USD.
     * @param max_ Indicates whether the transaction should respect the maximum limit for contributions.
     * @notice Reverts if the funds are below the minimum or above the user's limit.
     */
    function _validateFundsAndLimits(address user_, uint256 funds, bool max_) internal view {
        if (_presaleStorage.getMin() > funds) revert ErrMin(funds, _presaleStorage.getMin());
        uint256 limit = max_ ? _presaleStorage.maxLimitOf(user_) : _presaleStorage.limitOf(user_);
        if (limit < funds) revert ErrMax(funds, limit);
    }

    /**
     * @dev Handles the referral logic by checking and updating the referral information.
     * @param user_ The address of the user who is making the purchase.
     * @param ref_ The referral address provided by the user.
     * @return address The updated referral address.
     */
    function _handleReferral(address user_, address ref_) internal returns (address) {
        if (_hasPurchased[user_]) {
            ref_ = _referrer[user_];
        } else {
            _referrer[user_] = ref_;
        }
        return ref_;
    }

    /**
     * @dev Retrieves the current price of the currency.
     * @param currency The currency information.
     * @return int256 The current price of the currency.
     */
    function _getCurrencyPrice(Currency storage currency) internal view returns (int256) {
        return currency.useStaticPrice ? int256(1e8) : _getLatestPrice(currency.priceFeed);
    }

    /**
     * @dev Records the sale by processing and recording the sale details in the presale storage.
     * @param user_ The address of the user who is making the purchase.
     * @param tokenAddress_ The address of the ERC20 token used for purchase.
     * @param funds The amount of funds calculated in USD.
     * @param tokensToSell The number of tokens to be sold.
     * @param ref_ The referral address.
     * @param coinFunds The funds associated with the referral in coins.
     * @param tokenFunds The funds associated with the referral in tokens.
     */
    function _recordSale(
        address user_,
        address tokenAddress_,
        uint256 funds,
        uint256 tokensToSell,
        address ref_,
        uint256 coinFunds,
        uint256 tokenFunds
    ) internal {
        _presaleStorage.processAndRecordSale(user_, tokenAddress_, funds, tokensToSell, ref_, coinFunds, tokenFunds);
    }

    /**
     * @dev Awards Nova Points to the user based on the provided funds.
     * @param user_ The address of the user who is making the purchase.
     * @param funds The amount of funds calculated in USD.
     * @return uint256 The number of Nova Points awarded to the user.
     */
    function _awardNovaPoints(address user_, uint256 funds) internal returns (uint256) {
        uint256 novaPoints = _calculateNovaPoints(funds);
        _novaPoints[user_] += novaPoints;
        return novaPoints;
    }

    /**
     * @dev Updates the total collected amount for the given currency.
     * @param currency The currency information.
     * @param amount_ The amount to be added to the total collected amount.
     */
    function _updateCurrencyCollectedAmount(Currency storage currency, uint256 amount_) internal {
        currency.totalCollected += amount_;
    }

    /**
     * @dev Emits the TokensPurchased and NovaPointsAwarded events.
     * @param user_ The address of the user who is making the purchase.
     * @param ref The referral address.
     * @param amount_ The amount of currency used for purchase.
     * @param tokensToSell The number of tokens sold.
     * @param funds The amount of funds calculated in USD.
     * @param currencyPrice The current price of the currency.
     * @param novaPoints The number of Nova Points awarded to the user.
     */
    function _emitTokensPurchased(
        address user_,
        address ref,
        uint256 amount_,
        uint256 tokensToSell,
        uint256 funds,
        int256 currencyPrice,
        uint256 novaPoints
    ) internal {
        uint256 snovaPrice = _presaleStorage.getPrice();
        emit TokensPurchased(
            user_,
            ref,
            amount_,
            snovaPrice,
            tokensToSell,
            _presaleStorage.getCurrentRound(),
            funds,
            currencyPrice,
            novaPoints
        );
        emit NovaPointsAwarded(user_, novaPoints);
    }

    /**
     * @dev Handles the rewards for the referrer by awarding Nova Points and updating referral information.
     * @param user_ The address of the user who is making the purchase.
     * @param ref The referral address.
     * @param novaPoints The number of Nova Points awarded to the user.
     */
    function _handleReferrerRewards(address user_, address ref, uint256 novaPoints) internal {
        if (ref != address(0)) {
            uint256 referrerNovaPoints = (novaPoints * 20) / 100;
            _novaPoints[ref] += referrerNovaPoints;
            emit NovaPointsAwarded(ref, referrerNovaPoints);
            if (!_hasPurchased[user_]) {
                _hasPurchased[user_] = true;
                _referralCount[ref] += 1;
                emit ReferralRegistered(ref);
            }
        }
    }

    /**
     * @dev Retrieves the latest price from the price feed and ensures the data is recent and valid.
     * Adds a check to ensure the price is greater than zero.
     * @param priceFeed The price feed contract.
     * @return int256 The latest price.
     * @notice Reverts with `ErrPriceThreshold` if the price feed update is beyond the acceptable time threshold.
     * Reverts with `ErrInvalidPrice` if the price is zero or negative.
     */
    function _getLatestPrice(AggregatorV3Interface priceFeed) internal view returns (int256) {
        (, int256 price, , uint256 updatedAt, ) = priceFeed.latestRoundData();
        if (block.timestamp - updatedAt > _priceThresholdSeconds) {
            revert ErrPriceThreshold();
        }
        if (price <= 0) {
            revert ErrInvalidPrice();
        }
        return price;
    }

    /**
     * @dev Converts a specified amount of tokens (native currency, USDT, USDC, or DAI) into its equivalent value in USD.
     * This conversion is based on the latest available price of the native currency in terms of USD.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or zero address for native currency.
     * @param amount_ The amount of tokens to be converted.
     * @return uint256 The equivalent amount in USD.
     */
    function _calculateFundsInUSD(address tokenAddress_, uint256 amount_) internal view returns (uint256) {
        Currency storage currency = _currencies[tokenAddress_];
        uint8 decimals = currency.useStaticPrice ? 8 : currency.priceFeed.decimals();
        int256 price = currency.useStaticPrice ? int256(1e8) : _getLatestPrice(currency.priceFeed);

        uint256 amountAdjusted = currency.decimals == 6 ? amount_ * 1e12 : amount_;

        return (amountAdjusted * uint256(price)) / (10 ** decimals);
    }

    /**
     * @dev Calculates the number of tokens that can be purchased with a given amount of currency.
     * Includes a check to prevent division by zero if the presale price is zero.
     * @param amount_ The amount of currency provided for the purchase.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or the native currency address.
     * @return uint256 The calculated number of tokens that can be bought with the specified amount of currency.
     * @notice Reverts with `ErrInvalidPrice` if the presale price is zero.
     */
    function _calculateTokensSold(uint256 amount_, address tokenAddress_) internal view returns (uint256) {
        Currency storage currency = _currencies[tokenAddress_];
        uint8 decimals = currency.useStaticPrice ? 8 : currency.priceFeed.decimals();
        int256 price = currency.useStaticPrice ? int256(1e8) : _getLatestPrice(currency.priceFeed);

        uint256 amountAdjusted = currency.decimals == 6 ? amount_ * 1e12 : amount_;
        uint256 presalePrice = _presaleStorage.getPrice();

        if (presalePrice == 0) {
            revert ErrInvalidPrice();
        }

        return (amountAdjusted * uint256(price) * 1e18) / (presalePrice * (10 ** decimals));
    }

    /**
     * @dev Calculates the referral rewards based on the purchase amount and the rates applicable to the referrer.
     * Handles different decimals for different tokens.
     * @param user_ The user who made the purchase.
     * @param ref_ The referral address.
     * @param amount_ The amount of currency used in the purchase.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or zero address for native currency.
     * @return address The effective referral address.
     * @return uint256 The amount of native currency as a referral reward.
     * @return uint256 The amount of tokens as a referral reward.
     */
    function _calculateReferralRewards(
        address user_,
        address ref_,
        uint256 amount_,
        address tokenAddress_
    ) internal view returns (address, uint256, uint256) {
        address ref = _presaleStorage.getRef(user_, ref_);
        if (ref == address(0)) {
            return (ref, 0, 0);
        }

        (uint256 fRate, uint256 sRate) = _presaleStorage.getRefRates(ref);

        uint256 coinFunds = (amount_ * fRate) / 1000;
        uint256 tokenFunds = (amount_ * sRate) / 1000;

        uint256 tokenSold = _calculateTokensSold(tokenFunds, tokenAddress_);

        return (ref, coinFunds, tokenSold);
    }

    /**
     * @dev Transfers the purchase funds and referral rewards to the appropriate recipients.
     *      Handles different decimal places for currencies and ensures precise calculations.
     * @param tokenAddress_ The address of the ERC20 token used for purchase, or zero address for native currency.
     * @param amount_ The total amount of the currency used for purchase.
     * @param reward_ The amount of the currency to be transferred as a referral reward.
     */
    function _transferPurchaseFunds(address tokenAddress_, uint256 amount_, uint256 reward_) internal {
        address treasury = _presaleStorage.getFundsWallet();

        if (tokenAddress_ != NATIVE_CURRENCY_ADDRESS) {
            IERC20(tokenAddress_).safeTransferFrom(_msgSender(), treasury, amount_ - reward_);

            if (reward_ > 0) {
                IERC20(tokenAddress_).safeTransferFrom(_msgSender(), address(_presaleStorage), reward_);
            }
        } else {
            Address.sendValue(payable(treasury), amount_ - reward_);

            if (reward_ > 0) {
                Address.sendValue(payable(address(_presaleStorage)), reward_);
            }
        }
    }

    /**
     * @notice Calculates the number of Nova Points awarded based on the investment amount in USD.
     * @dev The investment amount is in USD and the multipliers are predefined for different investment ranges.
     * @param investment_ The investment amount in USD (in 18 decimal places).
     * @return The number of Nova Points awarded.
     */
    function _calculateNovaPoints(uint256 investment_) internal pure returns (uint256) {
        uint256 multiplier = 0;
        if (investment_ >= 20000 * 1e18) {
            multiplier = 20;
        } else if (investment_ >= 15000 * 1e18) {
            multiplier = 16;
        } else if (investment_ >= 10000 * 1e18) {
            multiplier = 13;
        } else if (investment_ >= 5000 * 1e18) {
            multiplier = 10;
        } else if (investment_ >= 1000 * 1e18) {
            multiplier = 9;
        } else if (investment_ >= 500 * 1e18) {
            multiplier = 8;
        } else if (investment_ >= 250 * 1e18) {
            multiplier = 7;
        } else if (investment_ >= 50 * 1e18) {
            multiplier = 6;
        }

        return (investment_ * multiplier) / 1e18;
    }

    /**
     * @dev Fallback function to allow the contract to receive Ether directly.
     */
    receive() external payable {}
}

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

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

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

  function version() external view returns (uint256);

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

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

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

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

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

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

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

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

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

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

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

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

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

        _revokeRole(role, callerConfirmation);
    }

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

// 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 6 of 20 : 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 7 of 20 : 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";

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

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

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

// 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 12 of 20 : 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);
}

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

pragma solidity ^0.8.20;

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

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

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

// 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 16 of 20 : 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))
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

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

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

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

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

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

// 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 20 of 20 : TokenSaleRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";

/**
 * @title Token Sale Registry
 * @dev Manages the lifecycle of token sale rounds, including referral programs and fund allocation.
 * This contract allows for the configuration of sale rounds, referral rates, and the claiming of referral rewards.
 * It implements AccessControl for administrative actions and utilizes SafeERC20 for token interactions.
 */
contract TokenSaleRegistry is AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;
    using Address for address payable;

    /**
     * @notice Tracks the state of the token sale.
     * @dev Used to manage the lifecycle stages of a sale round within the contract.
     * @param Reset Initial state, no sale is active.
     * @param Started Sale round has started and is currently active.
     * @param Ended Sale round has completed, and no further sales are possible.
     */
    enum State {
        Reset,
        Started,
        Ended
    }

    /**
     * @notice Structure representing a sale round within the token sale.
     * @dev Stores details pertinent to a single round of the sale.
     * @param defined Boolean indicating if the round is defined, used to check initialization.
     * @param state Current state of the round, corresponding to the State enum.
     * @param sold Total number of tokens sold in this round.
     * @param supply Total number of tokens available for sale in this round.
     */
    struct Round {
        bool defined;
        State state;
        uint256 price;
        uint256 sold;
        uint256 supply;
    }

    /**
     * @notice Details about a referral account used in the token sale.
     * @dev Tracks whether a referral is active and the rates applicable for commission.
     * @param defined Boolean indicating if the referral account is set up in the system.
     * @param enabled Boolean indicating if the referral account is currently enabled.
     * @param primaryRefRate Referral rate for direct referrals, expressed as a percentage of the sale.
     * @param secondaryRefRate Referral rate for secondary referrals, affecting indirect sales influence.
     */
    struct Referral {
        bool defined;
        bool enabled;
        uint256 primaryRefRate;
        uint256 secondaryRefRate;
    }

    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
    address internal constant NATIVE_CURRENCY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    address internal constant TOKEN = 0x0000000000000000000000000000000000000001;
    uint256 internal constant MAX_ALLOCATION = 1e25;
    uint256 internal constant MIN_CONTRIBUTION = 49e18;

    address private _fundsManagementWallet;
    State private _state;

    Round[] private _rounds;
    uint256 private _currentRound;

    uint256 private _max;
    uint256 private _min;

    uint256 private _authLimit;
    mapping(address => bool) private _auth;

    uint256 private _primaryRefRate = 150;
    uint256 private _secondaryRefRate = 50;

    uint256 private _totalSold;
    mapping(address => uint256) private _funds;
    mapping(address => mapping(uint256 => uint256)) private _balances;

    mapping(address => Referral) private _refs;
    mapping(address => address) private _refsUsers;
    mapping(address => mapping(address => uint256)) private _refsBalances;

    /**
     * @notice Emitted when the state of the token sale is updated.
     * @param state The new state of the token sale.
     */
    event StateUpdated(State state);

    /**
     * @notice Emitted when a new sale round starts.
     * @param round The index of the sale round that has started.
     */
    event SaleRoundStarted(uint256 indexed round);

    /**
     * @notice Emitted when a sale round ends.
     * @param round The index of the sale round that has ended.
     */
    event SaleRoundEnded(uint256 indexed round);

    /**
     * @notice Emitted when a new sale round is configured.
     * @param price The price per token.
     * @param supply The total supply of tokens for the round.
     */
    event SaleRoundConfigured(uint256 price, uint256 supply);

    /**
     * @notice Emitted when the pricing of a sale round is adjusted.
     * @param round The index of the sale round.
     * @param price The new price per token.
     */
    event SaleRoundPricingAdjusted(uint256 indexed round, uint256 price);

    /**
     * @notice Emitted when the token supply for a sale round is adjusted.
     * @param round The index of the sale round.
     * @param supply The new total supply for the round.
     */
    event SaleRoundSupplyAdjusted(uint256 indexed round, uint256 supply);

    /**
     * @notice Emitted when native currency is retrieved from the contract.
     * @param amount The amount of native currency retrieved.
     */
    event NativeCurrencyRetrieved(uint256 amount);

    /**
     * @notice Emitted when ERC20 tokens are retrieved from the contract.
     * @param token The address of the ERC20 token retrieved.
     * @param amount The amount of tokens retrieved.
     */
    event TokensRetrieved(address token, uint256 amount);

    /**
     * @notice Emitted when the authorization threshold for participants is updated.
     * @param limit The new authorization limit.
     */
    event AuthorizationThresholdUpdated(uint256 limit);

    /**
     * @notice Emitted when a user's authorization status is updated.
     * @param user The address of the user.
     * @param value The new authorization value (true for authorized, false for not authorized).
     */
    event AuthUserUpdated(address indexed user, bool value);

    /**
     * @notice Emitted when the maximum contribution limit is updated.
     * @param amount The new maximum contribution limit.
     */
    event MaxUpdated(uint256 amount);

    /**
     * @notice Emitted when the minimum contribution limit is updated.
     * @param amount The new minimum contribution limit.
     */
    event MinUpdated(uint256 amount);

    /**
     * @notice Emitted when the funds management wallet address is updated.
     * @param fundsManagementWallet The new funds management wallet address.
     */
    event FundsManagementWalletUpdated(address indexed fundsManagementWallet);

    /**
     * @notice Emitted when referral rates are configured.
     * @param primaryRefRate The primary referral rate.
     * @param secondaryRefRate The secondary referral rate.
     */
    event ReferralRatesConfigured(uint256 primaryRefRate, uint256 secondaryRefRate);

    /**
     * @notice Emitted when a new referral account is initialized.
     * @param ref The address of the referral.
     * @param primaryRefRate The primary referral rate for this account.
     * @param secondaryRefRate The secondary referral rate for this account.
     */
    event ReferralAccountInitialized(address indexed ref, uint256 primaryRefRate, uint256 secondaryRefRate);

    /**
     * @notice Emitted when a referral account is enabled.
     * @param ref The address of the referral account that was enabled.
     */
    event ReferralEnabled(address indexed ref);

    /**
     * @notice Emitted when a referral account is disabled.
     * @param ref The address of the referral account that was disabled.
     */
    event ReferralDisabled(address indexed ref);

    /**
     * @notice Emitted when referral rewards are claimed.
     * @param ref The address of the referral claiming the rewards.
     * @param token The token in which the rewards are claimed.
     * @param amount The amount of rewards claimed.
     */
    event ReferralRewardsClaimed(address indexed ref, address indexed token, uint256 amount);

    /**
     * @notice Thrown when an operation is attempted with invalid parameters.
     */
    error ErrInvalidParameters();

    /**
     * @notice Thrown when an operation is attempted to start a sale that has already been started.
     */
    error ErrSaleAlreadyStarted();

    /**
     * @notice Thrown when an operation is attempted on a sale that is not active.
     */
    error ErrSaleNotActive();

    /**
     * @notice Thrown when a zero address is used where a valid address is required.
     */
    error ErrNullAddress();

    /**
     * @notice Thrown when a specified sale round does not exist.
     * @param index_ The index of the sale round.
     */
    error ErrUndefinedSaleRound(uint256 index_);

    /**
     * @notice Thrown when an operation is attempted on a sale round that has already started.
     * @param index_ The index of the sale round.
     */
    error ErrRoundStarted(uint256 index_);

    /**
     * @notice Thrown when an invalid price is set (e.g., zero).
     */
    error ErrInvalidPrice();

    /**
     * @notice Thrown when an invalid supply is set (e.g., zero).
     */
    error ErrInvalidSupply();

    /**
     * @notice Thrown when an operation is attempted on a sale round that has already ended.
     * @param index_ The index of the sale round.
     */
    error ErrRoundEnded(uint256 index_);

    /**
     * @notice Thrown when there is insufficient supply in a sale round for an operation.
     * @param index_ The index of the sale round.
     */
    error ErrInsufficientRoundSupply(uint256 index_);

    /**
     * @notice Thrown when the amount provided is below the required minimum.
     * @param amount_ The amount provided.
     * @param min_ The minimum required amount.
     */
    error ErrMin(uint256 amount_, uint256 min_);

    /**
     * @notice Thrown when the amount provided exceeds the allowed maximum.
     * @param amount_ The amount provided.
     * @param max_ The maximum allowed amount.
     */
    error ErrMax(uint256 amount_, uint256 max_);

    /**
     * @notice Thrown when the authorization limit is set outside the allowed range.
     * @param limit_ The authorization limit.
     * @param min_ The minimum allowed limit.
     * @param max_ The maximum allowed limit.
     */
    error ErrAuthLimitOutsideAllowedRange(uint256 limit_, uint256 min_, uint256 max_);

    /**
     * @notice Thrown when the total of referral rates exceeds the limit of 100%.
     * @param rates_ The total referral rates.
     */
    error ErrReferralRatesExceedLimit(uint256 rates_);

    /**
     * @notice Thrown when an undefined referral account is referenced.
     * @param ref_ The referral account address.
     */
    error ErrUndefinedReferralAccount(address ref_);

    /**
     * @notice Thrown when trying to enable an already enabled referral account.
     * @param ref_ The referral account address.
     */
    error ErrReferralAlreadyEnabled(address ref_);

    /**
     * @notice Thrown when trying to disable a referral account that is not enabled.
     * @param ref_ The referral account address.
     */
    error ErrReferralNotEnabled(address ref_);

    /**
     * @notice Thrown when an empty list of tokens is used where it is not permitted.
     */
    error ErrEmptyTokenList();

    /**
     * @notice Thrown when a transfer of funds fails.
     */
    error ErrTransferFailure();

    /**
     * @notice Initializes the TokenSaleRegistry with the specified funds management wallet.
     * @param fundsManagementWallet_ The wallet that will manage the funds collected from token sales. Must be a non-zero address.
     * @dev Sets up the initial admin and operator roles and assigns them to the message sender. Ensures that the contract starts
     * in a predictable state.
     */
    constructor(address fundsManagementWallet_) {
        if (fundsManagementWallet_ == address(0)) {
            revert ErrNullAddress();
        }
        _fundsManagementWallet = fundsManagementWallet_;

        _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
        _grantRole(OPERATOR_ROLE, _msgSender());
    }

    /**
     * @notice Activates the token sale, allowing rounds to be configured and started.
     * @dev Transitions the contract state from 'Reset' to 'Started'. This change is crucial as it permits the creation and management
     * of sale rounds.
     * Reverts if attempting to activate when already active to prevent reinitialization of the sale process.
     * Emits a {StateUpdated} event on success.
     */
    function activateSale() external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_state != State.Reset) {
            revert ErrSaleAlreadyStarted();
        }
        _state = State.Started;

        emit StateUpdated(_state);
    }

    /**
     * @notice Deactivates the token sale, preventing any new rounds from starting.
     * @dev Sets the contract state to `Ended`. Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * Reverts if the contract is already inactive.
     * Emits a {StateUpdated} event on success.
     */
    function deactivateSale() external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (!isActive()) {
            revert ErrSaleNotActive();
        }
        _state = State.Ended;

        emit StateUpdated(_state);
    }

    /**
     * @notice Processes and records a sale transaction, distributing rewards if applicable.
     * @dev This function can only be called by an account with the `OPERATOR_ROLE`. It handles the processing of sales,
     * updates the total sold amount, participant's funds, and manages referral rewards if a valid referral is provided.
     * Refactoring involves separate functions for processing sales, recording, and updating referrals.
     * @param user_ The address of the user participating in the sale.
     * @param token_ The token in which the sale is conducted.
     * @param amount_ The amount of funds involved in the transaction.
     * @param sold_ The amount of tokens sold in this transaction.
     * @param ref_ The referral's address, if any.
     * @param primaryReward_ The 'SNOVA' reward amount for the referral.
     * @param secondaryReward_ The COIN reward amount based on the sale amount.
     */
    function processAndRecordSale(
        address user_,
        address token_,
        uint256 amount_,
        uint256 sold_,
        address ref_,
        uint256 primaryReward_,
        uint256 secondaryReward_
    ) external onlyRole(OPERATOR_ROLE) {
        processSale(user_, amount_, sold_);
        recordReferral(ref_);

        if (ref_ != address(0)) {
            updateReferralRewards(ref_, token_, primaryReward_, secondaryReward_);
        }
        _refsUsers[user_] = ref_;
    }

    /**
     * @notice Allows referral accounts to claim their accrued rewards for specified tokens.
     * @dev Can only be executed by the referral account itself. It transfers the accrued rewards for each token specified in the `tokens_` array.
     * @param tokens_ An array of token addresses for which to claim rewards.
     * Reverts if the caller has no rewards to claim for a specified token or if the referral account is not enabled.
     * Emits a {ReferralRewardsClaimed} event for each token with rewards being claimed.
     */
    function claimRef(address[] calldata tokens_) external nonReentrant {
        address ref_ = _msgSender();

        if (tokens_.length == 0) {
            revert ErrEmptyTokenList();
        }
        if (!_refs[ref_].defined) {
            revert ErrUndefinedReferralAccount(ref_);
        }
        if (!_refs[ref_].enabled) {
            revert ErrReferralNotEnabled(ref_);
        }

        for (uint256 i = 0; i < tokens_.length; i++) {
            address token = tokens_[i];
            uint256 balance = _refsBalances[ref_][token];

            if (balance == 0) {
                continue;
            }

            _refsBalances[ref_][token] = 0;

            if (token == NATIVE_CURRENCY_ADDRESS) {
                payable(ref_).sendValue(balance);
            } else {
                IERC20(token).safeTransfer(ref_, balance);
            }

            emit ReferralRewardsClaimed(ref_, token, balance);
        }
    }

    /**
     * @notice Configures a new sale round with specified prices and supply.
     * @dev Adds validation to prevent setting the price or supply to zero.
     * @param price_ The price for the 'SNOVA' token.
     * @param supply_ The total token supply for the round.
     * Reverts with `ErrInvalidPrice` if the price is zero.
     * Reverts with `ErrInvalidSupply` if the supply is zero.
     * Emits a {SaleRoundConfigured} event on success.
     */
    function configureSaleRound(uint256 price_, uint256 supply_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (isInactive()) {
            revert ErrSaleNotActive();
        }
        if (price_ == 0) {
            revert ErrInvalidPrice();
        }
        if (supply_ == 0) {
            revert ErrInvalidSupply();
        }
        _rounds.push(Round({defined: true, state: State.Reset, price: price_, sold: 0, supply: supply_}));

        emit SaleRoundConfigured(price_, supply_);
    }

    /**
     * @notice Sets the referral rates for primary and secondary referrals.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`. Rates are expressed in tenths of a percent (i.e., 10 equals 1%).
     * @param primaryRefRate_ The referral rate for primary referrals, determining the percentage of the sale amount credited as a reward.
     * @param secondaryRefRate_ The referral rate for secondary referrals, used to calculate secondary rewards based on the sale amount.
     * Emits a {ReferralRatesConfigured} event on success.
     */
    function configureReferralRates(
        uint256 primaryRefRate_,
        uint256 secondaryRefRate_
    ) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (isInactive()) {
            revert ErrSaleNotActive();
        }
        uint256 refRatesSum = primaryRefRate_ + secondaryRefRate_;
        if (refRatesSum > 1000) {
            revert ErrReferralRatesExceedLimit(refRatesSum);
        }
        _primaryRefRate = primaryRefRate_;
        _secondaryRefRate = secondaryRefRate_;

        emit ReferralRatesConfigured(_primaryRefRate, _secondaryRefRate);
    }

    /**
     * @notice Initializes referral accounts with specific primary and secondary referral rates.
     * @dev Configures each referral account provided in the `refs_` array with rates specified in `primaryRefRate_` and `secondaryRefRate_` arrays.
     *      This method should be used carefully as it directly affects the incentives structure.
     * @param refs_ Array of addresses to be set up as referral accounts.
     * @param primaryRefRate_ Array of primary referral rates corresponding to each address in `refs_`.
     * @param secondaryRefRate_ Array of secondary referral rates corresponding to each address in `refs_`.
     * Emits a {ReferralAccountInitialized} event for each referral account on success.
     */
    function initializeReferralAccounts(
        address[] calldata refs_,
        uint256[] calldata primaryRefRate_,
        uint256[] calldata secondaryRefRate_
    ) external onlyRole(OPERATOR_ROLE) {
        if (isInactive()) {
            revert ErrSaleNotActive();
        }
        if (refs_.length != primaryRefRate_.length || refs_.length != secondaryRefRate_.length) {
            revert ErrInvalidParameters();
        }
        for (uint256 index = 0; index < refs_.length; index++) {
            _refs[refs_[index]] = Referral({
                defined: true,
                enabled: true,
                primaryRefRate: primaryRefRate_[index],
                secondaryRefRate: secondaryRefRate_[index]
            });

            emit ReferralAccountInitialized(refs_[index], primaryRefRate_[index], secondaryRefRate_[index]);
        }
    }

    /**
     * @notice Adjusts the pricing for a specific sale round.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`. The round must exist and be in the `Reset` state.
     * Adds validation to prevent setting the price to zero.
     * @param index_ The index of the sale round to adjust.
     * @param price_ The new investment price.
     * Reverts with `ErrInvalidPrice` if the price is zero.
     * Reverts if the sale is not active, the round does not exist, or the round is not in the `Reset` state.
     * Emits a {SaleRoundPricingAdjusted} event on success.
     */
    function adjustRoundPricing(uint256 index_, uint256 price_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (isInactive()) {
            revert ErrSaleNotActive();
        }
        if (!_rounds[index_].defined) {
            revert ErrUndefinedSaleRound(index_);
        }
        if (_rounds[index_].state != State.Reset) {
            revert ErrRoundStarted(index_);
        }
        if (price_ == 0) {
            revert ErrInvalidPrice();
        }
        _rounds[index_].price = price_;

        emit SaleRoundPricingAdjusted(index_, price_);
    }

    /**
     * @notice Adjusts the supply for a specific sale round.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`. The round must exist and cannot be in the `Ended` state.
     * Adds validation to prevent setting the supply to zero.
     * @param index_ The index of the sale round to adjust.
     * @param supply_ The new supply for the round.
     * Reverts with `ErrInvalidSupply` if the supply is zero.
     * Reverts if the sale is not active, the round does not exist, or the round is in the `Ended` state.
     * Emits a {SaleRoundSupplyAdjusted} event on success.
     */
    function adjustRoundSupply(uint256 index_, uint256 supply_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (isInactive()) {
            revert ErrSaleNotActive();
        }
        if (!_rounds[index_].defined) {
            revert ErrUndefinedSaleRound(index_);
        }
        if (_rounds[index_].state == State.Ended) {
            revert ErrRoundEnded(index_);
        }
        if (_rounds[index_].sold > supply_) {
            revert ErrInsufficientRoundSupply(index_);
        }
        if (supply_ == 0) {
            revert ErrInvalidSupply();
        }
        _rounds[index_].supply = supply_;

        emit SaleRoundSupplyAdjusted(index_, supply_);
    }

    /**
     * @notice Starts a specific sale round, allowing tokens to be sold.
     * @dev Can only be called by an account with the `OPERATOR_ROLE`. The round must exist and be in the `Reset` state.
     * @param index_ The index of the sale round to start.
     * Reverts if the sale is not active, the round does not exist, or the round is not in the `Reset` state.
     * Emits a {SaleRoundStarted} event on success.
     */
    function startSaleRound(uint256 index_) external onlyRole(OPERATOR_ROLE) {
        if (!isActive()) {
            revert ErrSaleNotActive();
        }
        if (!_rounds[index_].defined) {
            revert ErrUndefinedSaleRound(index_);
        }
        if (_rounds[index_].state != State.Reset) {
            revert ErrRoundStarted(index_);
        }
        if (_rounds[_currentRound].state == State.Started) {
            _rounds[_currentRound].state = State.Ended;
        }
        _rounds[index_].state = State.Started;
        _currentRound = index_;

        emit SaleRoundStarted(index_);
    }

    /**
     * @notice Ends a specific sale round, stopping any further token sales.
     * @dev Can only be called by an account with the `OPERATOR_ROLE`. The round must exist and be in the `Started` state.
     * @param index_ The index of the sale round to end.
     * Reverts if the round does not exist or is not in the `Started` state.
     * Emits a {SaleRoundEnded} event on success.
     */
    function endSaleRound(uint256 index_) external onlyRole(OPERATOR_ROLE) {
        if (!_rounds[index_].defined) {
            revert ErrUndefinedSaleRound(index_);
        }
        if (_rounds[index_].state != State.Started) {
            revert ErrRoundEnded(index_);
        }
        _rounds[index_].state = State.Ended;

        emit SaleRoundEnded(index_);
    }

    /**
     * @notice Updates the maximum allocation allowed per participant.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param amount_ The new maximum allocation amount.
     * Reverts if `amount_` is greater than `MAX_ALLOCATION` or less than the current minimum contribution limit.
     * Emits a {MaxUpdated} event on success.
     */
    function updateMaximumAllocation(uint256 amount_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (amount_ > MAX_ALLOCATION) {
            revert ErrMax(amount_, MAX_ALLOCATION);
        }
        if (amount_ < _min) {
            revert ErrMin(amount_, _min);
        }
        _max = amount_;

        emit MaxUpdated(_max);
    }

    /**
     * @notice Updates the minimum contribution required to participate in the sale.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param amount_ The new minimum contribution amount.
     * Reverts if `amount_` is less than `MIN_CONTRIBUTION` or greater than the current maximum allocation limit.
     * Emits a {MinUpdated} event on success.
     */

    function updateMinimumContribution(uint256 amount_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (amount_ < MIN_CONTRIBUTION) {
            revert ErrMin(amount_, MIN_CONTRIBUTION);
        }
        if (amount_ > _max) {
            revert ErrMax(amount_, _max);
        }
        _min = amount_;

        emit MinUpdated(_min);
    }

    /**
     * @notice Sets the threshold for which participants are automatically authorized.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param amount_ The new authorization threshold amount.
     * Reverts if `amount_` is not within the bounds of the minimum and maximum contribution limits.
     * Emits an {AuthorizationThresholdUpdated} event on success.
     */
    function updateAuthorizationThreshold(uint256 amount_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_min > amount_ || amount_ > _max) {
            revert ErrAuthLimitOutsideAllowedRange(amount_, _min, _max);
        }
        _authLimit = amount_;

        emit AuthorizationThresholdUpdated(amount_);
    }

    /**
     * @notice Authorizes or deauthorizes a participant for the token sale.
     * @dev Can only be called by an account with the `OPERATOR_ROLE`.
     * @param user_ The address of the participant to authorize or deauthorize.
     * @param value_ A boolean where `true` authorizes the participant and `false` deauthorizes them.
     * Emits an {AuthUserUpdated} event on success.
     */
    function authorizeParticipant(address user_, bool value_) external onlyRole(OPERATOR_ROLE) {
        _auth[user_] = value_;

        emit AuthUserUpdated(user_, value_);
    }

    /**
     * @notice Batch authorizes or deauthorizes participants for the token sale.
     * @dev Can only be called by an account with the `OPERATOR_ROLE`.
     * @param users_ The addresses of the participants to authorize or deauthorize.
     * @param values_ An array of booleans where `true` authorizes and `false` deauthorizes the corresponding participant.
     * Reverts if the length of `users_` and `values_` arrays do not match.
     * Emits an {AuthUserUpdated} event for each participant on success.
     */

    function batchAuthorizeParticipants(
        address[] calldata users_,
        bool[] calldata values_
    ) external onlyRole(OPERATOR_ROLE) {
        if (users_.length != values_.length) {
            revert ErrInvalidParameters();
        }
        for (uint256 index = 0; index < users_.length; index++) {
            _auth[users_[index]] = values_[index];

            emit AuthUserUpdated(users_[index], values_[index]);
        }
    }

    /**
     * @notice Updates the wallet address used for managing funds collected from the sale.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param fundsManagementWallet_ The new funds management wallet address.
     * Reverts if `fundsManagementWallet_` is the zero address.
     * Emits a {FundsManagementWalletUpdated} event on success.
     */
    function updateFundsWallet(address fundsManagementWallet_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (fundsManagementWallet_ == address(0)) {
            revert ErrNullAddress();
        }
        _fundsManagementWallet = fundsManagementWallet_;

        emit FundsManagementWalletUpdated(fundsManagementWallet_);
    }

    /**
     * @notice Enables a referral account, allowing it to receive referral rewards.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`. Marks a referral as enabled.
     * @param ref_ The address of the referral account to enable.
     * Reverts if the referral account is already enabled or undefined.
     * Emits a {ReferralEnabled} event upon success.
     */
    function enableReferral(address ref_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (!_refs[ref_].defined) {
            revert ErrUndefinedReferralAccount(ref_);
        }
        if (_refs[ref_].enabled) {
            revert ErrReferralAlreadyEnabled(ref_);
        }
        _refs[ref_].enabled = true;

        emit ReferralEnabled(ref_);
    }

    /**
     * @notice Disables a referral account, preventing it from receiving further referral rewards.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`. Marks a referral as disabled.
     * @param ref_ The address of the referral account to disable.
     * Reverts if the referral account is already disabled or undefined.
     * Emits a {ReferralDisabled} event upon success.
     */
    function disableReferral(address ref_) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (!_refs[ref_].defined) {
            revert ErrUndefinedReferralAccount(ref_);
        }
        if (!_refs[ref_].enabled) {
            revert ErrReferralNotEnabled(ref_);
        }
        _refs[ref_].enabled = false;

        emit ReferralDisabled(ref_);
    }

    /**
     * @notice Retrieves native currency sent to the contract.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @notice Requires successful transfer to the caller.
     * Emits a {NativeCurrencyRetrieved} event on successful retrieval.
     */
    function retrieveNativeCurrency() external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
        uint256 balance = address(this).balance;
        Address.sendValue(payable(_msgSender()), balance);
        emit NativeCurrencyRetrieved(balance);
    }

    /**
     * @notice Retrieves ERC20 tokens sent to the contract.
     * @dev Can only be called by an account with the `DEFAULT_ADMIN_ROLE`.
     * @param token_ The address of the ERC20 token to retrieve.
     * @param amount_ The amount of tokens to retrieve.
     * Emits a {TokensRetrieved} event on successful retrieval.
     */
    function retrieveTokens(address token_, uint256 amount_) external onlyRole(DEFAULT_ADMIN_ROLE) nonReentrant {
        IERC20(token_).safeTransfer(_msgSender(), amount_);
        emit TokensRetrieved(token_, amount_);
    }

    /**
     * @notice Returns the address of the funds management wallet.
     * @dev Getter function for the address where the funds collected from the sales are managed.
     * @return The address of the funds management wallet.
     */
    function getFundsWallet() external view returns (address) {
        return _fundsManagementWallet;
    }

    /**
     * @notice Retrieves the maximum allowed allocation per participant in the token sale.
     * @dev This getter function provides the maximum amount a participant can contribute to the token sale.
     * @return The maximum allocation amount in the token sale's currency.
     */
    function getMax() external view returns (uint256) {
        return _max;
    }

    /**
     * @notice Retrieves the minimum required contribution for participating in the token sale.
     * @dev This getter function provides the minimum amount required to participate in the token sale.
     * @return The minimum contribution amount in the token sale's currency.
     */
    function getMin() external view returns (uint256) {
        return _min;
    }

    /**
     * @notice Provides detailed information about a specific sale round.
     * @dev Fetches round data, including prices and state, based on the round index provided.
     * @param index_ The index of the sale round to retrieve information for.
     * @return A `Round` struct containing details about the specified sale round.
     * Reverts if the round index is out of bounds.
     */
    function getRound(uint256 index_) external view returns (Round memory) {
        return _rounds[index_];
    }

    /**
     * @notice Returns the total number of sale rounds configured in the contract.
     * @dev Provides a count of how many rounds have been added to the sale, regardless of their state.
     * @return The total number of sale rounds.
     */
    function getRoundsCount() external view returns (uint256) {
        return _rounds.length;
    }

    /**
     * @notice Retrieves the identifier of the currently active sale round.
     * @dev This function provides the index of the currently active round. Rounds are indexed starting from 0.
     * @return The index of the currently active sale round.
     */
    function getCurrentRound() external view returns (uint256) {
        return _currentRound;
    }

    /**
     * @notice Retrieves the total amount of tokens sold across all rounds.
     * @dev Sums up the total tokens sold in all rounds to give a cumulative figure.
     * @return The total amount of tokens sold in the token sale.
     */
    function getTotalSold() external view returns (uint256) {
        return _totalSold;
    }

    /**
     * @notice Checks the amount of tokens a user has purchased in a specific sale round.
     * @dev Provides the number of tokens a given user has bought in a particular round.
     * @param user_ The address of the user.
     * @param round_ The index of the sale round.
     * @return The number of tokens purchased by the user in the specified round.
     */
    function balanceOf(address user_, uint256 round_) external view returns (uint256) {
        return _balances[user_][round_];
    }

    /**
     * @notice Retrieves the referral rewards balance for a user in a specific token.
     * @dev Indicates how much of a particular token a user has earned as referral rewards.
     * @param user_ The address of the user or referral.
     * @param token_ The token for which the referral balance is queried.
     * @return The referral rewards balance for the user in the specified token.
     */
    function refBalanceOf(address user_, address token_) external view returns (uint256) {
        return _refsBalances[user_][token_];
    }

    /**
     * @notice Retrieves the total amount of funds a user has contributed to the sale.
     * @dev Provides the cumulative contribution amount of a user across all sale rounds.
     * @param user_ The address of the user.
     * @return The total contribution amount of the user in the token sale's currency.
     */
    function getFundsOfUser(address user_) external view returns (uint256) {
        return _funds[user_];
    }

    /**
     * @notice Calculates the remaining allocation a user is allowed to contribute.
     * @dev Determines how much more a user can contribute based on their current contributions and the authorization limit.
     * @param user_ The address of the user.
     * @return The remaining amount the user is allowed to contribute.
     */
    function limitOf(address user_) external view returns (uint256) {
        uint256 amount = _funds[user_];
        uint256 limit = _authLimit;
        if (isAuth(user_)) {
            limit = _max;
        }
        return amount < limit ? limit - amount : 0;
    }

    /**
     * @notice Calculates the maximum limit a user can contribute based on their current contributions.
     * @dev Determines the maximum amount a user is still allowed to contribute towards the sale.
     * @param user_ The address of the participant.
     * @return The maximum remaining contribution amount for the user.
     */
    function maxLimitOf(address user_) external view returns (uint256) {
        uint256 amount = _funds[user_];
        return amount < _max ? _max - amount : 0;
    }

    /**
     * @notice Returns the authorization limit for participants.
     * @dev Provides the threshold above which users need special authorization to contribute.
     * @return The authorization limit for contributions.
     */
    function getAuthLimit() external view returns (uint256) {
        return _authLimit;
    }

    /**
     * @notice Determines the referral associated with a user or transaction.
     * @dev Identifies the referral, if any, responsible for a user's participation in the sale.
     * @param user_ The address of the user whose referral is to be identified.
     * @param ref_ A potential referral address provided by the user.
     * @return The address of the referral, if valid and enabled; otherwise, the zero address.
     */
    function getRef(address user_, address ref_) external view returns (address) {
        Referral memory ref = _refs[_refsUsers[user_]];
        if (ref.defined && ref.enabled) {
            return _refsUsers[user_];
        }
        ref = _refs[ref_];
        if (!ref.defined || ref.enabled) {
            return ref_;
        }
        return address(0);
    }

    /**
     * @notice Provides the detailed referral structure for a given referral account.
     * @dev Fetches detailed referral information, including rates and enabled status.
     * @param user_ The address of the referral account.
     * @return The `Referral` struct containing detailed information about the referral.
     */
    function getReferralStruct(address user_) external view returns (Referral memory) {
        return _refs[user_];
    }

    /**
     * @notice Retrieves the referral rates for a specific referral account.
     * @dev Provides the custom referral rates set for a specific referral, if defined; otherwise, returns the global rates.
     * @param ref_ The address of the referral account.
     * @return The primary and secondary referral rates for the specified account.
     */
    function getRefRates(address ref_) external view returns (uint256, uint256) {
        Referral memory ref = _refs[ref_];
        if (ref.defined) {
            return (Math.max(ref.primaryRefRate, _primaryRefRate), Math.max(ref.secondaryRefRate, _secondaryRefRate));
        }
        return (_primaryRefRate, _secondaryRefRate);
    }

    /**
     * @notice Retrieves global referral rates for the sale.
     * @dev Provides the default referral rates applied to all referrals unless overridden.
     * @return The primary and secondary referral rates.
     */
    function getGlobalRefRates() external view returns (uint256, uint256) {
        return (_primaryRefRate, _secondaryRefRate);
    }

    /**
     * @notice Checks if the token sale is currently active.
     * @dev Utility function to determine if the sale is in the `Started` state.
     * @return `true` if the sale is active, `false` otherwise.
     */
    function isActive() public view returns (bool) {
        return _state == State.Started;
    }

    /**
     * @notice Checks if the token sale is currently inactive or ended.
     * @dev Utility function to determine if the sale is in the `Ended` state.
     * @return `true` if the sale is inactive, `false` otherwise.
     */
    function isInactive() public view returns (bool) {
        return _state == State.Ended;
    }

    /**
     * @notice Retrieves the sale price for tokens.
     * @dev Provides the price for the currently active round.
     * @return The sale price per token for the currently active round.
     */
    function getPrice() public view returns (uint256) {
        if (_rounds[_currentRound].state == State.Started) {
            return _rounds[_currentRound].price;
        }
        return 0;
    }

    /**
     * @notice Checks if a user is authorized for '_max' contributions.
     * @dev Determines if a user has been marked as authorized to bypass the standard contribution limit.
     * @param user_ The address of the user to check.
     * @return `true` if the user is authorized, `false` otherwise.
     */
    function isAuth(address user_) public view returns (bool) {
        return _auth[user_];
    }

    /**
     * @dev Updates the internal accounting for the sale, including total funds received and tokens sold.
     * @param user_ The address of the user participating in the sale.
     * @param amount_ The amount of funds involved in the transaction.
     * @param sold_ The amount of tokens sold in this transaction.
     */
    function processSale(address user_, uint256 amount_, uint256 sold_) private {
        _funds[user_] += amount_;
        _totalSold += sold_;
        _rounds[_currentRound].sold += sold_;
        _balances[user_][_currentRound] += sold_;
    }

    /**
     * @dev Updates the referral rewards balances for the given referral.
     * @param ref_ The address of the referral.
     * @param token_ The token in which the sale is conducted.
     * @param primaryReward_ The 'SNOVA' reward amount for the referral.
     * @param secondaryReward_ The COIN reward amount based on the sale amount.
     */
    function updateReferralRewards(
        address ref_,
        address token_,
        uint256 primaryReward_,
        uint256 secondaryReward_
    ) private {
        _refsBalances[ref_][token_] += primaryReward_;
        _refsBalances[ref_][TOKEN] += secondaryReward_;
    }

    /**
     * @dev Handles referral initialization and updates the referral tracking if applicable.
     * @param ref_ The referral's address, if any.
     */
    function recordReferral(address ref_) private {
        if (ref_ != address(0) && !_refs[ref_].defined) {
            _refs[ref_].defined = true;
            _refs[ref_].enabled = true;
            emit ReferralAccountInitialized(ref_, _primaryRefRate, _secondaryRefRate);
        }
    }

    /**
     * @dev Fallback function to allow the contract to receive Ether directly.
     */
    receive() external payable {}
}

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

API
[{"inputs":[{"internalType":"address payable","name":"storage_","type":"address"},{"internalType":"uint256","name":"priceThresholdSeconds_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ErrAmountValidation","type":"error"},{"inputs":[],"name":"ErrAmountZero","type":"error"},{"inputs":[],"name":"ErrCurrencyNotWhitelisted","type":"error"},{"inputs":[],"name":"ErrInvalidDecimals","type":"error"},{"inputs":[],"name":"ErrInvalidPrice","type":"error"},{"inputs":[],"name":"ErrInvalidPriceThreshold","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount_","type":"uint256"},{"internalType":"uint256","name":"max_","type":"uint256"}],"name":"ErrMax","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount_","type":"uint256"},{"internalType":"uint256","name":"min_","type":"uint256"}],"name":"ErrMin","type":"error"},{"inputs":[],"name":"ErrNullAddress","type":"error"},{"inputs":[],"name":"ErrPriceThreshold","type":"error"},{"inputs":[],"name":"ErrReferral","type":"error"},{"inputs":[],"name":"ErrRoundAllocation","type":"error"},{"inputs":[],"name":"ErrRoundClosed","type":"error"},{"inputs":[],"name":"ErrSaleNotActive","type":"error"},{"inputs":[],"name":"ErrTransferFailure","type":"error"},{"inputs":[],"name":"ErrUserNullAddress","type":"error"},{"inputs":[],"name":"ErrValueValidation","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"NativeCurrencyRetrieved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"points","type":"uint256"}],"name":"NovaPointsAwarded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"priceFeedTimeThreshold","type":"uint256"}],"name":"PriceThresholdUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"referrer","type":"address"}],"name":"ReferralRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"ref","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"price","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sold","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"round","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"investmentUSD","type":"uint256"},{"indexed":false,"internalType":"int256","name":"currencyPrice","type":"int256"},{"indexed":false,"internalType":"uint256","name":"novaPoints","type":"uint256"}],"name":"TokensPurchased","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TokensRetrieved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PURCHASE_AGENT_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress_","type":"address"},{"internalType":"address","name":"priceFeed_","type":"address"},{"internalType":"uint256","name":"decimals_","type":"uint256"},{"internalType":"bool","name":"useStaticPrice_","type":"bool"}],"name":"addCurrency","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user_","type":"address"}],"name":"getNovaPoints","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress_","type":"address"}],"name":"getPriceFeed","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPriceThreshold","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user_","type":"address"}],"name":"getReferralCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getStorage","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenAddress_","type":"address"}],"name":"getTotalCollected","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"ref_","type":"address"},{"internalType":"address","name":"tokenAddress_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"purchaseTokens","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"user_","type":"address"},{"internalType":"address","name":"ref_","type":"address"},{"internalType":"address","name":"tokenAddress_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"purchaseTokensFor","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"retrieveNativeCurrency","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"retrieveTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"priceThresholdSeconds_","type":"uint256"}],"name":"setPriceThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

608034620000d157601f62002a0938819003918201601f19168301916001600160401b03831184841017620000d6578084926040948552833981010312620000d1578051906001600160a01b03821690818303620000d1576020015191600180556002549115620000bf578215620000ad576001600160a81b0319909116600891821b610100600160a81b031617600255556200009c33620000ec565b5060405161288b90816200017e8239f35b60405163e840a88d60e01b8152600490fd5b604051633eaa20b360e01b8152600490fd5b600080fd5b634e487b7160e01b600052604160045260246000fd5b6001600160a01b031660008181527fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5602052604081205490919060ff166200017957818052816020526040822081835260205260408220600160ff1982541617905533917f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d8180a4600190565b509056fe60806040818152600480361015610021575b505050361561001f57600080fd5b005b600092833560e01c90816301ffc9a71461095757508063248a9ca31461092e57806324acbd69146108f65780632f2ff15d146108cd5780633408f73a146108a057806334e8c679146107e657806336568abe1461079f5780633f4ba83a146107365780634fb52c70146106d25780635b6cca80146106975780635c975abb146106735780635dc52ff6146105815780635f31d92b146104b25780636dcf5ce114610493578063784bfa32146104585780637b1b901a146103fa5780638456cb591461039f5780638743c549146103325780638eecbfa81461020157806391d14854146101bc578063a217fddf1461019d578063d547741f1461015f5763df56867b03610011573461015b57602036600319011261015b5760209282916001600160a01b0361014d6109ab565b168252845220549051908152f35b8280fd5b50903461015b578060031936011261015b57610199913561019460016101836109c6565b938387528660205286200154610ab8565b610b7f565b5080f35b5050346101b857816003193601126101b85751908152602090f35b5080fd5b503461015b578160031936011261015b578160209360ff926101dc6109c6565b903582528186528282206001600160a01b039091168252855220549151911615158152f35b50919060803660031901126101b8576102186109ab565b906102216109c6565b604435916001600160a01b03831680840361032e57606435907f4d6ca2d030abc29757f11bdec506b9c196a27de798e9e9c57321409317dc0d0f8088528760205283882033895260205260ff8489205416156103105750610280610b5c565b808752600360205260018388200154156103005773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee036102d8576102c957506102c0939450349261175d565b505b6001805580f35b5163816565db60e01b81528590fd5b9390346102f157506102eb94955061175d565b506102c2565b5163d26bd23360e01b81528690fd5b82516343614f2760e01b81528890fd5b835163e2517d3f60e01b815233818b01526024810191909152604490fd5b8580fd5b5050346101b85760203660031901126101b857602091606091906001600160a01b03906003908390836103636109ab565b16815282875220835192610376846109dc565b815416835260018101548684015260ff6002820154161515848401520154928391015251908152f35b5050346101b857816003193601126101b85760207f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258916103dd610a60565b6103e5612372565b600160ff19600254161760025551338152a180f35b5050346101b857816003193601126101b85760207f6f5e7a5e558e349050c8a249c9443f579e68b88e8a3d287689ae6459a48a237a91610438610a60565b610440610b5c565b479061044c8233612272565b51908152a16001805580f35b5050346101b857816003193601126101b857602090517f4d6ca2d030abc29757f11bdec506b9c196a27de798e9e9c57321409317dc0d0f8152f35b5050346101b857816003193601126101b8576020906008549051908152f35b50919060603660031901126101b8576104c96109ab565b906104d26109c6565b906044356104de610b5c565b6001600160a01b038316801561057157808652600360205260018387200154156105615773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0361053e5761052f57506102c0929350349133610bf4565b5163816565db60e01b81528490fd5b92903461055257506102eb93945033610bf4565b5163d26bd23360e01b81528590fd5b82516343614f2760e01b81528790fd5b8251633eaa20b360e01b81528790fd5b509190346101b85760803660031901126101b85761059d6109ab565b906105a66109c6565b916044356064359182151580930361032e576105c0610a60565b6001600160a01b03908116938415610664578215801561065a575b61064c57600395969750818151976105f2896109dc565b16875260208701928352808701938452606087019488865288528560205287209551166bffffffffffffffffffffffff60a01b865416178555516001850155600284019051151560ff801983541691161790555191015580f35b5162b967f360e21b81528790fd5b50601283116105db565b51633eaa20b360e01b81528790fd5b5050346101b857816003193601126101b85760209060ff6002541690519015158152f35b5050346101b85760203660031901126101b8576020916001600160a01b03908290826106c16109ab565b168152600385522054169051908152f35b50903461015b57602036600319011261015b578135916106f0610a60565b82156107285750816020917f6b0695b82961d69699cb7b8438d7eac257041649a2d203c75aa4f54e13d1ecca9360085551908152a180f35b905163e840a88d60e01b8152fd5b503461015b578260031936011261015b5761074f610a60565b6002549060ff821615610791575060ff1916600255513381527f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa90602090a180f35b8251638dfc202b60e01b8152fd5b509190346101b857806003193601126101b8576107ba6109c6565b90336001600160a01b038316036107d75750610199919235610b7f565b5163334bd91960e11b81528390fd5b5050346101b857806003193601126101b8577fd5ccc4809a3c78442b501cf0eb58cdb32e19a527ed3d34b0458e2cc85d0bc2f9906108226109ab565b61089660243592610831610a60565b610839610b5c565b805163a9059cbb60e01b60208201523360248201526044808201869052815261087690610867606482610a3e565b6001600160a01b038516612316565b516001600160a01b03909216825260208201929092529081906040820190565b0390a16001805580f35b5050346101b857816003193601126101b857600254905160089190911c6001600160a01b03168152602090f35b50903461015b578060031936011261015b5761019991356108f160016101836109c6565b610ade565b5050346101b85760203660031901126101b85760209181906001600160a01b0361091e6109ab565b1681526005845220549051908152f35b503461015b57602036600319011261015b57816020936001923581528085522001549051908152f35b9250503461015b57602036600319011261015b573563ffffffff60e01b811680910361015b5760209250637965db0b60e01b811490811561099a575b5015158152f35b6301ffc9a760e01b14905038610993565b600435906001600160a01b03821682036109c157565b600080fd5b602435906001600160a01b03821682036109c157565b6080810190811067ffffffffffffffff8211176109f857604052565b634e487b7160e01b600052604160045260246000fd5b60a0810190811067ffffffffffffffff8211176109f857604052565b67ffffffffffffffff81116109f857604052565b90601f8019910116810190811067ffffffffffffffff8211176109f857604052565b3360009081527fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5602052604081205460ff1615610a9a5750565b6044906040519063e2517d3f60e01b82523360048301526024820152fd5b80600052600060205260406000203360005260205260ff6040600020541615610a9a5750565b9060009180835282602052604083209160018060a01b03169182845260205260ff60408420541615600014610b5757808352826020526040832082845260205260408320600160ff198254161790557f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d339380a4600190565b505090565b600260015414610b6d576002600155565b604051633ee5aeb560e01b8152600490fd5b9060009180835282602052604083209160018060a01b03169182845260205260ff604084205416600014610b575780835282602052604083208284526020526040832060ff1981541690557ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b339380a4600190565b9092610bfe612372565b6001600160a01b0382161561174b576001600160a01b0382811690851614611739578015611727576002546040516308bcf8b560e21b8152909390602081600481600889901c6001600160a01b03165afa90811561120c576000916116ed575b50156116db5760006080604051610c7481610a0e565b82815282602082015282604082015282606082015201526040519463a32bf59760e01b865260208660048160018060a01b038960081c165afa95861561120c576000966116a7575b5060405163023c4c9f60e61b8152600481019690965260a086602481600889901c6001600160a01b03165afa95861561120c57600096611625575b506020860151600381101561160f576001036115fd57610d178284612567565b95610d2b876060608084015193015161239d565b116115eb576001600160a01b0382166000908152600360205260409020600281015460ff168015611581576008905b1561156157600660016305f5e100935b0154036115515764e8d4a5100091858381020483036111c257610d95610d9b91610da19488026123c3565b916123d6565b906123e7565b60405163d6362e9760e01b80825291969190602081600481600887901c6001600160a01b03165afa801561120c57889160009161151c575b501161149c575060405163151a8b2960e21b81526001600160a01b03868116600483015290916020918391602491839160081c165afa90811561120c5760009161146a575b5085811061144c57506001600160a01b038416600090815260066020526040902054819060ff161561141f5750506001600160a01b0383811660009081526007602052604090205416915b6001600160a01b0382166000908152600360205260409020600281015490939060ff1615611405576305f5e100905b610ea484848389612426565b60025460405163cb69a03f60e01b815293979293906020908290600490829060081c6001600160a01b03165afa90811561120c576000916113d6575b506001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1461139957610f2490610f13858961255a565b90336001600160a01b03861661280c565b82611373575b60025460081c6001600160a01b031692833b156109c157604051636d81c97960e01b81526001600160a01b038b811660048301529384166024820152604481018c9052606481018d905294909216608485015260a484019190915260c4830152600090829060e490829084905af1801561120c57611364575b50600069043c33c1937564800000871061124f57506003670de0b6b3a7640000610fcf60145b896123c3565b049460018060a01b03871660005260046020526040600020610ff287825461239d565b90550161100083825461239d565b9055600254604051634c6afee560e11b815260089190911c6001600160a01b03169690936020856004818b5afa94851561120c57600095611218575b506020600498604051998a809263a32bf59760e01b82525afa97881561120c576000986111d8575b5060018060a01b031696879460405194855260208501528860408501526060840152608083015260a08201528260c08201527f2ba87f3cecfb54ed0671f0be32d0caa2acaa1f68286c7024d3c7bb1a475c3fac60e060018060a01b03861692a36040518181527fd56c110470e0a75be40547eacf7b79089170526429680cd344272b7c9c38d84d906001600160a01b038416908290602090a28361110a575b5050505090565b6014820291808304601414901517156111c257602060648593048360005260048252604060002061113c82825461239d565b9055604051908152a26001600160a01b03166000908152600660205260409020805460ff81161561116e575b80611103565b60019060ff19161790558060005260056020526040600020805490600182018092116111c257557f7c6b5ed95091a3f3da836a7a26ea470ff49218fd66b3eceb37f8acfe6e7d9b4c600080a2388080611168565b634e487b7160e01b600052601160045260246000fd5b9097506020813d602011611204575b816111f460209383610a3e565b810103126109c157519638611064565b3d91506111e7565b6040513d6000823e3d90fd5b9794506020883d602011611247575b8161123460209383610a3e565b810103126109c15796519396602061103c565b3d9150611227565b69032d26d12e980b600000871061127657506003670de0b6b3a7640000610fcf6010610fc9565b69021e19e0c9bab2400000871061129d57506003670de0b6b3a7640000610fcf600d610fc9565b69010f0cf064dd5920000087106112c457506003670de0b6b3a7640000610fcf600a610fc9565b683635c9adc5dea0000087106112ea57506003670de0b6b3a7640000610fcf6009610fc9565b681b1ae4d6e2ef500000871061131057506003670de0b6b3a7640000610fcf6008610fc9565b680d8d726b7177a80000871061133657506003670de0b6b3a7640000610fcf6007610fc9565b6802b5e3af16b188000087101561135c575b670de0b6b3a7640000610fcf600392610fc9565b506006611348565b61136d90610a2a565b38610fa3565b60025461139490849060081c6001600160a01b03908116903390861661280c565b610f2a565b6113b6906113a7858961255a565b906001600160a01b0316612272565b8215610f2a5760025461139490849060081c6001600160a01b0316612272565b6113f8915060203d6020116113fe575b6113f08183610a3e565b810190612407565b38610ee0565b503d6113e6565b8354611419906001600160a01b031661273d565b90610e98565b6007602052604060002080546001600160a01b0319166001600160a01b0390921691909117905591610e69565b8560449160405191634909fb6f60e11b835260048301526024820152fd5b90506020813d602011611494575b8161148560209383610a3e565b810103126109c1575138610e1e565b3d9150611478565b6040519081529086906020908390600490829060081c6001600160a01b03165afa801561120c576000906114e9575b6044925060405191637932cc9560e01b835260048301526024820152fd5b506020823d602011611514575b8161150360209383610a3e565b810103126109c157604491516114cb565b3d91506114f6565b9150506020813d602011611549575b8161153860209383610a3e565b810103126109c15787905138610dd9565b3d915061152b565b610d9b610d95610da193876123c3565b815460069060019061157b906001600160a01b031661273d565b93610d6a565b815460405163313ce56760e01b815290602090829060049082906001600160a01b03165afa90811561120c576000916115bc575b5090610d5a565b6115de915060203d6020116115e4575b6115d68183610a3e565b8101906123aa565b386115b5565b503d6115cc565b60405163cba58f4560e01b8152600490fd5b604051631879d33d60e01b8152600490fd5b634e487b7160e01b600052602160045260246000fd5b60a0969196813d60a01161169f575b8161164160a09383610a3e565b810103126101b8576040519161165683610a0e565b61165f82612390565b8352602082015190600382101561169c57509060809160208401526040810151604084015260608101516060840152015160808201529438610cf7565b80fd5b3d9150611634565b9095506020813d6020116116d3575b816116c360209383610a3e565b810103126109c157519438610cbc565b3d91506116b6565b604051635b08f14d60e11b8152600490fd5b90506020813d60201161171f575b8161170860209383610a3e565b810103126109c15761171990612390565b38610c5e565b3d91506116fb565b60405163f2f17a2b60e01b8152600490fd5b604051630bb028ab60e11b8152600490fd5b604051632390dddf60e11b8152600490fd5b91909160009161176b612372565b6001600160a01b0382161561174b576001600160a01b0382811690851614611739578415611727576002546040516308bcf8b560e21b815290949060208160048160088a901c6001600160a01b03165afa9081156121f9578591612238575b50156116db578360806040516117df81610a0e565b82815282602082015282604082015282606082015201526040519563a32bf59760e01b875260208760048160018060a01b038a60081c165afa9687156121f9578597612204575b5060405163023c4c9f60e61b8152600481019790975260a08760248160088a901c6001600160a01b03165afa9687156121f9578597612178575b5060208701516003811015612164576001036115fd576118808382612567565b96611894886060608084015193015161239d565b116115eb576001600160a01b0383168552600360205260408520600281015460ff1690811561210b576008915b156120eb57600660016305f5e100925b0154036120da5764e8d4a51000838181020481036120c657610d956118fc9392610d9b9286026123c3565b60405163d6362e9760e01b8152909690602081600481600886901c6001600160a01b03165afa908115611ec957908891889161208d575b5011611ff657604051632b1d914f60e21b81526001600160a01b03868116600483015290916020918391602491839160081c165afa908115611feb578691611fb9575b50868110611f9b57506001600160a01b038416855260066020526040852054829060ff1615611f7057506001600160a01b038481168652600760205260408620541691505b6001600160a01b0383168552600360205260408520600281015490939060ff1615611f56576305f5e100905b6119f381848689612426565b60025460405163cb69a03f60e01b8152939793919291906020908290600490829060081c6001600160a01b03165afa908115611f4b578b91611f2c575b506001600160a01b03851673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14611efe57611a7490611a63838961255a565b90336001600160a01b03881661280c565b80611ed8575b60025460081c6001600160a01b031692833b15611ed457604051636d81c97960e01b81526001600160a01b03808c1660048301529586166024820152604481018d9052606481018e90529416608485015260a484015260c48301528790829060e490829084905af18015611ec957611eb6575b508569043c33c19375648000008810611da157506003670de0b6b3a7640000611b1860145b8a6123c3565b049460018060a01b0387168852600460205260408820611b3987825461239d565b905501611b4783825461239d565b9055600254604051634c6afee560e11b815260089190911c6001600160a01b03169790936020856004818c5afa948515611d5f578895611d6a575b5060206004996040519a8b809263a32bf59760e01b82525afa988915611d5f578899611d2b575b5060018060a01b031697889460405194855260208501528960408501526060840152608083015260a08201528260c08201527f2ba87f3cecfb54ed0671f0be32d0caa2acaa1f68286c7024d3c7bb1a475c3fac60e060018060a01b03861692a36040518181527fd56c110470e0a75be40547eacf7b79089170526429680cd344272b7c9c38d84d91906001600160a01b038416908390602090a284611c51575b505050505090565b601481029080820460141490151715611d175790602060648693048386526004825260408620611c8282825461239d565b9055604051908152a26001600160a01b03168152600660205260408120805460ff811615611cb1575b80611c49565b60019060ff191617905581815260056020526040812080549060018201809211611d0357557f7c6b5ed95091a3f3da836a7a26ea470ff49218fd66b3eceb37f8acfe6e7d9b4c9080a238808080611cab565b634e487b7160e01b83526011600452602483fd5b634e487b7160e01b84526011600452602484fd5b9098506020813d602011611d57575b81611d4760209383610a3e565b810103126109c157519738611ba9565b3d9150611d3a565b6040513d8a823e3d90fd5b9894506020893d602011611d99575b81611d8660209383610a3e565b810103126109c157975193976020611b82565b3d9150611d79565b69032d26d12e980b6000008810611dc857506003670de0b6b3a7640000611b186010611b12565b69021e19e0c9bab24000008810611def57506003670de0b6b3a7640000611b18600d611b12565b69010f0cf064dd592000008810611e1657506003670de0b6b3a7640000611b18600a611b12565b683635c9adc5dea000008810611e3c57506003670de0b6b3a7640000611b186009611b12565b681b1ae4d6e2ef5000008810611e6257506003670de0b6b3a7640000611b186008611b12565b680d8d726b7177a800008810611e8857506003670de0b6b3a7640000611b186007611b12565b6802b5e3af16b1880000881015611eae575b670de0b6b3a7640000611b18600392611b12565b506006611e9a565b611ec290969196610a2a565b9438611aed565b6040513d89823e3d90fd5b8a80fd5b600254611ef990829060081c6001600160a01b03908116903390881661280c565b611a7a565b611f0c906113a7838961255a565b8015611a7a57600254611ef990829060081c6001600160a01b0316612272565b611f45915060203d6020116113fe576113f08183610a3e565b38611a30565b6040513d8d823e3d90fd5b8354611f6a906001600160a01b031661273d565b906119e7565b60076020526040862080546001600160a01b0319166001600160a01b039092169190911790556119bb565b8660449160405191634909fb6f60e11b835260048301526024820152fd5b90506020813d602011611fe3575b81611fd460209383610a3e565b8101031261032e575138611976565b3d9150611fc7565b6040513d88823e3d90fd5b60405163d6362e9760e01b815286918891906020908290600490829060081c6001600160a01b03165afa90811561208257839161204c575b6044838360405191637932cc9560e01b835260048301526024820152fd5b90506020813d60201161207a575b8161206760209383610a3e565b8101031261015b5760449250518361202e565b3d915061205a565b6040513d85823e3d90fd5b9150506020813d6020116120be575b816120a960209383610a3e565b810103126120ba5787905138611933565b8680fd5b3d915061209c565b634e487b7160e01b88526011600452602488fd5b90610d9b610d956118fc93856123c3565b8054600690600190612105906001600160a01b031661273d565b926118d1565b805460405163313ce56760e01b815290602090829060049082906001600160a01b03165afa908115611d5f578891612145575b50916118c1565b61215e915060203d6020116115e4576115d68183610a3e565b3861213e565b634e487b7160e01b86526021600452602486fd5b90965060a0813d60a0116121f1575b8161219460a09383610a3e565b810103126121ed57604051906121a982610a0e565b6121b281612390565b8252602081015160038110156120ba579060809160208401526040810151604084015260608101516060840152015160808201529538611860565b8480fd5b3d9150612187565b6040513d87823e3d90fd5b9096506020813d602011612230575b8161222060209383610a3e565b810103126121ed57519538611826565b3d9150612213565b90506020813d60201161226a575b8161225360209383610a3e565b810103126121ed5761226490612390565b386117ca565b3d9150612246565b8147106122f757600080808094819460018060a01b03165af1903d156122f1573d9067ffffffffffffffff82116122dd57604051916122bb601f8201601f191660200184610a3e565b825260203d92013e5b156122cb57565b60405163d6bda27560e01b8152600490fd5b634e487b7160e01b81526041600452602490fd5b506122c4565b60405163cf47918160e01b815247600482015260248101839052604490fd5b906000602091828151910182855af11561120c576000513d61236957506001600160a01b0381163b155b6123475750565b604051635274afe760e01b81526001600160a01b039091166004820152602490fd5b60011415612340565b60ff6002541661237e57565b60405163d93c066560e01b8152600490fd5b519081151582036109c157565b919082018092116111c257565b908160209103126109c1575160ff811681036109c15790565b818102929181159184041417156111c257565b60ff16604d81116111c257600a0a90565b81156123f1570490565b634e487b7160e01b600052601260045260246000fd5b908160209103126109c157516001600160a01b03811681036109c15790565b60025460408051630977471760e31b81526001600160a01b039384166004820152938316602485015293959294929360089190911c82169291602086604481875afa95861561254f5760009661252e575b508516801561251f5781906024825180968193638f11740b60e01b835260048301525afa928315612514576000916000946124d9575b50506124cd6124d3936124c6926103e89384918a6123c3565b04976123c3565b04612567565b91929190565b8194508092503d831161250d575b6124f18183610a3e565b810103126109c1578151602090920151916124cd6124c66124ad565b503d6124e7565b50513d6000823e3d90fd5b50505050915090600090600090565b61254891965060203d6020116113fe576113f08183610a3e565b9438612477565b82513d6000823e3d90fd5b919082039182116111c257565b60018060a01b039081600093168352602091600383526040908185209160ff60028401541693846000146126d1576008945b156126ba5785600660016305f5e100965b0154036126b1575064e8d4a510009081810291818304149015171561269d5785600491935b60025460081c16835192838092634c6afee560e11b82525afa958615612693578796612663575b50508415612653575090612609916123c3565b92670de0b6b3a76400009384810294818604149015171561263f575061263c9291612636610d9b926123d6565b906123c3565b90565b634e487b7160e01b81526011600452602490fd5b51630b1faeab60e41b8152600490fd5b9080929650813d831161268c575b61267b8183610a3e565b8101031261032e57519338806125f6565b503d612671565b82513d89823e3d90fd5b634e487b7160e01b87526011600452602487fd5b600491936125cf565b85600660016126cb8688541661273d565b966125aa565b6004868486541684519283809263313ce56760e01b82525afa90811561271c5788916126ff575b5094612599565b6127169150873d89116115e4576115d68183610a3e565b386126f8565b83513d8a823e3d90fd5b519069ffffffffffffffffffff821682036109c157565b604051633fabe5a360e21b81529060a090829060049082906001600160a01b03165afa801561120c5760009081906127b4575b61277c9192504261255a565b600854106127a25760008113156127905790565b604051630b1faeab60e41b8152600490fd5b604051634339de0f60e11b8152600490fd5b5060a0823d60a011612804575b816127ce60a09383610a3e565b8101031261169c57506127e081612726565b5061277c60208201516127fa608060608501519401612726565b5091829150612770565b3d91506127c1565b6040516323b872dd60e01b60208201526001600160a01b0392831660248201529290911660448301526064808301939093529181526128539161284e82610a0e565b612316565b56fea26469706673582212209ac8fb1a7f3851a230f2644010ec5d17d80844de35b1554dae00f6f06f3260bf64736f6c634300081800330000000000000000000000008a7042dfbb8de81c8062cff9ca9f013827b9e49c0000000000000000000000000000000000000000000000000000000000001518

Deployed Bytecode

0x60806040818152600480361015610021575b505050361561001f57600080fd5b005b600092833560e01c90816301ffc9a71461095757508063248a9ca31461092e57806324acbd69146108f65780632f2ff15d146108cd5780633408f73a146108a057806334e8c679146107e657806336568abe1461079f5780633f4ba83a146107365780634fb52c70146106d25780635b6cca80146106975780635c975abb146106735780635dc52ff6146105815780635f31d92b146104b25780636dcf5ce114610493578063784bfa32146104585780637b1b901a146103fa5780638456cb591461039f5780638743c549146103325780638eecbfa81461020157806391d14854146101bc578063a217fddf1461019d578063d547741f1461015f5763df56867b03610011573461015b57602036600319011261015b5760209282916001600160a01b0361014d6109ab565b168252845220549051908152f35b8280fd5b50903461015b578060031936011261015b57610199913561019460016101836109c6565b938387528660205286200154610ab8565b610b7f565b5080f35b5050346101b857816003193601126101b85751908152602090f35b5080fd5b503461015b578160031936011261015b578160209360ff926101dc6109c6565b903582528186528282206001600160a01b039091168252855220549151911615158152f35b50919060803660031901126101b8576102186109ab565b906102216109c6565b604435916001600160a01b03831680840361032e57606435907f4d6ca2d030abc29757f11bdec506b9c196a27de798e9e9c57321409317dc0d0f8088528760205283882033895260205260ff8489205416156103105750610280610b5c565b808752600360205260018388200154156103005773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee036102d8576102c957506102c0939450349261175d565b505b6001805580f35b5163816565db60e01b81528590fd5b9390346102f157506102eb94955061175d565b506102c2565b5163d26bd23360e01b81528690fd5b82516343614f2760e01b81528890fd5b835163e2517d3f60e01b815233818b01526024810191909152604490fd5b8580fd5b5050346101b85760203660031901126101b857602091606091906001600160a01b03906003908390836103636109ab565b16815282875220835192610376846109dc565b815416835260018101548684015260ff6002820154161515848401520154928391015251908152f35b5050346101b857816003193601126101b85760207f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258916103dd610a60565b6103e5612372565b600160ff19600254161760025551338152a180f35b5050346101b857816003193601126101b85760207f6f5e7a5e558e349050c8a249c9443f579e68b88e8a3d287689ae6459a48a237a91610438610a60565b610440610b5c565b479061044c8233612272565b51908152a16001805580f35b5050346101b857816003193601126101b857602090517f4d6ca2d030abc29757f11bdec506b9c196a27de798e9e9c57321409317dc0d0f8152f35b5050346101b857816003193601126101b8576020906008549051908152f35b50919060603660031901126101b8576104c96109ab565b906104d26109c6565b906044356104de610b5c565b6001600160a01b038316801561057157808652600360205260018387200154156105615773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0361053e5761052f57506102c0929350349133610bf4565b5163816565db60e01b81528490fd5b92903461055257506102eb93945033610bf4565b5163d26bd23360e01b81528590fd5b82516343614f2760e01b81528790fd5b8251633eaa20b360e01b81528790fd5b509190346101b85760803660031901126101b85761059d6109ab565b906105a66109c6565b916044356064359182151580930361032e576105c0610a60565b6001600160a01b03908116938415610664578215801561065a575b61064c57600395969750818151976105f2896109dc565b16875260208701928352808701938452606087019488865288528560205287209551166bffffffffffffffffffffffff60a01b865416178555516001850155600284019051151560ff801983541691161790555191015580f35b5162b967f360e21b81528790fd5b50601283116105db565b51633eaa20b360e01b81528790fd5b5050346101b857816003193601126101b85760209060ff6002541690519015158152f35b5050346101b85760203660031901126101b8576020916001600160a01b03908290826106c16109ab565b168152600385522054169051908152f35b50903461015b57602036600319011261015b578135916106f0610a60565b82156107285750816020917f6b0695b82961d69699cb7b8438d7eac257041649a2d203c75aa4f54e13d1ecca9360085551908152a180f35b905163e840a88d60e01b8152fd5b503461015b578260031936011261015b5761074f610a60565b6002549060ff821615610791575060ff1916600255513381527f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa90602090a180f35b8251638dfc202b60e01b8152fd5b509190346101b857806003193601126101b8576107ba6109c6565b90336001600160a01b038316036107d75750610199919235610b7f565b5163334bd91960e11b81528390fd5b5050346101b857806003193601126101b8577fd5ccc4809a3c78442b501cf0eb58cdb32e19a527ed3d34b0458e2cc85d0bc2f9906108226109ab565b61089660243592610831610a60565b610839610b5c565b805163a9059cbb60e01b60208201523360248201526044808201869052815261087690610867606482610a3e565b6001600160a01b038516612316565b516001600160a01b03909216825260208201929092529081906040820190565b0390a16001805580f35b5050346101b857816003193601126101b857600254905160089190911c6001600160a01b03168152602090f35b50903461015b578060031936011261015b5761019991356108f160016101836109c6565b610ade565b5050346101b85760203660031901126101b85760209181906001600160a01b0361091e6109ab565b1681526005845220549051908152f35b503461015b57602036600319011261015b57816020936001923581528085522001549051908152f35b9250503461015b57602036600319011261015b573563ffffffff60e01b811680910361015b5760209250637965db0b60e01b811490811561099a575b5015158152f35b6301ffc9a760e01b14905038610993565b600435906001600160a01b03821682036109c157565b600080fd5b602435906001600160a01b03821682036109c157565b6080810190811067ffffffffffffffff8211176109f857604052565b634e487b7160e01b600052604160045260246000fd5b60a0810190811067ffffffffffffffff8211176109f857604052565b67ffffffffffffffff81116109f857604052565b90601f8019910116810190811067ffffffffffffffff8211176109f857604052565b3360009081527fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5602052604081205460ff1615610a9a5750565b6044906040519063e2517d3f60e01b82523360048301526024820152fd5b80600052600060205260406000203360005260205260ff6040600020541615610a9a5750565b9060009180835282602052604083209160018060a01b03169182845260205260ff60408420541615600014610b5757808352826020526040832082845260205260408320600160ff198254161790557f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d339380a4600190565b505090565b600260015414610b6d576002600155565b604051633ee5aeb560e01b8152600490fd5b9060009180835282602052604083209160018060a01b03169182845260205260ff604084205416600014610b575780835282602052604083208284526020526040832060ff1981541690557ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b339380a4600190565b9092610bfe612372565b6001600160a01b0382161561174b576001600160a01b0382811690851614611739578015611727576002546040516308bcf8b560e21b8152909390602081600481600889901c6001600160a01b03165afa90811561120c576000916116ed575b50156116db5760006080604051610c7481610a0e565b82815282602082015282604082015282606082015201526040519463a32bf59760e01b865260208660048160018060a01b038960081c165afa95861561120c576000966116a7575b5060405163023c4c9f60e61b8152600481019690965260a086602481600889901c6001600160a01b03165afa95861561120c57600096611625575b506020860151600381101561160f576001036115fd57610d178284612567565b95610d2b876060608084015193015161239d565b116115eb576001600160a01b0382166000908152600360205260409020600281015460ff168015611581576008905b1561156157600660016305f5e100935b0154036115515764e8d4a5100091858381020483036111c257610d95610d9b91610da19488026123c3565b916123d6565b906123e7565b60405163d6362e9760e01b80825291969190602081600481600887901c6001600160a01b03165afa801561120c57889160009161151c575b501161149c575060405163151a8b2960e21b81526001600160a01b03868116600483015290916020918391602491839160081c165afa90811561120c5760009161146a575b5085811061144c57506001600160a01b038416600090815260066020526040902054819060ff161561141f5750506001600160a01b0383811660009081526007602052604090205416915b6001600160a01b0382166000908152600360205260409020600281015490939060ff1615611405576305f5e100905b610ea484848389612426565b60025460405163cb69a03f60e01b815293979293906020908290600490829060081c6001600160a01b03165afa90811561120c576000916113d6575b506001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1461139957610f2490610f13858961255a565b90336001600160a01b03861661280c565b82611373575b60025460081c6001600160a01b031692833b156109c157604051636d81c97960e01b81526001600160a01b038b811660048301529384166024820152604481018c9052606481018d905294909216608485015260a484019190915260c4830152600090829060e490829084905af1801561120c57611364575b50600069043c33c1937564800000871061124f57506003670de0b6b3a7640000610fcf60145b896123c3565b049460018060a01b03871660005260046020526040600020610ff287825461239d565b90550161100083825461239d565b9055600254604051634c6afee560e11b815260089190911c6001600160a01b03169690936020856004818b5afa94851561120c57600095611218575b506020600498604051998a809263a32bf59760e01b82525afa97881561120c576000986111d8575b5060018060a01b031696879460405194855260208501528860408501526060840152608083015260a08201528260c08201527f2ba87f3cecfb54ed0671f0be32d0caa2acaa1f68286c7024d3c7bb1a475c3fac60e060018060a01b03861692a36040518181527fd56c110470e0a75be40547eacf7b79089170526429680cd344272b7c9c38d84d906001600160a01b038416908290602090a28361110a575b5050505090565b6014820291808304601414901517156111c257602060648593048360005260048252604060002061113c82825461239d565b9055604051908152a26001600160a01b03166000908152600660205260409020805460ff81161561116e575b80611103565b60019060ff19161790558060005260056020526040600020805490600182018092116111c257557f7c6b5ed95091a3f3da836a7a26ea470ff49218fd66b3eceb37f8acfe6e7d9b4c600080a2388080611168565b634e487b7160e01b600052601160045260246000fd5b9097506020813d602011611204575b816111f460209383610a3e565b810103126109c157519638611064565b3d91506111e7565b6040513d6000823e3d90fd5b9794506020883d602011611247575b8161123460209383610a3e565b810103126109c15796519396602061103c565b3d9150611227565b69032d26d12e980b600000871061127657506003670de0b6b3a7640000610fcf6010610fc9565b69021e19e0c9bab2400000871061129d57506003670de0b6b3a7640000610fcf600d610fc9565b69010f0cf064dd5920000087106112c457506003670de0b6b3a7640000610fcf600a610fc9565b683635c9adc5dea0000087106112ea57506003670de0b6b3a7640000610fcf6009610fc9565b681b1ae4d6e2ef500000871061131057506003670de0b6b3a7640000610fcf6008610fc9565b680d8d726b7177a80000871061133657506003670de0b6b3a7640000610fcf6007610fc9565b6802b5e3af16b188000087101561135c575b670de0b6b3a7640000610fcf600392610fc9565b506006611348565b61136d90610a2a565b38610fa3565b60025461139490849060081c6001600160a01b03908116903390861661280c565b610f2a565b6113b6906113a7858961255a565b906001600160a01b0316612272565b8215610f2a5760025461139490849060081c6001600160a01b0316612272565b6113f8915060203d6020116113fe575b6113f08183610a3e565b810190612407565b38610ee0565b503d6113e6565b8354611419906001600160a01b031661273d565b90610e98565b6007602052604060002080546001600160a01b0319166001600160a01b0390921691909117905591610e69565b8560449160405191634909fb6f60e11b835260048301526024820152fd5b90506020813d602011611494575b8161148560209383610a3e565b810103126109c1575138610e1e565b3d9150611478565b6040519081529086906020908390600490829060081c6001600160a01b03165afa801561120c576000906114e9575b6044925060405191637932cc9560e01b835260048301526024820152fd5b506020823d602011611514575b8161150360209383610a3e565b810103126109c157604491516114cb565b3d91506114f6565b9150506020813d602011611549575b8161153860209383610a3e565b810103126109c15787905138610dd9565b3d915061152b565b610d9b610d95610da193876123c3565b815460069060019061157b906001600160a01b031661273d565b93610d6a565b815460405163313ce56760e01b815290602090829060049082906001600160a01b03165afa90811561120c576000916115bc575b5090610d5a565b6115de915060203d6020116115e4575b6115d68183610a3e565b8101906123aa565b386115b5565b503d6115cc565b60405163cba58f4560e01b8152600490fd5b604051631879d33d60e01b8152600490fd5b634e487b7160e01b600052602160045260246000fd5b60a0969196813d60a01161169f575b8161164160a09383610a3e565b810103126101b8576040519161165683610a0e565b61165f82612390565b8352602082015190600382101561169c57509060809160208401526040810151604084015260608101516060840152015160808201529438610cf7565b80fd5b3d9150611634565b9095506020813d6020116116d3575b816116c360209383610a3e565b810103126109c157519438610cbc565b3d91506116b6565b604051635b08f14d60e11b8152600490fd5b90506020813d60201161171f575b8161170860209383610a3e565b810103126109c15761171990612390565b38610c5e565b3d91506116fb565b60405163f2f17a2b60e01b8152600490fd5b604051630bb028ab60e11b8152600490fd5b604051632390dddf60e11b8152600490fd5b91909160009161176b612372565b6001600160a01b0382161561174b576001600160a01b0382811690851614611739578415611727576002546040516308bcf8b560e21b815290949060208160048160088a901c6001600160a01b03165afa9081156121f9578591612238575b50156116db578360806040516117df81610a0e565b82815282602082015282604082015282606082015201526040519563a32bf59760e01b875260208760048160018060a01b038a60081c165afa9687156121f9578597612204575b5060405163023c4c9f60e61b8152600481019790975260a08760248160088a901c6001600160a01b03165afa9687156121f9578597612178575b5060208701516003811015612164576001036115fd576118808382612567565b96611894886060608084015193015161239d565b116115eb576001600160a01b0383168552600360205260408520600281015460ff1690811561210b576008915b156120eb57600660016305f5e100925b0154036120da5764e8d4a51000838181020481036120c657610d956118fc9392610d9b9286026123c3565b60405163d6362e9760e01b8152909690602081600481600886901c6001600160a01b03165afa908115611ec957908891889161208d575b5011611ff657604051632b1d914f60e21b81526001600160a01b03868116600483015290916020918391602491839160081c165afa908115611feb578691611fb9575b50868110611f9b57506001600160a01b038416855260066020526040852054829060ff1615611f7057506001600160a01b038481168652600760205260408620541691505b6001600160a01b0383168552600360205260408520600281015490939060ff1615611f56576305f5e100905b6119f381848689612426565b60025460405163cb69a03f60e01b8152939793919291906020908290600490829060081c6001600160a01b03165afa908115611f4b578b91611f2c575b506001600160a01b03851673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14611efe57611a7490611a63838961255a565b90336001600160a01b03881661280c565b80611ed8575b60025460081c6001600160a01b031692833b15611ed457604051636d81c97960e01b81526001600160a01b03808c1660048301529586166024820152604481018d9052606481018e90529416608485015260a484015260c48301528790829060e490829084905af18015611ec957611eb6575b508569043c33c19375648000008810611da157506003670de0b6b3a7640000611b1860145b8a6123c3565b049460018060a01b0387168852600460205260408820611b3987825461239d565b905501611b4783825461239d565b9055600254604051634c6afee560e11b815260089190911c6001600160a01b03169790936020856004818c5afa948515611d5f578895611d6a575b5060206004996040519a8b809263a32bf59760e01b82525afa988915611d5f578899611d2b575b5060018060a01b031697889460405194855260208501528960408501526060840152608083015260a08201528260c08201527f2ba87f3cecfb54ed0671f0be32d0caa2acaa1f68286c7024d3c7bb1a475c3fac60e060018060a01b03861692a36040518181527fd56c110470e0a75be40547eacf7b79089170526429680cd344272b7c9c38d84d91906001600160a01b038416908390602090a284611c51575b505050505090565b601481029080820460141490151715611d175790602060648693048386526004825260408620611c8282825461239d565b9055604051908152a26001600160a01b03168152600660205260408120805460ff811615611cb1575b80611c49565b60019060ff191617905581815260056020526040812080549060018201809211611d0357557f7c6b5ed95091a3f3da836a7a26ea470ff49218fd66b3eceb37f8acfe6e7d9b4c9080a238808080611cab565b634e487b7160e01b83526011600452602483fd5b634e487b7160e01b84526011600452602484fd5b9098506020813d602011611d57575b81611d4760209383610a3e565b810103126109c157519738611ba9565b3d9150611d3a565b6040513d8a823e3d90fd5b9894506020893d602011611d99575b81611d8660209383610a3e565b810103126109c157975193976020611b82565b3d9150611d79565b69032d26d12e980b6000008810611dc857506003670de0b6b3a7640000611b186010611b12565b69021e19e0c9bab24000008810611def57506003670de0b6b3a7640000611b18600d611b12565b69010f0cf064dd592000008810611e1657506003670de0b6b3a7640000611b18600a611b12565b683635c9adc5dea000008810611e3c57506003670de0b6b3a7640000611b186009611b12565b681b1ae4d6e2ef5000008810611e6257506003670de0b6b3a7640000611b186008611b12565b680d8d726b7177a800008810611e8857506003670de0b6b3a7640000611b186007611b12565b6802b5e3af16b1880000881015611eae575b670de0b6b3a7640000611b18600392611b12565b506006611e9a565b611ec290969196610a2a565b9438611aed565b6040513d89823e3d90fd5b8a80fd5b600254611ef990829060081c6001600160a01b03908116903390881661280c565b611a7a565b611f0c906113a7838961255a565b8015611a7a57600254611ef990829060081c6001600160a01b0316612272565b611f45915060203d6020116113fe576113f08183610a3e565b38611a30565b6040513d8d823e3d90fd5b8354611f6a906001600160a01b031661273d565b906119e7565b60076020526040862080546001600160a01b0319166001600160a01b039092169190911790556119bb565b8660449160405191634909fb6f60e11b835260048301526024820152fd5b90506020813d602011611fe3575b81611fd460209383610a3e565b8101031261032e575138611976565b3d9150611fc7565b6040513d88823e3d90fd5b60405163d6362e9760e01b815286918891906020908290600490829060081c6001600160a01b03165afa90811561208257839161204c575b6044838360405191637932cc9560e01b835260048301526024820152fd5b90506020813d60201161207a575b8161206760209383610a3e565b8101031261015b5760449250518361202e565b3d915061205a565b6040513d85823e3d90fd5b9150506020813d6020116120be575b816120a960209383610a3e565b810103126120ba5787905138611933565b8680fd5b3d915061209c565b634e487b7160e01b88526011600452602488fd5b90610d9b610d956118fc93856123c3565b8054600690600190612105906001600160a01b031661273d565b926118d1565b805460405163313ce56760e01b815290602090829060049082906001600160a01b03165afa908115611d5f578891612145575b50916118c1565b61215e915060203d6020116115e4576115d68183610a3e565b3861213e565b634e487b7160e01b86526021600452602486fd5b90965060a0813d60a0116121f1575b8161219460a09383610a3e565b810103126121ed57604051906121a982610a0e565b6121b281612390565b8252602081015160038110156120ba579060809160208401526040810151604084015260608101516060840152015160808201529538611860565b8480fd5b3d9150612187565b6040513d87823e3d90fd5b9096506020813d602011612230575b8161222060209383610a3e565b810103126121ed57519538611826565b3d9150612213565b90506020813d60201161226a575b8161225360209383610a3e565b810103126121ed5761226490612390565b386117ca565b3d9150612246565b8147106122f757600080808094819460018060a01b03165af1903d156122f1573d9067ffffffffffffffff82116122dd57604051916122bb601f8201601f191660200184610a3e565b825260203d92013e5b156122cb57565b60405163d6bda27560e01b8152600490fd5b634e487b7160e01b81526041600452602490fd5b506122c4565b60405163cf47918160e01b815247600482015260248101839052604490fd5b906000602091828151910182855af11561120c576000513d61236957506001600160a01b0381163b155b6123475750565b604051635274afe760e01b81526001600160a01b039091166004820152602490fd5b60011415612340565b60ff6002541661237e57565b60405163d93c066560e01b8152600490fd5b519081151582036109c157565b919082018092116111c257565b908160209103126109c1575160ff811681036109c15790565b818102929181159184041417156111c257565b60ff16604d81116111c257600a0a90565b81156123f1570490565b634e487b7160e01b600052601260045260246000fd5b908160209103126109c157516001600160a01b03811681036109c15790565b60025460408051630977471760e31b81526001600160a01b039384166004820152938316602485015293959294929360089190911c82169291602086604481875afa95861561254f5760009661252e575b508516801561251f5781906024825180968193638f11740b60e01b835260048301525afa928315612514576000916000946124d9575b50506124cd6124d3936124c6926103e89384918a6123c3565b04976123c3565b04612567565b91929190565b8194508092503d831161250d575b6124f18183610a3e565b810103126109c1578151602090920151916124cd6124c66124ad565b503d6124e7565b50513d6000823e3d90fd5b50505050915090600090600090565b61254891965060203d6020116113fe576113f08183610a3e565b9438612477565b82513d6000823e3d90fd5b919082039182116111c257565b60018060a01b039081600093168352602091600383526040908185209160ff60028401541693846000146126d1576008945b156126ba5785600660016305f5e100965b0154036126b1575064e8d4a510009081810291818304149015171561269d5785600491935b60025460081c16835192838092634c6afee560e11b82525afa958615612693578796612663575b50508415612653575090612609916123c3565b92670de0b6b3a76400009384810294818604149015171561263f575061263c9291612636610d9b926123d6565b906123c3565b90565b634e487b7160e01b81526011600452602490fd5b51630b1faeab60e41b8152600490fd5b9080929650813d831161268c575b61267b8183610a3e565b8101031261032e57519338806125f6565b503d612671565b82513d89823e3d90fd5b634e487b7160e01b87526011600452602487fd5b600491936125cf565b85600660016126cb8688541661273d565b966125aa565b6004868486541684519283809263313ce56760e01b82525afa90811561271c5788916126ff575b5094612599565b6127169150873d89116115e4576115d68183610a3e565b386126f8565b83513d8a823e3d90fd5b519069ffffffffffffffffffff821682036109c157565b604051633fabe5a360e21b81529060a090829060049082906001600160a01b03165afa801561120c5760009081906127b4575b61277c9192504261255a565b600854106127a25760008113156127905790565b604051630b1faeab60e41b8152600490fd5b604051634339de0f60e11b8152600490fd5b5060a0823d60a011612804575b816127ce60a09383610a3e565b8101031261169c57506127e081612726565b5061277c60208201516127fa608060608501519401612726565b5091829150612770565b3d91506127c1565b6040516323b872dd60e01b60208201526001600160a01b0392831660248201529290911660448301526064808301939093529181526128539161284e82610a0e565b612316565b56fea26469706673582212209ac8fb1a7f3851a230f2644010ec5d17d80844de35b1554dae00f6f06f3260bf64736f6c63430008180033

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

0000000000000000000000008a7042dfbb8de81c8062cff9ca9f013827b9e49c0000000000000000000000000000000000000000000000000000000000001518

-----Decoded View---------------
Arg [0] : storage_ (address): 0x8a7042dfbB8de81C8062cfF9ca9F013827B9e49C
Arg [1] : priceThresholdSeconds_ (uint256): 5400

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 0000000000000000000000008a7042dfbb8de81c8062cff9ca9f013827b9e49c
Arg [1] : 0000000000000000000000000000000000000000000000000000000000001518


Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]
[ Download: CSV Export  ]

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