Mazement

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": {
    "contracts/Mazement_ethdrop_2000.sol": {
      "content": "// SPDX-License-Identifier: MIT
pragma solidity ^0.8.27;

/*
===============================================================================
Mazement — ERC-721 with Waves/Tranches, Promo Tiers, and USD-Target Pricing
OpenZeppelin v5 (ERC721, ERC2981, Ownable, ReentrancyGuard)
-------------------------------------------------------------------------------
WHAT THIS CONTRACT DOES
- Sequential mints (1..MAX_SUPPLY) across waves (size=500) and tranches (+100).
- Public mint gated by `saleActive` (OFF by default until owner enables).
- Per-wave baseURI (with global fallback), plus filename prefix/extension.
- TokenURI filenames are zero-padded automatically based on MAX_SUPPLY
  (e.g., 0001 … 2000), so metadata like mazement_0001.json resolves cleanly.
- Promo for Wave 1: first N free (wallet-capped), next M discounted, then full.
- USD-target price via Chainlink ETH/USD with stale-price protection,
  or manual wei pricing toggleable by owner.
- Per-wallet-per-wave mint cap; tranche and wave caps enforced on-chain.
- EIP-2981 royalties (default 2.5% to CREATOR).
- Physical-art lifecycle flags (claimed, shipped, fulfilled).

SECURITY & DESIGN NOTES
- Uses OpenZeppelin v5 primitives (nonReentrant on payable paths and withdraw).
- Oracle path guards stale data; price rounding uses ceil to avoid underpayment.
- State updates occur before external calls; no hidden owner mint in public path.
- Admin setters restricted to `onlyOwner`; clear revert reasons throughout.

DEPLOY & OPERATE
- Deploy with `(initialBaseURI, initialMintPriceWei)`; base URI must include a trailing "/".
- Verify the source on Etherscan after deployment to make the code publicly viewable.
- Flip `setSaleActive(true)` to open minting; use tranche/wave functions to manage supply.
===============================================================================
*/

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/common/ERC2981.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // ✅ OZ v5 path
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

/// @title Mazement_Drop1
/// @notice ERC-721 with waves (500 each), tranches (+100), Chainlink USD-target pricing,
///         per-wave baseURI, Wave-1 promo pricing (10 free, next 20 at 25% off),
///         and 1-free-per-wallet guardrail.
/// @custom:version 1.4.0 (adds Wave-1 promo + quotes + per-wallet free cap)
contract Mazement is ERC721, ERC2981, Ownable, ReentrancyGuard {
    using Strings for uint256;

    // -------- Supply / sale --------
    uint256 public constant MAX_SUPPLY   = 2000;  // total across all waves
    uint256 public constant WAVE_SIZE    = 500;   // each wave = 500
    uint256 public constant TRANCHE_SIZE = 100;   // tranche step = +100
    uint256 private _nextId = 1;                  // mints 1..MAX_SUPPLY in order
    bool    public saleActive = false;

    // Waves + tranches
    uint256 public waveId = 1;                    // current wave (1-based)
    uint256 public trancheId = 1;                 // sub-release id inside current wave (1-based)
    uint256 public releaseCap = TRANCHE_SIZE;     // live cumulative mint cap (starts at 100)

    // Where this wave starts (in total minted terms)
    mapping(uint256 => uint256) public waveStartMinted;  // waveId => totalMinted() at wave start

    event ReleaseCapUpdated(uint256 oldCap, uint256 newCap);
    event WaveAdvanced(uint256 newWaveId, uint256 newReleaseCap);
    event TrancheAdvanced(uint256 waveId, uint256 newTrancheId, uint256 newReleaseCap);
    event WaveBaseURISet(uint256 indexed wave, string uri);

    // Per-wallet cap (resets per wave)
    uint256 public maxPerWalletPerWave = 2;
    mapping(uint256 => mapping(address => uint256)) public mintedByWave;
    event MaxPerWalletPerWaveUpdated(uint256 oldVal, uint256 newVal);

    // Manual (fallback) mint price in wei; owner can toggle between oracle/manual
    uint256 public mintPriceWei;

    // -------- USD-target pricing (via Chainlink) --------
    AggregatorV3Interface public ethUsdFeed;      // ETH/USD feed (mainnet proxy)
    uint256 public usdMintPrice = 200e18;         // $200 with 18 decimals
    uint256 public maxPriceAge = 2 hours;         // reject stale oracle data; changed from 1 hours to 2 hours
    bool    public useOraclePricing = true;       // if false, uses mintPriceWei

    event UsdMintPriceUpdated(uint256 oldPrice, uint256 newPrice);
    event UseOraclePricingUpdated(bool oldVal, bool newVal);
    event MaxPriceAgeUpdated(uint256 oldAge, uint256 newAge);
    event PriceFeedUpdated(address oldFeed, address newFeed);

    // -------- Metadata --------
    string  private _baseTokenURI;                // fallback base URI (used if wave-specific not set)
    string  public  filenamePrefix = "mazement_";
    string  public  filenameExtension = ".json";
    bool    public  metadataFrozen;

    // ✅ Auto pad width for tokenURI filenames
    uint8   private _padWidth;

    // Per-wave baseURI + token→wave mapping
    mapping(uint256 => string) public waveBaseURI;          // waveId => baseURI (must include trailing "/")
    mapping(uint256 => uint256) public tokenWave;           // tokenId => waveId

    // -------- Royalties (2.5%) --------
    address public constant CREATOR = 0xc646Eb7B990AFC048B7e7C2f60F8f0838ab0411B;

    // -------- Physical flags --------
    mapping(uint256 => bool) public physicalClaimed;
    mapping(uint256 => bool) public physicalShipped;
    mapping(uint256 => bool) public physicalFulfilled; // set true when shipped
    event PhysicalClaimedSet(uint256 indexed tokenId, bool claimed);
    event PhysicalShippedSet(uint256 indexed tokenId, bool shipped);
    event PhysicalFulfillmentSet(uint256 indexed tokenId, bool fulfilled);

    // === Wave-1 promo pricing (NEW) =========================================
    // First 10 mints of promo wave are FREE; next 20 are DISCOUNTED 25%; rest FULL.
    bool    public promoPricingEnabled = true;
    uint256 public promoWaveId         = 1;      // apply promo to Wave 1 only
    uint256 public promoFreeQty        = 10;      // first 10 are free
    uint256 public promoDiscountQty    = 20;     // next 20 are discounted
    uint96  public promoDiscountBps    = 2500;   // 25% off (buyer pays 75%), bps out of 10_000

    // Per-wallet cap for FREE mints in the promo wave (NEW)
    uint256 public promoFreePerWallet = 1; // set 0 to disable per-wallet free cap
    mapping(uint256 => mapping(address => uint256)) public promoFreeUsed; // waveId => wallet => count

    event PromoPricingUpdated(bool enabled, uint256 waveId, uint256 freeQty, uint256 discountQty, uint96 discountBps);
    event PromoFreePerWalletUpdated(uint256 oldVal, uint256 newVal);
    // ========================================================================

    constructor(string memory initialBaseURI, uint256 initialMintPriceWei)
        ERC721("Mazement", "MAZE")
        Ownable(msg.sender) // If using OZ v4, change to: Ownable()
    {
        _baseTokenURI = initialBaseURI;           // keep trailing "/"
        mintPriceWei  = initialMintPriceWei;      // fallback manual price
        _setDefaultRoyalty(CREATOR, 250);         // 250 bps = 2.5%

        // Chainlink ETH/USD (Ethereum mainnet proxy)
        ethUsdFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);

        // >>> Wave 1 bootstrap <<<
        waveStartMinted[1] = 0;                   // minted count at start of wave 1
        releaseCap         = TRANCHE_SIZE;        // first tranche live = 100

        // ✅ Compute pad width from MAX_SUPPLY (e.g., 2000 -> 4)
        _padWidth = _digits(MAX_SUPPLY);
    }

    // -------- Views --------
    function totalMinted() public view returns (uint256) {
        return _nextId - 1;
    }

    // Remaining of the current wave’s 500 target
    function remainingInWave() public view returns (uint256) {
        uint256 mintedThisWave = totalMinted() - waveStartMinted[waveId];
        if (mintedThisWave >= WAVE_SIZE) return 0;
        return WAVE_SIZE - mintedThisWave;
    }

    // Remaining in the current live tranche (until you open the next +100)
    function remainingInTranche() public view returns (uint256) {
        uint256 minted = totalMinted();
        return minted >= releaseCap ? 0 : (releaseCap - minted);
    }

    function _baseURI() internal view override returns (string memory) {
        return _baseTokenURI;
    }

    // ✅ Per-wave tokenURI with auto zero-padding up to _padWidth
    function tokenURI(uint256 tokenId) public view override returns (string memory) {
        _requireOwned(tokenId);
        uint256 w = tokenWave[tokenId];
        string memory base = bytes(waveBaseURI[w]).length > 0 ? waveBaseURI[w] : _baseTokenURI;

        string memory idStr = tokenId.toString();
        bytes memory b = bytes(idStr);
        if (b.length < _padWidth) {
            uint256 zeros = _padWidth - b.length;
            bytes memory z = new bytes(zeros);
            for (uint256 i = 0; i < zeros; i++) z[i] = bytes1("0");
            idStr = string(abi.encodePacked(z, idStr));
        }
        return string.concat(base, filenamePrefix, idStr, filenameExtension);
    }

    // --- Oracle-assisted pricing helpers ---
    function weiForUSD_(uint256 usdAmount18) internal view returns (uint256) {
        require(address(ethUsdFeed) != address(0), "Price feed unset");
        (, int256 answer, , uint256 updatedAt, ) = ethUsdFeed.latestRoundData();
        require(answer > 0, "Bad price");
        require(block.timestamp - updatedAt <= maxPriceAge, "Stale price");
        uint8 d = ethUsdFeed.decimals(); // typically 8
        // requiredWei = usdAmount18 * 10^d / (ETH/USD), rounded up
        return Math.mulDiv(usdAmount18, 10 ** d, uint256(answer), Math.Rounding.Ceil);
    }

    function currentMintPriceWei() public view returns (uint256) {
        return useOraclePricing ? weiForUSD_(usdMintPrice) : mintPriceWei;
    }

    // === Promo price helpers (NEW) ==========================================
    /// @dev Buyer-aware promo price (Wave-scoped): applies free-per-wallet during the FREE window.
    function _promoPriceWeiFor(address buyer) internal view returns (uint256) {
        // If promo is off or this isn't the promo wave, use full/base price.
        if (!promoPricingEnabled || waveId != promoWaveId) {
            return currentMintPriceWei();
        }

        // Position within the current wave (already minted so far).
        uint256 mintedThisWave = totalMinted() - waveStartMinted[waveId];

        // FREE tier (first promoFreeQty of the wave), gated per wallet if configured
        if (mintedThisWave < promoFreeQty) {
            bool walletHasFree = (promoFreePerWallet == 0) ||
                                 (promoFreeUsed[waveId][buyer] < promoFreePerWallet);
            if (walletHasFree) return 0;
            // else: wallet already used its free; fall through to discount/full
        }

        // DISCOUNT tier (after free, for promoDiscountQty mints)
        if (mintedThisWave < promoFreeQty + promoDiscountQty) {
            uint256 baseWei = currentMintPriceWei();
            return Math.mulDiv(baseWei, 10_000 - promoDiscountBps, 10_000, Math.Rounding.Ceil);
        }

        // FULL price for the rest
        return currentMintPriceWei();
    }

    /// @notice Price for the *next* mint (any buyer), in wei; and tier code (0=FREE,1=DISCOUNT,2=FULL).
    function quoteNextMintPriceWei() external view returns (uint256 priceWei, uint8 tier) {
        if (promoPricingEnabled && waveId == promoWaveId) {
            uint256 mintedThisWave = totalMinted() - waveStartMinted[waveId];
            if (mintedThisWave < promoFreeQty) {
                return (0, 0); // FREE (pool not exhausted)
            }
            if (mintedThisWave < promoFreeQty + promoDiscountQty) {
                uint256 baseWei = currentMintPriceWei();
                uint256 discountedWei = Math.mulDiv(baseWei, 10_000 - promoDiscountBps, 10_000, Math.Rounding.Ceil);
                return (discountedWei, 1); // DISCOUNT
            }
        }
        return (currentMintPriceWei(), 2); // FULL
    }

    /// @notice Price the given buyer would pay *if they mint next*, in wei; tier code (0=FREE,1=DISCOUNT,2=FULL).
    function quoteNextMintPriceWeiFor(address buyer) external view returns (uint256 priceWei, uint8 tier) {
        if (promoPricingEnabled && waveId == promoWaveId) {
            uint256 mintedThisWave = totalMinted() - waveStartMinted[waveId];

            // FREE (buyer has remaining free allocation and global free pool not exhausted)
            if (mintedThisWave < promoFreeQty) {
                bool walletHasFree = (promoFreePerWallet == 0) ||
                                     (promoFreeUsed[waveId][buyer] < promoFreePerWallet);
                if (walletHasFree) return (0, 0);
            }

            // DISCOUNT window (regardless of wallet's free usage)
            if (mintedThisWave < promoFreeQty + promoDiscountQty) {
                uint256 baseWei = currentMintPriceWei();
                uint256 discountedWei = Math.mulDiv(baseWei, 10_000 - promoDiscountBps, 10_000, Math.Rounding.Ceil);
                return (discountedWei, 1);
            }
        }
        return (currentMintPriceWei(), 2);
    }
    // ========================================================================

    // -------- Public mint (wave/tranche gated + per-wallet-per-wave cap) --------
    function mint() external payable nonReentrant {
        require(saleActive, "Sale inactive");
        require(totalMinted() < releaseCap, "Current wave/tranche sold out");
        require(mintedByWave[waveId][msg.sender] + 1 <= maxPerWalletPerWave, "Wave wallet cap reached");

        // --- price (buyer-aware promo) ---
        uint256 required = _promoPriceWeiFor(msg.sender);
        require(msg.value == required, "Incorrect ETH");

        // --- effects (state before external call) ---
        mintedByWave[waveId][msg.sender] += 1;

        // If this mint consumed a FREE slot for this wallet in the promo wave, record it.
        if (
            promoPricingEnabled &&
            waveId == promoWaveId &&
            required == 0
        ) {
            // Compute position before this mint to confirm we were still inside the free window
            uint256 mintedThisWaveBefore = totalMinted() - waveStartMinted[waveId];
            if (mintedThisWaveBefore < promoFreeQty && promoFreePerWallet > 0) {
                promoFreeUsed[waveId][msg.sender] += 1;
            }
        }

        uint256 tokenId = _nextId++;
        tokenWave[tokenId] = waveId;

        // Interactions
        _safeMint(msg.sender, tokenId);

        // (Optional) exact-change refund could be added here if you want to auto-refund overpay.
    }

    // -------- Owner tools --------
    function setPromoPricing(
        bool enabled,
        uint256 wave,
        uint256 freeQty,
        uint256 discountQty,
        uint96 discountBps_
    ) external onlyOwner {
        require(discountBps_ <= 10_000, "bps > 100%");
        promoPricingEnabled = enabled;
        promoWaveId         = wave;
        promoFreeQty        = freeQty;
        promoDiscountQty    = discountQty;
        promoDiscountBps    = discountBps_;
        emit PromoPricingUpdated(enabled, wave, freeQty, discountQty, discountBps_);
    }

    function setPromoFreePerWallet(uint256 n) external onlyOwner {
        emit PromoFreePerWalletUpdated(promoFreePerWallet, n);
        promoFreePerWallet = n;
    }

    function setSaleActive(bool active) external onlyOwner { saleActive = active; }

    // Start a NEW WAVE (fixed size = 500). Per-wallet counters reset.
    // - newReleaseCap: cumulative cap after opening this wave (must be within this wave’s 500 and aligned to +100)
    // - waveURI: optional baseURI for this wave
    function startNextWave(uint256 newReleaseCap, string calldata waveURI) external onlyOwner {
        require(newReleaseCap > releaseCap, "cap must increase");
        require(newReleaseCap <= MAX_SUPPLY, "cap > MAX_SUPPLY");

        uint256 prevMinted = totalMinted();
        waveId += 1;
        trancheId = 1;
        waveStartMinted[waveId] = prevMinted;

        // must be within this wave’s 500 target, and aligned to 100
        uint256 diffFromWaveStart = newReleaseCap - waveStartMinted[waveId];
        require(diffFromWaveStart > 0, "cap unchanged");
        require(diffFromWaveStart <= WAVE_SIZE, "cap exceeds wave size");
        require(diffFromWaveStart % TRANCHE_SIZE == 0, "cap not aligned to 100");

        if (bytes(waveURI).length > 0) {
            waveBaseURI[waveId] = waveURI; // must include trailing "/"
            emit WaveBaseURISet(waveId, waveURI);
        }

        emit WaveAdvanced(waveId, newReleaseCap);
        emit ReleaseCapUpdated(releaseCap, newReleaseCap);
        releaseCap = newReleaseCap;
    }

    // Open the NEXT TRANCHE inside the current wave (+100 exactly)
    function openNextTranche() external onlyOwner {
        uint256 newReleaseCap = releaseCap + TRANCHE_SIZE;
        require(newReleaseCap <= MAX_SUPPLY, "cap > MAX_SUPPLY");
        require(newReleaseCap - waveStartMinted[waveId] <= WAVE_SIZE, "cap exceeds wave size");

        trancheId += 1;
        emit TrancheAdvanced(waveId, trancheId, newReleaseCap);
        emit ReleaseCapUpdated(releaseCap, newReleaseCap);
        releaseCap = newReleaseCap;
    }

    // Safety setter (keeps wave & step rules; can jump multiple steps)
    function setReleaseCap(uint256 newCap) external onlyOwner {
        require(newCap <= MAX_SUPPLY, "cap > MAX_SUPPLY");
        require(newCap >= totalMinted(), "cap < already minted");

        uint256 diffFromWaveStart = newCap - waveStartMinted[waveId];
        require(diffFromWaveStart <= WAVE_SIZE, "cap exceeds wave size");
        require(diffFromWaveStart % TRANCHE_SIZE == 0, "cap not aligned to 100");

        emit ReleaseCapUpdated(releaseCap, newCap);
        releaseCap = newCap;

        // keep trancheId consistent with step count (1-based)
        uint256 steps = diffFromWaveStart / TRANCHE_SIZE; // 1..5 within a 500 wave
        trancheId = steps == 0 ? 1 : steps;
    }

    // Per-wave baseURI controls
    function setWaveBaseURI(uint256 wave, string calldata uri) external onlyOwner {
        waveBaseURI[wave] = uri; // must include trailing "/"
        emit WaveBaseURISet(wave, uri);
    }

    // Per-wallet-per-wave limit
    function setMaxPerWalletPerWave(uint256 n) external onlyOwner {
        emit MaxPerWalletPerWaveUpdated(maxPerWalletPerWave, n);
        maxPerWalletPerWave = n;
    }

    // Manual pricing (fallback)
    function setMintPriceWei(uint256 newPriceWei) external onlyOwner { mintPriceWei = newPriceWei; }

    // USD target & oracle controls
    function setUsdMintPrice(uint256 usdAmount18) external onlyOwner {
        emit UsdMintPriceUpdated(usdMintPrice, usdAmount18);
        usdMintPrice = usdAmount18;
    }
    function setUseOraclePricing(bool v) external onlyOwner {
        emit UseOraclePricingUpdated(useOraclePricing, v);
        useOraclePricing = v;
    }
    function setMaxPriceAge(uint256 seconds_) external onlyOwner {
        emit MaxPriceAgeUpdated(maxPriceAge, seconds_);
        maxPriceAge = seconds_;
    }
    function setPriceFeed(address feed) external onlyOwner {
        emit PriceFeedUpdated(address(ethUsdFeed), feed);
        ethUsdFeed = AggregatorV3Interface(feed);
    }

    // Global fallback baseURI
    function setBaseURI(string calldata newBaseURI) external onlyOwner {
        require(!metadataFrozen, "Metadata frozen");
        _baseTokenURI = newBaseURI; // must include trailing "/"
    }
    function setFilenamePrefix(string calldata p) external onlyOwner {
        require(!metadataFrozen, "Metadata frozen");
        filenamePrefix = p;
    }
    function setFilenameExtension(string calldata e) external onlyOwner {
        require(!metadataFrozen, "Metadata frozen");
        filenameExtension = e;
    }
    function freezeMetadata() external onlyOwner { metadataFrozen = true; }

    // -------- Physical flags setters --------
    function setPhysicalClaimed(uint256 tokenId) external onlyOwner {
        _requireOwned(tokenId);
        require(!physicalClaimed[tokenId], "Already claimed");
        physicalClaimed[tokenId] = true;
        emit PhysicalClaimedSet(tokenId, true);
    }

    function setPhysicalShipped(uint256 tokenId) public onlyOwner {
        _requireOwned(tokenId);
        require(physicalClaimed[tokenId], "Not claimed");
        require(!physicalShipped[tokenId], "Already shipped");
        physicalShipped[tokenId] = true;
        emit PhysicalShippedSet(tokenId, true);

        if (!physicalFulfilled[tokenId]) {
            physicalFulfilled[tokenId] = true;
            emit PhysicalFulfillmentSet(tokenId, true);
        }
    }

    function markFulfilled(uint256 tokenId) external onlyOwner {
        setPhysicalShipped(tokenId);
    }

    /// Withdraw proceeds
    function withdraw(address payable to) external onlyOwner nonReentrant {
        (bool ok, ) = to.call{value: address(this).balance}("");
        require(ok, "Withdraw failed");
    }

    // ----- EIP-2981 admin -----
    function setDefaultRoyalty(address receiver, uint96 feeNumerator) external onlyOwner {
        _setDefaultRoyalty(receiver, feeNumerator);
    }
    function deleteDefaultRoyalty() external onlyOwner { _deleteDefaultRoyalty(); }

    // ----- Interface wiring -----
    function supportsInterface(bytes4 iid)
        public
        view
        override(ERC721, ERC2981)
        returns (bool)
    {
        return super.supportsInterface(iid);
    }

    // ===== Helpers =====
    function _digits(uint256 n) internal pure returns (uint8 d) {
        do { d++; n /= 10; } while (n > 0);
    }
}"
    },
    "@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/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 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;
    }
}
"
    },
    "@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/Strings.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

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

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

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

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

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

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

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

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

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

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as 

Tags:
ERC721, ERC165, Multisig, Non-Fungible, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xa58bb81b1b3d96dd42e231e3fc49c29be69f1e11|verified:true|block:23537069|tx:0x3a6e1169cf5f7e352cb14d30a252a63294af82774cbf951ba81cf499904b66e7|first_check:1759996708

Submitted on: 2025-10-09 09:58:29

Comments

Log in to comment.

No comments yet.