CPXPresaleNoCooldown

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "CPXPresaleNoCooldown.sol": {
      "content": "// SPDX-License-Identifier: MIT\r
pragma solidity ^0.8.24;\r
\r
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";\r
import "@openzeppelin/contracts/access/Ownable.sol";\r
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";\r
import "@openzeppelin/contracts/utils/Address.sol";\r
import "@openzeppelin/contracts/utils/math/Math.sol";\r
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";\r
\r
/**\r
 * @title CPX Presale Contract - NO COOLDOWN VERSION\r
 * @dev Advanced presale contract without purchase cooldown\r
 */\r
contract CPXPresaleNoCooldown is Ownable, ReentrancyGuard {\r
    using Address for address payable;\r
    using Math for uint256;\r
\r
    // Token contracts\r
    IERC20 public immutable cpxToken;\r
    IERC20 public immutable usdtToken;\r
    IERC20 public immutable usdcToken;\r
\r
    // Price Feed Oracles\r
    AggregatorV3Interface internal usdtPriceFeed;\r
    AggregatorV3Interface internal usdcPriceFeed;\r
    \r
    // Oracle configuration\r
    uint256 public constant PRICE_FEED_HEARTBEAT = 24 hours;\r
\r
    // Presale parameters\r
    uint256 public constant HARD_CAP = 10000 ether;\r
    uint256 public constant SOFT_CAP = 33 ether;\r
    uint256 public constant MIN_CONTRIBUTION = 0.0022 ether; // ~$10 USD\r
    uint256 public constant MAX_CONTRIBUTION = 10 ether;\r
    uint256 public constant INITIAL_DURATION = 333 days;\r
    uint256 public constant MAX_EXTENSION = 365 days;\r
\r
    // Security parameters (COOLDOWN REMOVED)\r
    uint256 public maxDailyPurchase = 1000 ether;\r
    uint256 public dailyPurchased;\r
    uint256 public lastResetDay;\r
    bool public paused = false;\r
\r
    // Referral system\r
    uint256 public constant REFERRAL_BONUS = 25;\r
    uint256 public constant MAX_REFERRAL_BONUS_PER_USER = 1000 ether;\r
    mapping(address => address) public referrals;\r
    mapping(address => uint256) public referralEarnings;\r
    mapping(address => uint256) public referralCount;\r
    mapping(address => bool) public whitelistedReferrers;\r
\r
    // Vesting parameters\r
    uint256 public constant IMMEDIATE_RELEASE_PERCENT = 30;\r
    uint256 public constant VESTING_DURATION = 10 * 30 days;\r
    mapping(address => uint256) public firstPurchaseTime;\r
\r
    // Price tiers\r
    uint256[10] public tierPrices = [\r
        590000000000000,\r
        1180000000000000,\r
        2360000000000000,\r
        3540000000000000,\r
        4720000000000000,\r
        5900000000000000,\r
        11800000000000000,\r
        17700000000000000,\r
        21830000000000000,\r
        21830000000000000\r
    ];\r
\r
    // Tier thresholds\r
    uint256[10] public tierThresholds = [\r
        100 ether,\r
        300 ether,\r
        600 ether,\r
        1000 ether,\r
        1500 ether,\r
        2200 ether,\r
        3000 ether,\r
        4000 ether,\r
        6000 ether,\r
        10000 ether\r
    ];\r
\r
    // State variables\r
    uint256 public totalRaised;\r
    uint256 public totalParticipants;\r
    uint256 public startTime;\r
    uint256 public endTime;\r
    uint256 public totalExtensionTime;\r
    uint256 public presaleEndTime;\r
    bool public presaleFinalized;\r
    bool public softCapReached;\r
    address public fundingWallet;\r
\r
    // Multi-signature\r
    address[] public owners;\r
    mapping(address => bool) public isOwner;\r
    uint256 public requiredSignatures = 2;\r
    mapping(bytes32 => mapping(address => bool)) public confirmations;\r
    mapping(bytes32 => uint256) public confirmationCount;\r
\r
    // Mappings\r
    mapping(address => uint256) public contributions;\r
    mapping(address => uint256) public tokensPurchased;\r
    mapping(address => uint256) public tokensReleased;\r
    mapping(address => bool) public hasParticipated;\r
\r
    // Timelock\r
    uint256 public constant TIMELOCK_DELAY = 24 hours;\r
    mapping(bytes32 => uint256) public timelockProposals;\r
\r
    // Events\r
    event TokensPurchased(address indexed buyer, uint256 ethAmount, uint256 tokenAmount, uint256 currentTier, address referrer);\r
    event ReferralBonus(address indexed referrer, address indexed buyer, uint256 bonusAmount);\r
    event PresaleExtended(uint256 newEndTime);\r
    event PresaleFinalized(uint256 totalRaised, bool softCapReached);\r
    event TokensWithdrawn(address indexed buyer, uint256 amount);\r
    event EmergencyWithdraw(address indexed token, address indexed destination, uint256 amount);\r
    event ProposalCreated(bytes32 indexed proposalId, string proposalType, uint256 executeTime);\r
    event FundingWalletUpdated(address indexed newWallet);\r
    event TierPricesUpdated();\r
    event TierThresholdsUpdated();\r
    event DailyLimitUpdated(uint256 newLimit);\r
    event OwnerAdded(address indexed newOwner);\r
    event OwnerRemoved(address indexed removedOwner);\r
    event RequiredSignaturesUpdated(uint256 newRequired);\r
    event PresalePaused(bool paused);\r
    event ReferrerWhitelisted(address indexed referrer, bool whitelisted);\r
\r
    modifier onlyMultiSig() {\r
        require(isOwner[msg.sender], "Not an owner");\r
        _;\r
    }\r
\r
    modifier circuitBreaker(uint256 amount) {\r
        _checkDailyLimit(amount);\r
        _;\r
    }\r
\r
    modifier whenNotPaused() {\r
        require(!paused, "Contract is paused");\r
        _;\r
    }\r
\r
    modifier timelocked(bytes32 proposalId) {\r
        require(block.timestamp >= timelockProposals[proposalId], "Timelock active");\r
        _;\r
    }\r
\r
    constructor(\r
        address _cpxToken,\r
        address _fundingWallet,\r
        address _usdtToken,\r
        address _usdcToken,\r
        address _usdtPriceFeed,\r
        address _usdcPriceFeed,\r
        address[] memory _initialOwners\r
    ) Ownable(msg.sender) {\r
        require(_cpxToken != address(0), "Invalid token address");\r
        require(_fundingWallet != address(0), "Invalid funding wallet");\r
        require(_initialOwners.length >= 2, "Need at least 2 owners");\r
\r
        cpxToken = IERC20(_cpxToken);\r
        usdtToken = IERC20(_usdtToken);\r
        usdcToken = IERC20(_usdcToken);\r
        fundingWallet = _fundingWallet;\r
        startTime = block.timestamp;\r
        endTime = startTime + INITIAL_DURATION;\r
\r
        usdtPriceFeed = AggregatorV3Interface(_usdtPriceFeed);\r
        usdcPriceFeed = AggregatorV3Interface(_usdcPriceFeed);\r
\r
        for (uint i = 0; i < _initialOwners.length; i++) {\r
            require(_initialOwners[i] != address(0), "Invalid owner");\r
            require(!isOwner[_initialOwners[i]], "Duplicate owner");\r
            owners.push(_initialOwners[i]);\r
            isOwner[_initialOwners[i]] = true;\r
        }\r
    }\r
\r
    function _checkDailyLimit(uint256 amount) internal {\r
        uint256 currentDay = block.timestamp / 1 days;\r
        if (currentDay > lastResetDay) {\r
            dailyPurchased = 0;\r
            lastResetDay = currentDay;\r
        }\r
        require(dailyPurchased + amount <= maxDailyPurchase, "Daily limit exceeded");\r
        dailyPurchased += amount;\r
    }\r
\r
    function getLatestPrice(AggregatorV3Interface priceFeed) internal view returns (uint256) {\r
        (\r
            /*uint80 roundID*/,\r
            int256 price,\r
            /*uint256 startedAt*/,\r
            uint256 timeStamp,\r
            /*uint80 answeredInRound*/\r
        ) = priceFeed.latestRoundData();\r
        \r
        require(price > 0, "Invalid price from oracle");\r
        require(block.timestamp - timeStamp < PRICE_FEED_HEARTBEAT, "Stale price data");\r
        \r
        return uint256(price) * 10**10;\r
    }\r
\r
    // NO COOLDOWN - Removed rateLimited modifier\r
    function buyTokens() external payable nonReentrant circuitBreaker(msg.value) whenNotPaused {\r
        _buyTokensInternal(msg.sender, msg.value, address(0));\r
    }\r
\r
    // NO COOLDOWN - Removed rateLimited modifier\r
    function buyTokensWithReferral(address referrer) external payable nonReentrant circuitBreaker(msg.value) whenNotPaused {\r
        require(referrer != msg.sender, "Cannot refer yourself");\r
        require(referrer != address(0), "Invalid referrer");\r
        require(whitelistedReferrers[referrer] || referralEarnings[referrer] < MAX_REFERRAL_BONUS_PER_USER, "Referrer not whitelisted or exceeded limit");\r
        _buyTokensInternal(msg.sender, msg.value, referrer);\r
    }\r
\r
    // NO COOLDOWN - Removed rateLimited modifier\r
    function buyTokensWithUSDT(uint256 usdtAmount, address referrer) external nonReentrant whenNotPaused {\r
        require(usdtAmount > 0, "Invalid amount");\r
        require(usdtToken.allowance(msg.sender, address(this)) >= usdtAmount, "Insufficient allowance");\r
        \r
        uint256 ethEquivalent = (usdtAmount * getLatestPrice(usdtPriceFeed)) / 1e18;\r
        require(ethEquivalent >= MIN_CONTRIBUTION, "Below minimum contribution");\r
        \r
        require(usdtToken.transferFrom(msg.sender, address(this), usdtAmount), "USDT transfer failed");\r
        _buyTokensInternal(msg.sender, ethEquivalent, referrer);\r
    }\r
\r
    // NO COOLDOWN - Removed rateLimited modifier\r
    function buyTokensWithUSDC(uint256 usdcAmount, address referrer) external nonReentrant whenNotPaused {\r
        require(usdcAmount > 0, "Invalid amount");\r
        require(usdcToken.allowance(msg.sender, address(this)) >= usdcAmount, "Insufficient allowance");\r
        \r
        uint256 ethEquivalent = (usdcAmount * getLatestPrice(usdcPriceFeed)) / 1e18;\r
        require(ethEquivalent >= MIN_CONTRIBUTION, "Below minimum contribution");\r
        \r
        require(usdcToken.transferFrom(msg.sender, address(this), usdcAmount), "USDC transfer failed");\r
        _buyTokensInternal(msg.sender, ethEquivalent, referrer);\r
    }\r
\r
    function _buyTokensInternal(address buyer, uint256 amount, address referrer) internal {\r
        require(block.timestamp >= startTime, "Presale not started");\r
        require(block.timestamp <= endTime, "Presale ended");\r
        require(!presaleFinalized, "Presale finalized");\r
        require(amount >= MIN_CONTRIBUTION, "Below minimum contribution");\r
        require(contributions[buyer] + amount <= MAX_CONTRIBUTION, "Exceeds max contribution");\r
        require(totalRaised + amount <= HARD_CAP, "Exceeds hard cap");\r
\r
        uint256 tokenAmount = calculateTokenAmount(amount);\r
        require(tokenAmount > 0, "Invalid token amount");\r
\r
        if (firstPurchaseTime[buyer] == 0) {\r
            firstPurchaseTime[buyer] = block.timestamp;\r
        }\r
\r
        if (referrer != address(0) && referrals[buyer] == address(0)) {\r
            referrals[buyer] = referrer;\r
            uint256 bonusTokens = (tokenAmount * REFERRAL_BONUS) / 100;\r
            tokenAmount += bonusTokens;\r
            referralEarnings[referrer] += bonusTokens;\r
            referralCount[referrer]++;\r
            emit ReferralBonus(referrer, buyer, bonusTokens);\r
        }\r
\r
        if (!hasParticipated[buyer]) {\r
            hasParticipated[buyer] = true;\r
            totalParticipants++;\r
        }\r
\r
        contributions[buyer] += amount;\r
        tokensPurchased[buyer] += tokenAmount;\r
        totalRaised += amount;\r
\r
        if (!softCapReached && totalRaised >= SOFT_CAP) {\r
            softCapReached = true;\r
        }\r
\r
        uint256 currentTier = getCurrentTier();\r
        emit TokensPurchased(buyer, amount, tokenAmount, currentTier, referrer);\r
    }\r
\r
    function calculateTokenAmount(uint256 ethAmount) public view returns (uint256) {\r
        uint256 remainingEth = ethAmount;\r
        uint256 totalTokens = 0;\r
        uint256 currentRaised = totalRaised;\r
\r
        for (uint256 i = 0; i < tierThresholds.length; i++) {\r
            if (currentRaised >= tierThresholds[i]) {\r
                continue;\r
            }\r
\r
            uint256 tierCapacity = tierThresholds[i] - currentRaised;\r
            uint256 ethForThisTier = remainingEth > tierCapacity ? tierCapacity : remainingEth;\r
\r
            if (ethForThisTier > 0) {\r
                require(tierPrices[i] > 0, "Invalid tier price");\r
                uint256 tokensInTier = (ethForThisTier * 1e18) / tierPrices[i];\r
                totalTokens += tokensInTier;\r
                remainingEth -= ethForThisTier;\r
                currentRaised += ethForThisTier;\r
            }\r
\r
            if (remainingEth == 0) {\r
                break;\r
            }\r
        }\r
\r
        return totalTokens;\r
    }\r
\r
    function calculateROI(uint256 ethAmount, uint256 futurePrice) external view returns (\r
        uint256 tokensReceived,\r
        uint256 futureValue,\r
        uint256 roiPercent\r
    ) {\r
        tokensReceived = calculateTokenAmount(ethAmount);\r
        futureValue = (tokensReceived * futurePrice) / 1e18;\r
\r
        if (ethAmount > 0) {\r
            roiPercent = ((futureValue - ethAmount) * 100) / ethAmount;\r
        }\r
    }\r
\r
    function getCurrentTier() public view returns (uint256) {\r
        for (uint256 i = 0; i < tierThresholds.length; i++) {\r
            if (totalRaised < tierThresholds[i]) {\r
                return i + 1;\r
            }\r
        }\r
        return tierThresholds.length;\r
    }\r
\r
    function getCurrentPrice() public view returns (uint256) {\r
        uint256 tier = getCurrentTier();\r
        return tierPrices[tier - 1];\r
    }\r
\r
    function getDashboardStats() external view returns (\r
        uint256 _totalRaised,\r
        uint256 _totalParticipants,\r
        uint256 _averageContribution,\r
        uint256 _timeRemaining,\r
        uint256 _currentTier,\r
        uint256 _currentPrice,\r
        uint256 _softCapProgress,\r
        uint256 _hardCapProgress,\r
        uint256 _dailyPurchased,\r
        uint256 _dailyLimit\r
    ) {\r
        _totalRaised = totalRaised;\r
        _totalParticipants = totalParticipants;\r
        _averageContribution = totalParticipants > 0 ? totalRaised / totalParticipants : 0;\r
        _timeRemaining = block.timestamp < endTime ? endTime - block.timestamp : 0;\r
        _currentTier = getCurrentTier();\r
        _currentPrice = getCurrentPrice();\r
        _softCapProgress = (totalRaised * 100) / SOFT_CAP;\r
        _hardCapProgress = (totalRaised * 100) / HARD_CAP;\r
        _dailyPurchased = dailyPurchased;\r
        _dailyLimit = maxDailyPurchase;\r
    }\r
\r
    function getReferralStats(address user) external view returns (\r
        address referrer,\r
        uint256 referralEarnings_,\r
        uint256 referralCount_,\r
        uint256 totalReferralBonus\r
    ) {\r
        referrer = referrals[user];\r
        referralEarnings_ = referralEarnings[user];\r
        referralCount_ = referralCount[user];\r
        totalReferralBonus = tokensPurchased[user] > 0 ? (referralEarnings[user] * 100) / tokensPurchased[user] : 0;\r
    }\r
\r
    function getBuyerInfo(address buyer) external view returns (\r
        uint256 contribution,\r
        uint256 tokens,\r
        uint256 released,\r
        uint256 vested,\r
        uint256 remainingVestingTime\r
    ) {\r
        contribution = contributions[buyer];\r
        tokens = tokensPurchased[buyer];\r
        released = tokensReleased[buyer];\r
        vested = calculateAvailableTokens(buyer);\r
        remainingVestingTime = firstPurchaseTime[buyer] + VESTING_DURATION > block.timestamp ? (firstPurchaseTime[buyer] + VESTING_DURATION) - block.timestamp : 0;\r
    }\r
\r
    function getTierInfo(uint256 tier) external view returns (uint256 price, uint256 threshold) {\r
        require(tier > 0 && tier <= tierPrices.length, "Invalid tier");\r
        price = tierPrices[tier - 1];\r
        threshold = tierThresholds[tier - 1];\r
    }\r
\r
    function calculateAvailableTokens(address buyer) public view returns (uint256) {\r
        uint256 totalTokens = tokensPurchased[buyer];\r
        if (totalTokens == 0) return 0;\r
\r
        uint256 immediateRelease = (totalTokens * IMMEDIATE_RELEASE_PERCENT) / 100;\r
        \r
        if (block.timestamp < firstPurchaseTime[buyer]) {\r
            return immediateRelease;\r
        }\r
\r
        uint256 timeElapsed = block.timestamp - firstPurchaseTime[buyer];\r
        if (timeElapsed >= VESTING_DURATION) {\r
            return totalTokens;\r
        }\r
\r
        uint256 vestedTokens = ((totalTokens - immediateRelease) * timeElapsed) / VESTING_DURATION;\r
        return Math.min(immediateRelease + vestedTokens, totalTokens);\r
    }\r
\r
    function withdrawTokens() external nonReentrant {\r
        uint256 available = calculateAvailableTokens(msg.sender);\r
        uint256 toWithdraw = available - tokensReleased[msg.sender];\r
        require(toWithdraw > 0, "No tokens to withdraw");\r
\r
        tokensReleased[msg.sender] += toWithdraw;\r
        require(cpxToken.transfer(msg.sender, toWithdraw), "Token transfer failed");\r
        emit TokensWithdrawn(msg.sender, toWithdraw);\r
    }\r
\r
    function claimRefund() external nonReentrant {\r
        require(presaleFinalized, "Presale not finalized");\r
        require(!softCapReached, "Soft cap reached");\r
        require(contributions[msg.sender] > 0, "No contribution");\r
\r
        uint256 refundAmount = contributions[msg.sender];\r
        contributions[msg.sender] = 0;\r
        payable(msg.sender).sendValue(refundAmount);\r
    }\r
\r
    // Admin Functions\r
\r
    function extendPresale(uint256 extensionDays) external onlyMultiSig {\r
        bytes32 proposalId = keccak256(abi.encodePacked("extendPresale", extensionDays));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            _extendPresale(extensionDays);\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
\r
    function _extendPresale(uint256 extensionDays) internal {\r
        uint256 extensionSeconds = extensionDays * 1 days;\r
        require(totalExtensionTime + extensionSeconds <= MAX_EXTENSION, "Exceeds max extension");\r
        endTime += extensionSeconds;\r
        totalExtensionTime += extensionSeconds;\r
        emit PresaleExtended(endTime);\r
    }\r
\r
    function finalizePresale() external onlyMultiSig {\r
        bytes32 proposalId = keccak256(abi.encodePacked("finalizePresale"));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            _finalizePresale();\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
\r
    function _finalizePresale() internal {\r
        require(!presaleFinalized, "Already finalized");\r
        presaleFinalized = true;\r
        presaleEndTime = block.timestamp;\r
\r
        if (softCapReached) {\r
            payable(fundingWallet).sendValue(address(this).balance);\r
        }\r
        emit PresaleFinalized(totalRaised, softCapReached);\r
    }\r
\r
    function updateFundingWallet(address newWallet) external onlyMultiSig {\r
        bytes32 proposalId = keccak256(abi.encodePacked("updateFundingWallet", newWallet));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            fundingWallet = newWallet;\r
            emit FundingWalletUpdated(newWallet);\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
\r
    function addOwner(address newOwner) external onlyMultiSig {\r
        require(newOwner != address(0), "Invalid address");\r
        require(!isOwner[newOwner], "Already an owner");\r
\r
        bytes32 proposalId = keccak256(abi.encodePacked("addOwner", newOwner));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            owners.push(newOwner);\r
            isOwner[newOwner] = true;\r
            emit OwnerAdded(newOwner);\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
\r
    function removeOwner(address ownerToRemove) external onlyMultiSig {\r
        require(isOwner[ownerToRemove], "Not an owner");\r
        require(owners.length > 2, "Cannot have less than 2 owners");\r
\r
        bytes32 proposalId = keccak256(abi.encodePacked("removeOwner", ownerToRemove));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            for (uint i = 0; i < owners.length; i++) {\r
                if (owners[i] == ownerToRemove) {\r
                    owners[i] = owners[owners.length - 1];\r
                    owners.pop();\r
                    isOwner[ownerToRemove] = false;\r
                    break;\r
                }\r
            }\r
            emit OwnerRemoved(ownerToRemove);\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
\r
    function setPaused(bool _paused) external onlyMultiSig {\r
        bytes32 proposalId = keccak256(abi.encodePacked("setPaused", _paused));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            paused = _paused;\r
            emit PresalePaused(_paused);\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
\r
    function whitelistReferrer(address referrer, bool whitelisted) external onlyMultiSig {\r
        bytes32 proposalId = keccak256(abi.encodePacked("whitelistReferrer", referrer, whitelisted));\r
        confirmations[proposalId][msg.sender] = true;\r
        confirmationCount[proposalId]++;\r
\r
        if (confirmationCount[proposalId] >= requiredSignatures) {\r
            whitelistedReferrers[referrer] = whitelisted;\r
            emit ReferrerWhitelisted(referrer, whitelisted);\r
            confirmationCount[proposalId] = 0;\r
        }\r
    }\r
}\r
"
    },
    "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
      "content": "// 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);
}
"
    },
    "@openzeppelin/contracts/utils/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = 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 = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @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 {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(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 {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @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 {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 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 low / denominator;
            }

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

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, 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 ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, 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 high into low.
            low |= high * 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 high
            // is no longer required.
            result = low * 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 Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @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 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @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;
    }
}
"
    },
    "@openzeppelin/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}
"
    },
    "@openzeppelin/contracts/utils/ReentrancyGuard.sol": {
      "content": "// 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 nonReentr

Tags:
ERC20, Multisig, Voting, Timelock, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xf254b3a81cd678b24e2c23874cfd02213be49ca1|verified:true|block:23415346|tx:0x4e2696b4279e68f50775625c59ca1403f2a9ce0de3f6e04b326c411447868efd|first_check:1758534350

Submitted on: 2025-09-22 11:45:50

Comments

Log in to comment.

No comments yet.