Skip to content
Verified contractExactUNLICENSED

Sale

Address0x97000cf555138ffddbec7d6e13e6bcd76fe19598
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 100 runs
EVM version
cancun
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,388,491
Creation transaction
0x56ed93ca7b…9dfb5c76e2

45 files

src/sale/Sale.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/ICiretaIdentityRegistry.sol";
import "../fraction/CiretaFractionToken1155.sol";
import "../vault/CiretaVault.sol";
import "../otc/IssuerOTCToken.sol";

/// @dev PlatformFeeManager fee-receiver lookup (read with a validated staticcall).
interface IFeeReceiverLookup {
    function feeReceiver() external view returns (address);
    /// @dev The issuer's agreed fee and cap, re-checked by activate().
    function getFeeForIssuer(address issuer) external view returns (uint256);
    function getFeeCapForIssuer(address issuer) external view returns (uint256);
}

/// @dev The CiretaSaleFactory surface a Sale resolves its platform roles and OTC provenance from.
interface ISaleFactoryRoles {
    function governance() external view returns (address);
    function operator() external view returns (address);
    function guardian() external view returns (address);
    function isValidOTCToken(address otc, address issuer) external view returns (bool);
    function issuerRegistry() external view returns (address);
}

/// @dev Platform IssuerRegistry surface: issuer status and wallet rotation.
interface ISaleIssuerRegistry {
    function isActiveIssuer(address wallet) external view returns (bool);
    function rotatedTo(address wallet) external view returns (address);
}

/// @dev Project-token issuer state: suspension flag (CiretaToken.setIssuerSuspended) and the
///      governance-set issuer wallet (CiretaToken.setIssuer).
interface ISaleTokenSuspension {
    function isIssuerSuspended() external view returns (bool);
    function issuer() external view returns (address);
    /// @dev Address freeze on the project token (refund recovery recipient check).
    function isFrozen(address account) external view returns (bool);
}

/// @title Sale
/// @notice Multi-phase token sale with soft/hard cap, platform fee, OTC allocation and refunds.
///
///         Roles (resolved live from the deploying CiretaSaleFactory):
///         - governance (factory owner, a TimelockController): sole upgrade authority, never while
///           the sale is Active (a Paused sale can be patched), plus the 90-day emergency withdrawal.
///         - operator (Ops Safe): approve / unapprove / reject, unpause, forceFail, and finalize /
///           close while Paused. Exception: once its permissionless deadline passes, anyone
///           may end a Paused vested sale that is below its soft cap as failed, so a pause can
///           never hold refunds hostage.
///         - buyers: buy / buyOTC carry a maxCost bound, so an in-place price change (setPrice)
///           can never charge a pending buy more than the buyer accepted.
///         - guardian: pause only.
///         - factory: one-shot vested-mode wiring at deploy time.
///         - issuer: phases, activation, deposits, finalize/close while Active, fund withdrawal
///           (direct sales: also while Active, paying the platform fee owed so far first).
///           Every issuer power requires the issuer to be ACTIVE in the platform IssuerRegistry and
///           not suspended on the project token, so the operator's suspension contains a
///           compromised issuer key at once. After an IssuerRegistry wallet rotation AND the
///           governance (timelocked) CiretaToken.setIssuer, anyone calls syncIssuer() to move the
///           Sale (and its vault) to the new wallet; a registry rotation alone moves nothing.
///           The issuer may fail its own vested sale only below the soft cap.
///
///         OTC purchases count fully toward the soft cap. The issuer mints its own OTC vouchers,
///         so OTC buys can lift a vested sale over the soft cap, which disables refunds.
///         Safeguards: the OTC token must be platform-deployed for this issuer (factory-verified)
///         and can only be configured while the sale is an unapproved Draft, so the operator
///         reviews it at approval time and it cannot change afterwards.
/// @custom:security-contact [email protected]
contract Sale is Initializable, UUPSUpgradeable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    enum SaleStatus { Draft, Active, Paused, FinalizedSuccess, FinalizedFailed, Rejected }
    enum SaleMode { Direct, Vested }

    /// @notice Per-phase allocation strategy.
    /// - Fixed: phase has a hard cap in token units (`allocation`) plus any unconsumed unsold
    ///   allocation of earlier, ended Fixed phases (rollover).
    /// - Remaining: phase can buy any unsold tokens up to the global `totalTokenSupply`.
    enum AllocationMode { Fixed, Remaining }

    /// @dev Phase windows are half-open: a phase is live for start <= t < end.
    struct Phase {
        string name;
        uint256 pricePerToken;     // Payment-token raw units for 1 whole token
        uint256 allocation;        // Fixed mode only — cap in raw token units
        uint256 sold;
        uint256 minTokens;         // First-time buyer minimum (whole tokens)
        uint256 maxTokens;         // Per-investor cumulative cap (whole tokens, 0 = unlimited)
        uint256 topUpMinTokens;    // Repeat-buyer minimum per buy (whole tokens)
        uint256 startTime;
        uint256 endTime;
        bool whitelistOnly;
        AllocationMode allocationMode;
    }

    struct Contribution {
        uint256 amount;           // Total contribution (payment token + OTC) — informational
        uint256 tokensAllocated;  // Total tokens received from all sources
        bool claimed;             // Direct mode: tokens delivered at purchase
        bool refunded;
    }

    // ── State ────────────────────────────────────────────────────────────────
    address public token;
    IERC20 public paymentToken;
    ICiretaIdentityRegistry public identityRegistry;
    address public issuer;
    address public factory;     // CiretaSaleFactory — platform roles resolved through it
    address public feeManager;

    uint256 public softCap;
    uint256 public hardCap;
    uint256 public feeBasisPoints;   // e.g. 250 = 2.5%
    uint256 public feeCapUsdc;       // Absolute max fee in payment-token units (6 decimals), 0 = uncapped

    // Sale-level window. saleEndTime == 0 means open-ended.
    uint256 public saleStartTime;
    uint256 public saleEndTime;

    /// @notice Max tokens sellable across all phases (token raw units, whole tokens only).
    uint256 public totalTokenSupply;
    uint256 public totalTokenSold;

    uint8 public tokenDecimals;

    uint256 public constant MAX_FEE_BPS = 1000;
    uint256 public constant MAX_SALE_DURATION = 730 days;
    uint256 public constant INACTIVITY_TIMEOUT = 180 days;
    /// @notice After a fixed-end sale's end + this grace, anyone may finalize it.
    uint256 public constant FINALIZE_GRACE_PERIOD = 30 days;
    /// @notice Bound on the phases array so every phase loop stays well under the block gas limit.
    uint256 public constant MAX_PHASES = 64;
    /// @notice Bound on the IssuerRegistry rotation chain syncIssuer follows.
    uint256 public constant MAX_ROTATION_HOPS = 8;

    uint256 public totalRaised;              // payment-token + OTC (both 6 decimals)
    uint256 public paymentContributedTotal;  // payment-token buys only — fee base
    uint256 public platformFeeCollected;     // total fee assessed at successful finalization
    /// @notice Assessed fee not yet paid to the PFM fee receiver. Set at finalization to the
    ///         total fee minus what a live direct sale already paid (platformFeePaid).
    uint256 public platformFeeOwed;

    SaleStatus public status;
    Phase[] public phases;

    mapping(uint256 => mapping(address => bool)) public whitelisted;
    mapping(address => Contribution) public contributions;
    mapping(address => uint256) public totalContributed;
    /// @notice Payment-token amount each buyer paid (informational; zeroed when it refunds).
    ///         Refund entitlement follows the ID-1 fractions — see CiretaVault.refundBasis.
    mapping(address => uint256) public paymentContributed;
    mapping(address => uint256) public otcContributed;

    bool public approved;
    bool public openEnded;
    bool public finalizationPending;
    /// @notice True once a vested sale has failed; refunds then open automatically.
    bool public refundsActive;
    uint256 public lastPhaseAddedAt;

    /// @notice Unsold Fixed-phase allocation already consumed by later Fixed phases.
    uint256 public rolloverConsumed;
    uint256 public totalRefunded;

    // ── Vested mode state ─────────────────────────────────────────────────────
    SaleMode public saleMode;
    CiretaVault public vault;
    CiretaFractionToken1155 public fractionToken;
    uint256 public constant FRACTION_ID_USDC = 1;
    uint256 public constant FRACTION_ID_OTC = 2;

    // ── OTC token state ──────────────────────────────────────────────────────
    IssuerOTCToken public otcToken;

    // ── Emergency withdrawal ────────────────────────────────────────────────
    uint256 public finalizedAt;
    uint256 public constant EMERGENCY_WITHDRAW_DELAY = 90 days;

    /// @notice Incremented on every UUPS upgrade.
    uint256 public upgradeNonce;

    /// @notice When the sale was last paused (a Paused sale takes no money).
    uint256 public pausedAt;

    /// @notice Failed-sale refunds settled on a holder's behalf but not yet paid out.
    ///         Only the holder (claimRefund) or the operator (recoverRefund, lost keys) pays it out.
    mapping(address => uint256) public refundCredit;
    /// @notice Sum of every outstanding refundCredit.
    uint256 public totalRefundCredit;

    /// @notice A different fee offered by the operator while Draft. It applies only when the
    ///         issuer accepts these exact terms (acceptFeeTerms).
    uint256 public offeredFeeBps;
    uint256 public offeredFeeCapUsdc;
    bool public feeOfferPending;

    /// @notice Running total paid to the issuer by withdrawFunds.
    uint256 public totalWithdrawnToIssuer;
    /// @notice Running total of platform fee paid to the fee receiver: payments a live direct
    ///         sale makes before finalization, and every payment after it.
    uint256 public platformFeePaid;
    /// @notice The issuer turned live withdrawals off: a direct sale then pays the issuer only
    ///         after FinalizedSuccess. Off is false by default (live withdrawals
    ///         on); only the issuer sets it, only while an unapproved Draft, so it locks at approval:
    ///         the operator approves the setting it reviewed.
    bool public liveWithdrawalsOff;
    /// @notice The fee terms came from an accepted operator offer (acceptFeeTerms). Until
    ///         then activate() requires the sale's fee and cap to equal the issuer's current agreed
    ///         terms in the PlatformFeeManager; an accepted offer is kept as agreed.
    bool public feeTermsAccepted;

    /// @dev Reserved storage gap for future upgrades. 97 slots are reserved in total; the six
    ///      slots above (offeredFeeBps..feeOfferPending, totalWithdrawnToIssuer..liveWithdrawalsOff,
    ///      with feeTermsAccepted packed into liveWithdrawalsOff's slot) came out of it, leaving 91.
    uint256[91] private __gap;

    // ── Events ───────────────────────────────────────────────────────────────
    event PhaseAdded(uint256 indexed phaseId, string name, uint256 pricePerToken);
    event PhaseExtended(uint256 indexed phaseId, uint256 newEndTime);
    event PhaseShortened(uint256 indexed phaseId, uint256 newEndTime);
    event PhaseAdvanced(uint256 indexed phaseId, uint256 newStartTime);
    event Purchase(address indexed buyer, uint256 indexed phaseId, uint256 amount, uint256 tokensAllocated, bool isOTC);
    event RefundClaimed(address indexed contributor, uint256 amount);
    /// @notice A holder's ID-1 position was settled into refundCredit without a payment.
    event RefundCredited(address indexed holder, uint256 amount, address indexed by);
    /// @notice The operator paid a holder's refund to a replacement wallet (lost key).
    event RefundRecovered(address indexed holder, address indexed to, uint256 amount, address indexed by);
    event SaleFinalized(bool success, uint256 totalRaised, uint256 platformFee);
    event SaleStatusChanged(SaleStatus newStatus);
    event WhitelistUpdated(uint256 indexed phaseId, uint256 count, bool allow);
    event EmergencyWithdraw(address indexed recipient, uint256 amount);
    event ProjectTokensDeposited(uint256 amount);
    event FundsWithdrawn(address indexed recipient, uint256 amount);
    event TokensWithdrawn(address indexed recipient, uint256 amount);
    event PlatformFeeWithdrawn(address indexed receiver, uint256 amount);
    /// @notice One summary per withdrawFunds: paid to the issuer, fee paid to the receiver
    ///         in the same call, fee left reserved on the Sale, and both running totals.
    event ProceedsWithdrawn(
        address indexed recipient,
        uint256 amountToIssuer,
        uint256 feePaidNow,
        uint256 feeReserved,
        uint256 totalWithdrawnToIssuer,
        uint256 totalFeePaid
    );
    /// @notice A withdrawal could not pay the fee (receiver blocked, or none set); it stays reserved
    ///         on the Sale for withdrawPlatformFee.
    event PlatformFeeReserved(address indexed receiver, uint256 amount);
    /// @notice The issuer's choice of live withdrawals on a direct sale, set while Draft.
    event LiveWithdrawalsSet(bool enabled);
    event FeeTermsOffered(uint256 feeBps, uint256 feeCapUsdc);
    event FeeOfferCancelled(address indexed by);
    event FeeTermsChanged(uint256 oldFeeBps, uint256 oldFeeCapUsdc, uint256 feeBps, uint256 feeCapUsdc);
    event SaleApproved();
    event SaleUnapproved();
    event FinalizationPending(uint256 totalRaised, uint256 totalTokenSold);
    event RefundsActivated();
    event SaleClosed(bool failed, address closer);
    event VestedModeSet(address indexed vault, address indexed fractionToken);
    event OTCTokenSet(address indexed previousToken, address indexed newToken);
    /// @notice The issuer changed the price of the live phase of a direct sale (in place).
    event PriceUpdated(uint256 indexed previousPhaseId, uint256 indexed newPhaseId, uint256 oldPrice, uint256 newPrice);
    event ImplementationUpgraded(address indexed newImplementation, uint256 nonce);
    /// @notice The Sale followed an IssuerRegistry wallet rotation.
    event IssuerSynced(address indexed previousIssuer, address indexed newIssuer);

    // ── Errors ───────────────────────────────────────────────────────────────
    error InvalidStatus();
    error NotAdmin();
    error NotIssuer();
    error NotIssuerOrAdmin();
    error ZeroAddress();
    error AlreadyClaimed();
    error InvalidPhase();
    error PhaseNotStarted();
    error PhaseEnded();
    error BelowMinContribution();
    error ExceedsMaxContribution();
    error ExceedsHardCap();
    error KYCRequired();
    error NotWhitelisted();
    error ExceedsAllocation();
    error CannotAddPhase();
    error ZeroMinContribution();
    error InvalidCaps();
    error InvalidFeeBps();
    error FeeOfferMismatch();
    /// @dev activate(): the fee or cap differs from the issuer's current agreed terms and no offer
    ///      was accepted. Fix while Draft: the operator offers the agreed terms
    ///      and the issuer accepts them.
    error FeeTermsStale();
    error InvalidSaleWindow();
    error ZeroPricePerToken();
    error InvalidPhaseTimeRange();
    error PhaseOutsideSaleWindow();
    error PhaseInPast();
    error WhitelistPhaseAlreadyStarted();
    error InvalidContributionRange();
    error ZeroPhaseAllocation();
    error IssuerNotVerified();
    error CannotFinalize();
    error OTCNotEnabled();
    error NothingToWithdraw();
    error SaleNotFinalized();
    error TokensNotDeposited();
    error DelayNotElapsed();
    error ZeroTokenSupply();
    error SaleWindowTooLong();
    error TokenSupplyExceeded();
    error PhaseOverlap();
    error CannotExtendEnded();
    error ExtensionTooEarly();
    error ExtensionOverlap();
    error TopUpBelowMin();
    error PhaseStillActive();
    error PhaseAlreadyStarted();
    error ShortenMustReduce();
    error AdvanceMustReduce();
    error NotApproved();
    error AlreadyApproved();
    error RefundsNotActive();
    error NotPaymentContributor();
    /// @notice Refund recovery recipient is not verified, or is frozen on the project token.
    error InvalidRefundRecipient(address to);
    error AmountTooSmall();
    error InsufficientOTCBalance();
    error OTCNotApproved();
    error RefundsNotApplicable();
    error OnlyDirectMode();
    error NoActivePhase();
    error TooManyPhases();
    error InvalidOTCToken();
    error VaultMismatch();
    error InvalidFeeReceiver();
    error InvalidPaymentToken();
    error InvalidTokenSupply();
    /// @notice The buy would cost more than the buyer's `maxCost` bound (the price changed).
    error SlippageExceeded(uint256 cost, uint256 maxCost);
    /// @notice The IssuerRegistry records no rotation of the current issuer wallet.
    error IssuerNotRotated();
    /// @notice The rotation is not (yet) confirmed by governance on the project token.
    error IssuerNotConfirmed(address tokenIssuer);
    /// @notice The issuer cannot fail a vested sale that reached its soft cap.
    error SoftCapReached();

    // ── Access Control ──────────────────────────────────────────────────────

    /// @notice Platform governance (timelock): upgrade + emergency-withdraw authority.
    function governance() public view returns (address) {
        return ISaleFactoryRoles(factory).governance();
    }

    /// @notice Platform operator: approve / reject / unpause / forceFail.
    function operator() public view returns (address) {
        return ISaleFactoryRoles(factory).operator();
    }

    /// @notice Platform guardian: pause only.
    function guardian() public view returns (address) {
        return ISaleFactoryRoles(factory).guardian();
    }

    /// @notice Backward-compatible alias for the platform operator.
    function admin() external view returns (address) {
        return operator();
    }

    // Each modifier calls a private check, so its body is not inlined at every use (bytecode size).
    modifier onlyOperator() {
        _checkOperator();
        _;
    }

    function _checkOperator() private view {
        if (msg.sender != operator()) revert NotAdmin();
    }

    modifier onlyIssuer() {
        _checkIssuer();
        _;
    }

    function _checkIssuer() private view {
        if (!_isActiveIssuer(msg.sender)) revert NotIssuer();
    }

    /// @dev `account` is the issuer, ACTIVE in the platform IssuerRegistry (when the factory
    ///      exposes one) and not suspended on the project token. When the token reports an
    ///      issuer() it must also be that live issuer: CiretaToken.setIssuer clears
    ///      the token suspension, so the rotated-out key must not regain the Sale before syncIssuer.
    function _isActiveIssuer(address account) internal view returns (bool) {
        if (account != issuer) return false;
        address live = _tokenIssuer();
        if (live != address(0) && live != account) return false;
        address reg = _issuerRegistry();
        if (reg != address(0) && !ISaleIssuerRegistry(reg).isActiveIssuer(account)) return false;
        (bool ok, uint256 suspended) = _staticWord(token, ISaleTokenSuspension.isIssuerSuspended.selector, address(0), 4);
        return !(ok && suspended != 0);
    }

    /// @dev The platform IssuerRegistry read through the factory (zero if it exposes none).
    function _issuerRegistry() internal view returns (address) {
        return _staticAddress(factory, ISaleFactoryRoles.issuerRegistry.selector);
    }

    modifier onlyStatus(SaleStatus s) {
        _checkStatus(s);
        _;
    }

    function _checkStatus(SaleStatus s) private view {
        if (status != s) revert InvalidStatus();
    }

    /// @dev Issuer configuration edits are only allowed while Draft or Active — never while an
    ///      operator pause is in force, nor after finalization.
    modifier whenEditable() {
        _checkEditable();
        _;
    }

    function _checkEditable() private view {
        if (status != SaleStatus.Draft && status != SaleStatus.Active) revert InvalidStatus();
    }

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() { _disableInitializers(); }

    /// @notice Sale initializer. Every security-relevant field is re-verified by the factory.
    /// @param _feeCapUsdc Absolute fee cap in payment-token units; 0 = uncapped.
    /// @param _saleEndTime Pass 0 for an open-ended sale.
    /// @param _totalTokenSupply Max tokens sellable across all phases (raw units, whole tokens).
    function initialize(
        address _token,
        address _paymentToken,
        address _identityRegistry,
        address _issuer,
        address _factory,
        address _feeManager,
        uint256 _softCap,
        uint256 _hardCap,
        uint256 _feeBasisPoints,
        uint256 _feeCapUsdc,
        address _otcToken,
        uint256 _saleStartTime,
        uint256 _saleEndTime,
        uint256 _totalTokenSupply
    ) external initializer {
        if (_token == address(0) || _paymentToken == address(0) || _identityRegistry == address(0)) revert ZeroAddress();
        if (_issuer == address(0) || _factory == address(0) || _feeManager == address(0)) revert ZeroAddress();
        if (_softCap == 0 || _hardCap == 0 || _softCap > _hardCap) revert InvalidCaps();
        if (_feeBasisPoints > MAX_FEE_BPS) revert InvalidFeeBps();
        if (_totalTokenSupply == 0) revert ZeroTokenSupply();
        // totalRaised, feeCapUsdc and OTC vouchers are 6-decimal amounts.
        if (IERC20Metadata(_paymentToken).decimals() != 6) revert InvalidPaymentToken();
        if (_saleEndTime == 0) {
            if (_saleStartTime == 0) revert InvalidSaleWindow();
            openEnded = true;
        } else {
            if (_saleStartTime >= _saleEndTime) revert InvalidSaleWindow();
            if (_saleEndTime <= block.timestamp) revert InvalidSaleWindow();
            if (_saleEndTime - _saleStartTime > MAX_SALE_DURATION) revert SaleWindowTooLong();
        }
        if (!ICiretaIdentityRegistry(_identityRegistry).isVerified(_issuer)) revert IssuerNotVerified();

        token = _token;
        paymentToken = IERC20(_paymentToken);
        identityRegistry = ICiretaIdentityRegistry(_identityRegistry);
        issuer = _issuer;
        factory = _factory;
        feeManager = _feeManager;
        softCap = _softCap;
        hardCap = _hardCap;
        feeBasisPoints = _feeBasisPoints;
        feeCapUsdc = _feeCapUsdc;
        saleStartTime = _saleStartTime;
        saleEndTime = _saleEndTime;
        totalTokenSupply = _totalTokenSupply;
        lastPhaseAddedAt = _saleStartTime;

        try IERC20Metadata(_token).decimals() returns (uint8 d) {
            tokenDecimals = d;
        } catch {
            tokenDecimals = 18;
        }
        if (tokenDecimals > 36) revert InvalidTokenSupply();
        // Only whole tokens are sold, so a fractional remainder could never be sold.
        if (_totalTokenSupply % (10 ** tokenDecimals) != 0) revert InvalidTokenSupply();

        if (_otcToken != address(0)) otcToken = IssuerOTCToken(_otcToken);
        status = SaleStatus.Draft;
    }

    /// @dev Upgrades: platform governance only, never while the sale is Active. A Paused sale
    ///      may be upgraded, so a live bug can be paused, patched and resumed; the governance
    ///      timelock makes every upgrade public before it lands.
    function _authorizeUpgrade(address newImplementation) internal override {
        if (msg.sender != governance()) revert NotAdmin();
        if (status == SaleStatus.Active) revert InvalidStatus();
        upgradeNonce++;
        emit ImplementationUpgraded(newImplementation, upgradeNonce);
    }

    /// @notice Contract version.
    function version() external pure returns (string memory) { return "8.6.1"; }

    /// @notice Follow an issuer wallet rotation: moves this Sale's issuer, and its
    ///         vault's, to the wallet the project token's governance has confirmed.
    /// @dev Permissionless, but it only moves to `CiretaToken(token).issuer()`, and only when that
    ///      wallet is reached from the current issuer through IssuerRegistry.rotatedTo (at most
    ///      MAX_ROTATION_HOPS hops). The registry rotation alone (ISSUER_MANAGER_ROLE, no timelock)
    ///      can therefore never redirect proceeds, unsold tokens or returned deposits: governance
    ///      must first move the token with the timelocked CiretaToken.setIssuer. A token without
    ///      issuer() (non-platform token) never syncs.
    function syncIssuer() external {
        address reg = _issuerRegistry();
        address current = issuer;
        address next = reg == address(0) ? address(0) : ISaleIssuerRegistry(reg).rotatedTo(current);
        if (next == address(0)) revert IssuerNotRotated();
        address confirmed = _tokenIssuer();
        for (uint256 hops = 1; next != confirmed; hops++) {
            if (hops >= MAX_ROTATION_HOPS) revert IssuerNotConfirmed(confirmed);
            next = ISaleIssuerRegistry(reg).rotatedTo(next);
            if (next == address(0)) revert IssuerNotConfirmed(confirmed);
        }
        emit IssuerSynced(current, next);
        issuer = next;
        if (saleMode == SaleMode.Vested) vault.setIssuer(next);
    }

    /// @dev The project token's governance-set issuer (zero if the token exposes none).
    function _tokenIssuer() internal view returns (address) {
        return _staticAddress(token, ISaleTokenSuspension.issuer.selector);
    }

    // ── Operator / Factory ──────────────────────────────────────────────────

    /// @notice Operator approves the Draft sale (compliance gate). The issuer then activates it.
    function approveSale() external onlyOperator onlyStatus(SaleStatus.Draft) {
        if (approved) revert AlreadyApproved();
        approved = true;
        emit SaleApproved();
    }

    /// @notice Operator revokes approval before the issuer activates.
    function unapproveSale() external onlyOperator onlyStatus(SaleStatus.Draft) {
        if (!approved) revert NotApproved();
        approved = false;
        emit SaleUnapproved();
    }

    /// @notice Issuer activates an approved sale. Vested sales must have the full sellable
    ///         supply escrowed in the vault; direct sales need inventory on the Sale.
    ///         Unless the fee came from an accepted offer, it must still equal the issuer's agreed
    ///         fee and cap in the PlatformFeeManager, up or down.
    function activate() external onlyIssuer onlyStatus(SaleStatus.Draft) {
        if (!approved) revert NotApproved();
        if (!feeTermsAccepted) {
            // msg.sender is the issuer (onlyIssuer); the fee manager follows wallet rotations. A
            // failed lookup fails closed (FeeTermsStale).
            (bool okFee, uint256 fee) =
                _staticWord(feeManager, IFeeReceiverLookup.getFeeForIssuer.selector, msg.sender, 0x24);
            (bool okCap, uint256 cap) =
                _staticWord(feeManager, IFeeReceiverLookup.getFeeCapForIssuer.selector, msg.sender, 0x24);
            if (!okFee || !okCap || fee != feeBasisPoints || cap != feeCapUsdc) revert FeeTermsStale();
        }
        if (phases.length == 0) revert InvalidStatus();
        if (saleMode == SaleMode.Direct) {
            if (IERC20(token).balanceOf(address(this)) == 0) revert TokensNotDeposited();
        } else {
            if (vault.totalLocked() - vault.totalReleased() < totalTokenSupply) revert TokensNotDeposited();
        }
        status = SaleStatus.Active;
        emit SaleStatusChanged(SaleStatus.Active);
    }

    /// @notice Reject the Draft sale permanently. The issuer recovers deposited project tokens
    ///         with withdrawTokens() (direct: from the Sale; vested: returned by the vault).
    function reject() external onlyOperator onlyStatus(SaleStatus.Draft) {
        status = SaleStatus.Rejected;
        emit SaleStatusChanged(SaleStatus.Rejected);
    }

    /// @notice Lift a pause. Operator only.
    function unpause() external onlyOperator onlyStatus(SaleStatus.Paused) {
        status = SaleStatus.Active;
        emit SaleStatusChanged(SaleStatus.Active);
    }

    /// @notice Operator ends a live vested sale as failed regardless of phase windows (compliance
    ///         action); refunds open immediately.
    function forceFail() external onlyOperator nonReentrant {
        if (status != SaleStatus.Active && status != SaleStatus.Paused) revert InvalidStatus();
        if (saleMode != SaleMode.Vested) revert RefundsNotApplicable();
        _finalize(false);
        emit SaleClosed(true, msg.sender);
    }

    /// @notice Factory wires vested mode at deploy time. The vault and fraction must be bound to
    ///         this sale, its token and its issuer.
    function setVestedMode(address _vault, address _fractionToken) external onlyStatus(SaleStatus.Draft) {
        if (msg.sender != factory) revert NotAdmin();
        if (saleMode == SaleMode.Vested) revert InvalidStatus();
        if (_vault == address(0) || _fractionToken == address(0)) revert ZeroAddress();
        CiretaVault v = CiretaVault(_vault);
        CiretaFractionToken1155 f = CiretaFractionToken1155(_fractionToken);
        if (
            address(v.projectToken()) != token || v.sale() != address(this) || v.issuer() != issuer
                || address(v.fractionToken()) != _fractionToken || f.vault() != _vault || f.projectToken() != token
        ) revert VaultMismatch();
        saleMode = SaleMode.Vested;
        vault = v;
        fractionToken = f;
        emit VestedModeSet(_vault, _fractionToken);
    }

    // ── Issuer-Only Functions ───────────────────────────────────────────────

    /// @notice Add a sale phase (Draft or Active). Whole-token units for min/max/topUp.
    /// @param minTokens First-time buyer minimum (whole tokens)
    /// @param maxTokens Per-investor cumulative cap (whole tokens, 0 = unlimited)
    /// @param topUpMinTokens Repeat-buyer minimum per buy (whole tokens)
    function addPhase(
        string calldata name,
        uint256 pricePerToken,
        uint256 allocation,
        uint256 minTokens,
        uint256 maxTokens,
        uint256 topUpMinTokens,
        uint256 startTime,
        uint256 endTime,
        bool whitelistOnly,
        AllocationMode allocationMode
    ) external onlyIssuer {
        if (status != SaleStatus.Draft && status != SaleStatus.Active) revert CannotAddPhase();
        if (phases.length >= MAX_PHASES) revert TooManyPhases();
        if (pricePerToken == 0) revert ZeroPricePerToken();
        if (minTokens == 0 || topUpMinTokens == 0) revert ZeroMinContribution();
        if (maxTokens != 0 && maxTokens < minTokens) revert InvalidContributionRange();
        if (startTime >= endTime) revert InvalidPhaseTimeRange();
        if (endTime <= block.timestamp) revert PhaseInPast();
        // The whitelist can only be edited before the phase starts (setWhitelist), so a
        // whitelist-only phase that has already started could never admit a buyer.
        if (whitelistOnly && startTime <= block.timestamp) revert WhitelistPhaseAlreadyStarted();
        if (startTime < saleStartTime) revert PhaseOutsideSaleWindow();
        _checkWithinSaleWindow(endTime);

        // Half-open windows: adjacent phases (A.end == B.start) do not overlap.
        for (uint256 i = 0; i < phases.length; i++) {
            Phase storage existing = phases[i];
            if (startTime < existing.endTime && existing.startTime < endTime) revert PhaseOverlap();
        }

        if (allocationMode == AllocationMode.Fixed) {
            if (allocation == 0) revert ZeroPhaseAllocation();
            if (_totalFixedAllocations() + allocation > totalTokenSupply) revert TokenSupplyExceeded();
        }

        phases.push(Phase({
            name: name,
            pricePerToken: pricePerToken,
            allocation: allocation,
            sold: 0,
            minTokens: minTokens,
            maxTokens: maxTokens,
            topUpMinTokens: topUpMinTokens,
            startTime: startTime,
            endTime: endTime,
            whitelistOnly: whitelistOnly,
            allocationMode: allocationMode
        }));
        lastPhaseAddedAt = block.timestamp;
        emit PhaseAdded(phases.length - 1, name, pricePerToken);
    }

    /// @notice Extend the end time of a live or upcoming phase. Not while Paused.
    function extendPhase(uint256 phaseId, uint256 newEndTime) external onlyIssuer whenEditable {
        if (phaseId >= phases.length) revert InvalidPhase();
        Phase storage p = phases[phaseId];
        if (block.timestamp >= p.endTime) revert CannotExtendEnded();
        if (newEndTime <= p.endTime) revert ExtensionTooEarly();

        for (uint256 i = 0; i < phases.length; i++) {
            if (i == phaseId) continue;
            Phase storage other = phases[i];
            if (other.startTime >= p.endTime && other.startTime < newEndTime) revert ExtensionOverlap();
        }
        _checkWithinSaleWindow(newEndTime);

        p.endTime = newEndTime;
        emit PhaseExtended(phaseId, newEndTime);
    }

    /// @notice Shorten a phase's end time (>= now; == now closes it immediately). Not while Paused.
    function shortenPhase(uint256 phaseId, uint256 newEndTime) external onlyIssuer whenEditable {
        if (phaseId >= phases.length) revert InvalidPhase();
        Phase storage p = phases[phaseId];
        if (newEndTime >= p.endTime) revert ShortenMustReduce();
        if (newEndTime < block.timestamp) revert PhaseInPast();
        if (newEndTime < p.startTime) revert InvalidPhaseTimeRange();
        p.endTime = newEndTime;
        emit PhaseShortened(phaseId, newEndTime);
    }

    /// @notice Bring an upcoming phase's start forward. Not while Paused.
    function advancePhaseStart(uint256 phaseId, uint256 newStartTime) external onlyIssuer whenEditable {
        if (phaseId >= phases.length) revert InvalidPhase();
        Phase storage p = phases[phaseId];
        if (block.timestamp >= p.startTime) revert PhaseAlreadyStarted();
        if (newStartTime >= p.startTime) revert AdvanceMustReduce();
        if (newStartTime < block.timestamp) revert PhaseInPast();
        if (newStartTime < saleStartTime) revert PhaseOutsideSaleWindow();

        for (uint256 i = 0; i < phases.length; i++) {
            if (i == phaseId) continue;
            Phase storage other = phases[i];
            if (newStartTime < other.endTime && other.startTime < p.endTime) revert PhaseOverlap();
        }

        p.startTime = newStartTime;
        emit PhaseAdvanced(phaseId, newStartTime);
    }

    /// @notice Update the price of the live phase of a direct sale, in place. The phase keeps
    ///         its allocation, sales, caps and whitelist, no stale-price phase
    ///         remains buyable, and the phases array does not grow. Pending buys
    ///         are protected by their own `maxCost` bound: a price rise makes them revert.
    /// @dev Direct mode only: vested rounds commit to a price per phase.
    /// @param newPrice New payment-token price for one whole project token.
    function setPrice(uint256 newPrice) external onlyIssuer {
        if (saleMode != SaleMode.Direct) revert OnlyDirectMode();
        if (status != SaleStatus.Active) revert InvalidStatus();
        if (newPrice == 0) revert ZeroPricePerToken();
        uint256 phaseId = _activePhaseId();
        if (phaseId == type(uint256).max) revert NoActivePhase();
        Phase storage p = phases[phaseId];
        uint256 oldPrice = p.pricePerToken;
        p.pricePerToken = newPrice;
        emit PriceUpdated(phaseId, phaseId, oldPrice, newPrice);
    }

    /// @notice Remaining tokens available for sale across all phases.
    function getRemainingSupply() external view returns (uint256) {
        return totalTokenSupply - totalTokenSold;
    }

    /// @notice Manage the investor whitelist of a phase that has not started. Not while Paused.
    function setWhitelist(uint256 phaseId, address[] calldata addresses, bool allow) external onlyIssuer whenEditable {
        if (phaseId >= phases.length) revert InvalidPhase();
        if (block.timestamp >= phases[phaseId].startTime) revert PhaseStillActive();
        for (uint256 i = 0; i < addresses.length; i++) {
            whitelisted[phaseId][addresses[i]] = allow;
        }
        emit WhitelistUpdated(phaseId, addresses.length, allow);
    }

    /// @notice Set or clear the OTC token. Only while the sale is an unapproved Draft, and only
    ///         to an OTC token the platform factory deployed for this issuer (see the OTC note in
    ///         the contract header).
    function setOTCToken(address _otcToken) external onlyIssuer {
        if (status != SaleStatus.Draft || approved) revert InvalidStatus();
        if (_otcToken != address(0) && !ISaleFactoryRoles(factory).isValidOTCToken(_otcToken, issuer)) {
            revert InvalidOTCToken();
        }
        address previous = address(otcToken);
        otcToken = IssuerOTCToken(_otcToken);
        emit OTCTokenSet(previous, _otcToken);
    }

    /// @notice Escrow project tokens in the vault (vested mode, Draft or Active only).
    function depositProjectTokens(uint256 amount) external onlyIssuer nonReentrant whenEditable {
        if (saleMode != SaleMode.Vested) revert InvalidStatus();
        IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
        IERC20(token).forceApprove(address(vault), amount);
        vault.depositTokens(amount);
        emit ProjectTokensDeposited(amount);
    }

    /// @notice Recover project tokens from a sale that never sold or failed.
    ///         Direct: Draft/Rejected, tokens held by the Sale. Vested: Draft/Rejected/
    ///         FinalizedFailed, the vault returns the whole escrow to the issuer.
    function withdrawTokens() external onlyIssuer nonReentrant {
        bool vested = saleMode == SaleMode.Vested;
        if (
            status != SaleStatus.Draft && status != SaleStatus.Rejected
                && !(vested && status == SaleStatus.FinalizedFailed)
        ) revert InvalidStatus();

        uint256 amount = vested ? vault.returnDeposit() : 0;
        uint256 held = IERC20(token).balanceOf(address(this));
        if (held > 0) IERC20(token).safeTransfer(issuer, held);
        amount += held;
        if (amount == 0) revert NothingToWithdraw();
        emit TokensWithdrawn(issuer, amount);
    }

    /// @notice Withdraw unsold project tokens after a successful sale.
    ///         Direct: tokens left on the Sale. Vested: escrow not backing outstanding fractions
    ///         (the vault pays the issuer).
    function withdrawUnsoldTokens() external onlyIssuer nonReentrant {
        if (status != SaleStatus.FinalizedSuccess) revert SaleNotFinalized();
        if (saleMode == SaleMode.Vested) {
            vault.withdrawExcess();
        } else {
            uint256 balance = IERC20(token).balanceOf(address(this));
            if (balance == 0) revert NothingToWithdraw();
            IERC20(token).safeTransfer(issuer, balance);
            emit TokensWithdrawn(issuer, balance);
        }
    }

    /// @notice Withdraw everything available to the issuer: the payment-token balance minus the
    ///         platform fee still unpaid (no amount parameter).
    ///         - Direct: while Active and after FinalizedSuccess. Each withdrawal first pays
    ///           the fee owed so far to the fee receiver; if that payment fails (e.g. the receiver is
    ///           blocked by the payment token) the withdrawal still goes through and the fee stays
    ///           reserved on the Sale for withdrawPlatformFee. The issuer never receives it.
    ///         - Vested: after FinalizedSuccess only; the fee is left for withdrawPlatformFee.
    ///         Never while Paused (no money leaves a Paused sale). Governance can reach these funds
    ///         only via emergencyWithdraw (90 days after finalization) or a timelocked upgrade.
    function withdrawFunds() external onlyIssuer nonReentrant {
        if (!_canWithdraw()) revert SaleNotFinalized();
        uint256 paidNow = saleMode == SaleMode.Direct ? _tryPayFee() : 0;
        uint256 reserved = platformFeeOutstanding();
        uint256 balance = paymentToken.balanceOf(address(this));
        if (balance <= reserved) revert NothingToWithdraw();
        uint256 amount = balance - reserved;
        uint256 total = totalWithdrawnToIssuer += amount;
        paymentToken.safeTransfer(issuer, amount);
        emit FundsWithdrawn(issuer, amount);
        emit ProceedsWithdrawn(issuer, amount, paidNow, reserved, total, platformFeePaid);
    }

    /// @notice What withdrawFunds would pay the issuer now, if its fee payment goes through.
    function availableToWithdraw() external view returns (uint256) {
        if (!_canWithdraw()) return 0;
        uint256 balance = paymentToken.balanceOf(address(this));
        uint256 fee = platformFeeOutstanding();
        return balance > fee ? balance - fee : 0;
    }

    /// @notice Platform fee owed now and not yet paid to the fee receiver: platformFeeOwed after a
    ///         successful finalization; on a direct sale before it, the fee on the payment-token
    ///         raise so far (bps, capped; OTC excluded) minus platformFeePaid. Zero for a vested sale
    ///         before finalization.
    function platformFeeOutstanding() public view returns (uint256) {
        if (status == SaleStatus.FinalizedSuccess) return platformFeeOwed;
        if (saleMode == SaleMode.Direct) return _fee(paymentContributedTotal) - platformFeePaid;
        return 0;
    }

    /// @dev withdrawFunds may run: FinalizedSuccess, or a direct sale while Active unless its issuer
    ///      turned live withdrawals off.
    function _canWithdraw() private view returns (bool) {
        return status == SaleStatus.FinalizedSuccess
            || (status == SaleStatus.Active && saleMode == SaleMode.Direct && !liveWithdrawalsOff);
    }

    /// @notice The issuer chooses whether a direct sale pays out while live (on by default). Only
    ///         while an unapproved Draft, like setOTCToken: the choice locks at approval, so
    ///         the operator approves what it reviewed. The platform can read it, never change it.
    function setLiveWithdrawals(bool enabled) external onlyIssuer {
        if (status != SaleStatus.Draft || approved) revert InvalidStatus();
        liveWithdrawalsOff = !enabled;
        emit LiveWithdrawalsSet(enabled);
    }

    /// @dev Pay the outstanding fee to the fee receiver without reverting. A failed receiver lookup or
    ///      transfer leaves the fee reserved on the Sale. Returns the amount paid. State is
    ///      written after the transfer, whose outcome it depends on; every caller is nonReentrant.
    function _tryPayFee() private returns (uint256) {
        uint256 owed = platformFeeOutstanding();
        if (owed == 0) return 0;
        address receiver = _tryFeeReceiver();
        if (receiver != address(0) && paymentToken.trySafeTransfer(receiver, owed)) {
            _bookFeePaid(owed);
            emit PlatformFeeWithdrawn(receiver, owed);
            return owed;
        }
        emit PlatformFeeReserved(receiver, owed);
        return 0;
    }

    /// @dev The whole outstanding fee was paid: nothing assessed stays owed.
    function _bookFeePaid(uint256 amount) private {
        platformFeePaid += amount;
        platformFeeOwed = 0;
    }

    // ── Per-sale fee ─────────────────────────────────────────────────────────
    // The fee and cap are copied from the issuer's agreed terms at deploy (the factory checks
    // them). While Draft only, the operator may offer different terms; they apply when the issuer
    // accepts them, so neither side alone can change the fee. Activation locks it: no buyer has
    // bought before then. A new offer replaces the pending one. Terms not taken
    // from an accepted offer must still match the PlatformFeeManager at activate(); a stale fee is
    // fixed by an offer of the current agreed terms, which the issuer accepts.

    /// @notice Offer this sale a different fee (operator, Draft only, at most MAX_FEE_BPS).
    function offerFeeTerms(uint256 feeBps, uint256 feeCap) external onlyOperator onlyStatus(SaleStatus.Draft) {
        if (feeBps > MAX_FEE_BPS) revert InvalidFeeBps();
        offeredFeeBps = feeBps;
        offeredFeeCapUsdc = feeCap;
        feeOfferPending = true;
        emit FeeTermsOffered(feeBps, feeCap);
    }

    /// @notice Withdraw (operator) or decline (issuer) the pending offer; the fee stays as it is.
    function cancelFeeOffer() external {
        if (msg.sender != operator() && !_isActiveIssuer(msg.sender)) revert NotIssuerOrAdmin();
        if (!feeOfferPending) revert FeeOfferMismatch();
        _clearFeeOffer();
        emit FeeOfferCancelled(msg.sender);
    }

    /// @notice Accept the pending offer (issuer, Draft only). The terms are repeated so the issuer
    ///         accepts exactly what it was shown, never a replacement offer.
    function acceptFeeTerms(uint256 feeBps, uint256 feeCap) external onlyIssuer onlyStatus(SaleStatus.Draft) {
        if (!feeOfferPending || feeBps != offeredFeeBps || feeCap != offeredFeeCapUsdc) revert FeeOfferMismatch();
        emit FeeTermsChanged(feeBasisPoints, feeCapUsdc, feeBps, feeCap);
        feeBasisPoints = feeBps;
        feeCapUsdc = feeCap;
        feeTermsAccepted = true;
        _clearFeeOffer();
    }

    function _clearFeeOffer() private {
        delete offeredFeeBps;
        delete offeredFeeCapUsdc;
        feeOfferPending = false;
    }

    /// @notice Pay the outstanding platform fee (platformFeeOutstanding) to the PlatformFeeManager's
    ///         fee receiver. Anyone may call: on a live direct sale for the fee owed so far, including
    ///         a fee a withdrawal had to reserve; after a successful finalization for the
    ///         unpaid part of the assessed fee. Never while Paused. A blocked receiver blocks neither
    ///         finalization nor the issuer's withdrawals.
    function withdrawPlatformFee() external nonReentrant {
        uint256 owed = platformFeeOutstanding();
        if (owed == 0) revert NothingToWithdraw();
        if (status == SaleStatus.Paused) revert InvalidStatus();
        address receiver = _feeReceiver();
        _bookFeePaid(owed);
        paymentToken.safeTransfer(receiver, owed);
        emit PlatformFeeWithdrawn(receiver, owed);
    }

    // ── Pause / Finalization ────────────────────────────────────────────────

    /// @notice Pause the sale (compliance pause). Issuer, operator or guardian; only the operator
    ///         can unpause, and while Paused only the operator can finalize, close or forceFail —
    ///         except that a pause can never block refunds of a failing vested sale: once the
    ///         permissionless deadline passes, anyone can fail it (see _permissionlessFail).
    function pause() external onlyStatus(SaleStatus.Active) {
        if (!_isActiveIssuer(msg.sender) && msg.sender != operator() && msg.sender != guardian()) {
            revert NotIssuerOrAdmin();
        }
        status = SaleStatus.Paused;
        pausedAt = block.timestamp;
        emit SaleStatusChanged(SaleStatus.Paused);
    }

    /// @notice Finalize the sale (success iff totalRaised >= softCap; direct sales always succeed).
    ///         - Active: issuer/operator once finalizationPending or the fixed window has expired;
    ///           anyone once a fixed-end sale is FINALIZE_GRACE_PERIOD past its end.
    ///         - Paused: operator; or anyone, once a fixed-end vested sale below the soft
    ///           cap is FINALIZE_GRACE_PERIOD past its end — it then fails and refunds open, so
    ///           a pause (by the issuer or anyone else) cannot hold investor refunds hostage.
    ///           A paused sale that met its soft cap still needs the operator.
    ///         Open-ended sales use closeSale().
    function finalizeSale() external nonReentrant {
        bool windowExpired = !openEnded && block.timestamp >= saleEndTime;
        bool privileged = msg.sender == operator() || _isActiveIssuer(msg.sender);
        bool graceOver = !openEnded && block.timestamp >= saleEndTime + FINALIZE_GRACE_PERIOD;
        if (status == SaleStatus.Active) {
            if (privileged) {
                if (!finalizationPending && !windowExpired) revert CannotFinalize();
            } else if (!graceOver) {
                revert NotIssuerOrAdmin();
            }
        } else if (status == SaleStatus.Paused) {
            if (msg.sender != operator()) {
                if (!graceOver || !_failsWithoutOperator()) revert NotAdmin();
                _finalize(false);
                return;
            }
            if (!finalizationPending && !windowExpired) revert CannotFinalize();
        } else {
            revert CannotFinalize();
        }
        _finalize(totalRaised >= softCap);
    }

    /// @notice Close a sale with no live phase.
    ///         Who: issuer or operator (Active); operator (Paused); anyone after the
    ///         MAX_SALE_DURATION safety floor or INACTIVITY_TIMEOUT below soft cap (open-ended).
    ///         Inactivity runs from the end of the last scheduled phase, or from the pause
    ///         for a Paused sale. The permissionless paths also work on a Paused vested sale below
    ///         its soft cap, which then fails so refunds open; a phase that is still
    ///         scheduled does not block them, since a Paused sale takes no money.
    /// @param failed Force the failed branch. Honored for the operator, and for the issuer only
    ///        while the vested sale is below its soft cap.
    function closeSale(bool failed) external nonReentrant {
        bool pausedNonOperator;
        if (status == SaleStatus.Paused) {
            pausedNonOperator = msg.sender != operator();
        } else if (status != SaleStatus.Active) {
            revert InvalidStatus();
        }
        if (phases.length == 0) revert InvalidStatus();
        bool safetyFloor = openEnded && block.timestamp >= saleStartTime + MAX_SALE_DURATION;
        bool inactive = openEnded && block.timestamp >= _lastActivity() + INACTIVITY_TIMEOUT;

        if (pausedNonOperator) {
            if (!(safetyFloor || inactive) || !_failsWithoutOperator()) revert NotAdmin();
            _finalize(false);
            emit SaleClosed(true, msg.sender);
            return;
        }
        if (_activePhaseId() != type(uint256).max) revert PhaseStillActive();

        bool isOperator = msg.sender == operator();
        bool isOwner = isOperator || _isActiveIssuer(msg.sender);
        bool inactivityTimeout = inactive && totalRaised < softCap;
        if (!isOwner && !safetyFloor && !inactivityTimeout) revert NotIssuerOrAdmin();

        bool success;
        if (inactivityTimeout) {
            success = false;
        } else if (failed && isOwner) {
            if (!isOperator && saleMode == SaleMode.Vested && totalRaised >= softCap) revert SoftCapReached();
            success = false;
        } else {
            success = totalRaised >= softCap;
        }

        _finalize(success);
        emit SaleClosed(status == SaleStatus.FinalizedFailed, msg.sender);
    }

    /// @notice Governance (timelock) recovers remaining raised funds — excluding the unpaid
    ///         platform fee — EMERGENCY_WITHDRAW_DELAY (90 days) after a successful
    ///         finalization, e.g. when the issuer has lost its keys.
    function emergencyWithdraw(address recipient) external nonReentrant {
        if (msg.sender != governance()) revert NotAdmin();
        if (status != SaleStatus.FinalizedSuccess) revert SaleNotFinalized();
        if (block.timestamp < finalizedAt + EMERGENCY_WITHDRAW_DELAY) revert DelayNotElapsed();
        if (recipient == address(0)) revert ZeroAddress();
        uint256 balance = paymentToken.balanceOf(address(this));
        uint256 owed = platformFeeOwed;
        if (balance <= owed) revert NothingToWithdraw();
        uint256 amount = balance - owed;
        paymentToken.safeTransfer(recipient, amount);
        emit EmergencyWithdraw(recipient, amount);
    }

    // ── Buy ─────────────────────────────────────────────────────────────────

    /// @notice Buy whole tokens with the payment token. Cost = tokenQty * pricePerToken.
    /// @dev The issuer can change the live phase's price in place (setPrice), so the buyer
    ///      bounds what it is willing to pay: the buy reverts if the price moved up.
    /// @param phaseId Index of the live phase.
    /// @param tokenQty Number of whole tokens to buy.
    /// @param maxCost Maximum payment-token amount the buyer accepts to pay (normally
    ///        tokenQty * the price the buyer was shown).
    function buy(uint256 phaseId, uint256 tokenQty, uint256 maxCost)
        external
        nonReentrant
        onlyStatus(SaleStatus.Active)
    {
        if (tokenQty == 0) revert AmountTooSmall();
        if (phaseId >= phases.length) revert InvalidPhase();
        Phase storage phase = phases[phaseId];
        uint256 cost = tokenQty * phase.pricePerToken;
        if (cost > maxCost) revert SlippageExceeded(cost, maxCost);
        uint256 tokensRaw = tokenQty * (10 ** tokenDecimals);

        _checkBuyEligibility(phase, phaseId, tokenQty, cost);
        _checkMinTokens(phase, tokenQty);
        _consumeAllocation(phase, tokensRaw);

        phase.sold += tokensRaw;
        totalRaised += cost;
        totalTokenSold += tokensRaw;
        totalContributed[msg.sender] += cost;
        paymentContributed[msg.sender] += cost;
        paymentContributedTotal += cost;
        contributions[msg.sender].amount += cost;
        contributions[msg.sender].tokensAllocated += tokensRaw;

        paymentToken.safeTransferFrom(msg.sender, address(this), cost);
        _deliver(FRACTION_ID_USDC, tokensRaw, cost);
        _checkFinalizationPending();
        emit Purchase(msg.sender, phaseId, cost, tokensRaw, false);
    }

    /// @notice Buy whole tokens with OTC vouchers (burned). Skips the per-buy minimums
    ///         (pre-negotiated allocations); every other check applies. See the OTC note
    ///         in the contract header: OTC counts toward the soft cap.
    /// @param tokenQty Number of whole tokens to buy.
    /// @param maxOtc Maximum OTC-voucher amount the buyer accepts to burn.
    function buyOTC(uint256 phaseId, uint256 tokenQty, uint256 maxOtc)
        external
        nonReentrant
        onlyStatus(SaleStatus.Active)
    {
        if (address(otcToken) == address(0)) revert OTCNotEnabled();
        if (tokenQty == 0) revert AmountTooSmall();
        if (phaseId >= phases.length) revert InvalidPhase();
        Phase storage phase = phases[phaseId];
        uint256 otcRequired = tokenQty * phase.pricePerToken;
        if (otcRequired > maxOtc) revert SlippageExceeded(otcRequired, maxOtc);
        uint256 tokensRaw = tokenQty * (10 ** tokenDecimals);

        _checkBuyEligibility(phase, phaseId, tokenQty, otcRequired);
        if (IERC20(address(otcToken)).balanceOf(msg.sender) < otcRequired) revert InsufficientOTCBalance();
        if (IERC20(address(otcToken)).allowance(msg.sender, address(this)) < otcRequired) revert OTCNotApproved();
        _consumeAllocation(phase, tokensRaw);

        phase.sold += tokensRaw;
        totalRaised += otcRequired;
        totalTokenSold += tokensRaw;
        totalContributed[msg.sender] += otcRequired;
        otcContributed[msg.sender] += otcRequired;
        contributions[msg.sender].amount += otcRequired;
        contributions[msg.sender].tokensAllocated += tokensRaw;

        IERC20(address(otcToken)).safeTransferFrom(msg.sender, address(this), otcRequired);
        otcToken.burn(address(this), otcRequired);
        _deliver(FRACTION_ID_OTC, tokensRaw, 0);
        _checkFinalizationPending();
        emit Purchase(msg.sender, phaseId, otcRequired, tokensRaw, true);
    }

    // ── Claims & Refunds ─────────────────────────────────────────────────────

    /// @notice Refund for a failed vested sale. Pays the refund basis attached to the caller's
    ///         ID-1 fractions (it moves with transfers), burning those fractions, plus any
    ///         refundCredit a third party already settled for the caller. OTC (ID-2)
    ///         holders are refunded off-chain. Refunds open automatically on failure.
    function claimRefund() external nonReentrant {
        bool settled = _settleRefund(msg.sender);
        uint256 amount = refundCredit[msg.sender];
        if (amount == 0) {
            // ID-1 dust whose pro-rata refund basis rounded to zero: burned and cleared all the same.
            if (settled) {
                emit RefundClaimed(msg.sender, 0);
                return;
            }
            if (contributions[msg.sender].refunded) revert AlreadyClaimed();
            revert NotPaymentContributor();
        }
        _payRefund(msg.sender, msg.sender, amount);
    }

    /// @notice Settle the failed-sale ID-1 position of `holder` on its behalf:
    ///         permissionless escrow-ledger hygiene. Burns the holder's ID-1 fractions and clears
    ///         its compliance escrow position (which otherwise keeps a holder slot and balance
    ///         headroom although the backing went back to the issuer), and books the refund as
    ///         refundCredit[holder]. It pays NOTHING: the credit is paid out only by the holder
    ///         (claimRefund) or, for a lost key, by the operator to a replacement wallet
    ///         (recoverRefund), so a third party can never push a refund to a wallet the operator
    ///         still needs to recover.
    /// @param holder ID-1 fraction holder (or refund-basis owner) to settle.
    function claimRefundFor(address holder) external nonReentrant {
        if (holder == address(0)) revert ZeroAddress();
        uint256 before = refundCredit[holder];
        if (!_settleRefund(holder)) {
            if (contributions[holder].refunded) revert AlreadyClaimed();
            revert NotPaymentContributor();
        }
        emit RefundCredited(holder, refundCredit[holder] - before, msg.sender);
    }

    /**
     * @notice Lost-key path for a failed sale's refund: settle `from`'s ID-1 position, if
     *         still open, and pay its whole refund (basis + refundCredit) to `to`. Platform operator
     *         (resolved live from the factory, so the guardian kill switch removes it). Same power as
     *         CiretaFractionToken1155.recoverFractions of ID-1, which moves the refund basis to a
     *         verified wallet; the recipient must likewise be verified and not frozen.
     * @param from Holder whose refund is recovered (e.g. a lost wallet).
     * @param to   Replacement wallet (verified on this sale's identity registry, not frozen, not a
     *             registered system contract: a refund paid there could not be claimed back).
     */
    function recoverRefund(address from, address to) external nonReentrant onlyOperator {
        if (from == address(0) || to == address(0)) revert ZeroAddress();
        if (
            !identityRegistry.isVerified(to) || identityRegistry.isSystemContract(to)
                || ISaleTokenSuspension(token).isFrozen(to)
        ) {
            revert InvalidRefundRecipient(to);
        }
        _settleRefund(from);
        uint256 amount = refundCredit[from];
        if (amount == 0) revert NotPaymentContributor();
        emit RefundRecovered(from, to, amount, msg.sender);
        _payRefund(from, to, amount);
    }

    /// @dev Burn `holder`'s ID-1 fractions, clear its escrow position and move its refund basis
    ///      into refundCredit. Returns false when there was nothing to settle.
    function _settleRefund(address holder) internal returns (bool settled) {
        if (status != SaleStatus.FinalizedFailed) revert InvalidStatus();
        if (saleMode == SaleMode.Direct) revert RefundsNotApplicable();
        if (!refundsActive) revert RefundsNotActive();

        uint256 held = fractionToken.balanceOf(holder, FRACTION_ID_USDC);
        uint256 refund = vault.settleRefund(holder);
        if (refund > 0) {
            contributions[holder].refunded = true;
            paymentContributed[holder] = 0;
            refundCredit[holder] += refund;
            totalRefundCredit += refund;
        }
        return held > 0 || refund > 0;
    }

    /// @dev Pay `holder`'s whole refundCredit (`amount`) to `to`.
    function _payRefund(address holder, address to, uint256 amount) internal {
        refundCredit[holder] = 0;
        totalRefundCredit -= amount;
        totalRefunded += amount;
        paymentToken.safeTransfer(to, amount);
        emit RefundClaimed(holder, amount);
    }

    // ── View ─────────────────────────────────────────────────────────────────

    function getPhaseCount() external view returns (uint256) { return phases.length; }
    function getPhase(uint256 phaseId) external view returns (Phase memory) { return phases[phaseId]; }
    function getContribution(address contributor) external view returns (Contribution memory) { return contributions[contributor]; }
    function getTotalRaised() external view returns (uint256) { return totalRaised; }

    /// @notice Index of the live phase (start <= now < end), or type(uint256).max.
    function getCurrentPhase() external view returns (uint256) {
        return _activePhaseId();
    }

    /// @notice Sale-local fee estimate from this sale's snapshotted bps and cap. The fee actually
    ///         assessed at finalization uses paymentContributedTotal (OTC excluded).
    function calculateFee(uint256 onPlatformRaised) external view returns (uint256) {
        return _fee(onPlatformRaised);
    }

    // ── Internal ─────────────────────────────────────────────────────────────

    /// @dev Platform fee on `base`: bps, capped by feeCapUsdc when it is set.
    function _fee(uint256 base) internal view returns (uint256 fee) {
        fee = (base * feeBasisPoints) / 10000;
        if (feeCapUsdc > 0 && fee > feeCapUsdc) fee = feeCapUsdc;
    }

    function _checkWithinSaleWindow(uint256 endTime) internal view {
        if (openEnded) {
            if (endTime > saleStartTime + MAX_SALE_DURATION) revert SaleWindowTooLong();
        } else if (endTime > saleEndTime) {
            revert PhaseOutsideSaleWindow();
        }
    }

    /// @dev Last moment the sale could take money: the latest of lastPhaseAddedAt and every phase
    ///      end (a scheduled phase is activity); a Paused sale stopped at its pause.
    function _lastActivity() internal view returns (uint256 last) {
        last = lastPhaseAddedAt;
        for (uint256 i = 0; i < phases.length; i++) {
            if (phases[i].endTime > last) last = phases[i].endTime;
        }
        if (status == SaleStatus.Paused && pausedAt < last) last = pausedAt;
    }

    function _activePhaseId() internal view returns (uint256) {
        for (uint256 i = 0; i < phases.length; i++) {
            if (block.timestamp >= phases[i].startTime && block.timestamp < phases[i].endTime) return i;
        }
        return type(uint256).max;
    }

    /// @dev Sum of all Fixed-mode phase allocations.
    function _totalFixedAllocations() internal view returns (uint256 sum) {
        for (uint256 i = 0; i < phases.length; i++) {
            if (phases[i].allocationMode == AllocationMode.Fixed) sum += phases[i].allocation;
        }
    }

    /// @dev Sum of unsold allocation of Fixed phases that have ended.
    function _unsoldFromPriorPhases() internal view returns (uint256 unsold) {
        for (uint256 i = 0; i < phases.length; i++) {
            Phase storage p = phases[i];
            if (p.allocationMode == AllocationMode.Fixed && block.timestamp >= p.endTime && p.allocation > p.sold) {
                unsold += p.allocation - p.sold;
            }
        }
    }

    /// @dev Per-buy minimum in whole tokens: first-time buyers need minTokens, repeat buyers
    ///      topUpMinTokens. Last-chunk exception: a smaller buy is allowed when it takes exactly
    ///      everything still sellable — min(remaining supply, what fits under the hard cap).
    ///      The hard cap itself is always enforced.
    function _checkMinTokens(Phase storage phase, uint256 tokenQty) internal view {
        uint256 unit = 10 ** tokenDecimals;
        uint256 investorWholeTokens = contributions[msg.sender].tokensAllocated / unit;
        uint256 effectiveMin = investorWholeTokens == 0 ? phase.minTokens : phase.topUpMinTokens;
        if (tokenQty >= effectiveMin) return;

        uint256 remainingWhole = (totalTokenSupply - totalTokenSold) / unit;
        uint256 maxAffordable = hardCap > totalRaised ? (hardCap - totalRaised) / phase.pricePerToken : 0;
        uint256 lastChunk = remainingWhole < maxAffordable ? remainingWhole : maxAffordable;
        if (lastChunk > 0 && tokenQty == lastChunk) return;

        if (investorWholeTokens == 0) revert BelowMinContribution();
        revert TopUpBelowMin();
    }

    /// @dev Phase window (half-open), per-investor cap, hard cap, KYC and whitelist.
    function _checkBuyEligibility(Phase storage phase, uint256 phaseId, uint256 tokenQty, uint256 cost) internal view {
        if (block.timestamp < phase.startTime) revert PhaseNotStarted();
        if (block.timestamp >= phase.endTime) revert PhaseEnded();
        if (phase.maxTokens > 0) {
            uint256 investorWholeTokens = contributions[msg.sender].tokensAllocated / (10 ** tokenDecimals);
            if (investorWholeTokens + tokenQty > phase.maxTokens) revert ExceedsMaxContribution();
        }
        if (totalRaised + cost > hardCap) revert ExceedsHardCap();
        if (!identityRegistry.isVerified(msg.sender)) revert KYCRequired();
        if (phase.whitelistOnly && !whitelisted[phaseId][msg.sender]) revert NotWhitelisted();
    }

    /// @dev Fixed phases may sell their allocation plus the unsold allocation of ended Fixed
    ///      phases that no other phase has consumed yet; consumption is recorded.
    ///      Every phase is bounded by totalTokenSupply.
    function _consumeAllocation(Phase storage phase, uint256 tokensRaw) internal {
        if (phase.allocationMode == AllocationMode.Fixed) {
            uint256 unsoldPrior = _unsoldFromPriorPhases();
            uint256 available = unsoldPrior > rolloverConsumed ? unsoldPrior - rolloverConsumed : 0;
            uint256 newSold = phase.sold + tokensRaw;
            if (newSold > phase.allocation + available) revert ExceedsAllocation();
            if (newSold > phase.allocation) {
                uint256 overBefore = phase.sold > phase.allocation ? phase.sold - phase.allocation : 0;
                rolloverConsumed += (newSold - phase.allocation) - overBefore;
            }
        }
        if (totalTokenSold + tokensRaw > totalTokenSupply) revert TokenSupplyExceeded();
    }

    /// @dev Direct: transfer tokens now. Vested: record the (collateral-checked) allocation in
    ///      the vault, then mint the fraction.
    function _deliver(uint256 fractionId, uint256 tokensRaw, uint256 paid) internal {
        if (saleMode == SaleMode.Direct) {
            IERC20(token).safeTransfer(msg.sender, tokensRaw);
            contributions[msg.sender].claimed = true;
        } else {
            vault.recordAllocation(msg.sender, fractionId, tokensRaw, paid);
            fractionToken.mint(msg.sender, fractionId, tokensRaw, "");
        }
    }

    /// @dev A Paused sale may be ended by a non-operator only when that ends it as failed: a
    ///      vested sale below its soft cap (refund liveness). Anything that would release
    ///      funds to the issuer stays behind the operator's compliance pause.
    function _failsWithoutOperator() internal view returns (bool) {
        return saleMode == SaleMode.Vested && totalRaised < softCap;
    }

    function _checkFinalizationPending() internal {
        if (!finalizationPending && (totalRaised >= hardCap || totalTokenSold >= totalTokenSupply)) {
            finalizationPending = true;
            emit FinalizationPending(totalRaised, totalTokenSold);
        }
    }

    /// @dev Success: assess (not push) the platform fee and, for vested sales, start vesting;
    ///      the vault re-checks full collateralization. Fee a live direct sale already paid is part
    ///      of the total and never charged twice. Failure (vested only, direct sales always
    ///      succeed): open refunds.
    function _finalize(bool success) internal {
        finalizationPending = false;
        if (saleMode == SaleMode.Direct) success = true;
        finalizedAt = block.timestamp;
        if (success) {
            status = SaleStatus.FinalizedSuccess;
            uint256 fee = _fee(paymentContributedTotal);
            platformFeeCollected = fee;
            platformFeeOwed = fee - platformFeePaid;
            if (saleMode == SaleMode.Vested) vault.startVesting();
            emit SaleFinalized(true, totalRaised, fee);
        } else {
            status = SaleStatus.FinalizedFailed;
            refundsActive = true;
            emit RefundsActivated();
            emit SaleFinalized(false, totalRaised, 0);
        }
        emit SaleStatusChanged(status);
    }

    /// @dev PFM fee receiver; reverts InvalidFeeReceiver when there is no usable one.
    function _feeReceiver() internal view returns (address receiver) {
        receiver = _tryFeeReceiver();
        if (receiver == address(0)) revert InvalidFeeReceiver();
    }

    /// @dev PFM fee receiver via a validated staticcall (malformed return data cannot brick
    ///      the call path); zero when the lookup fails or returns no valid address.
    function _tryFeeReceiver() internal view returns (address) {
        return _staticAddress(feeManager, IFeeReceiverLookup.feeReceiver.selector);
    }

    /// @dev An address from a validated no-argument staticcall; zero when the call fails or the
    ///      word is not an address.
    function _staticAddress(address target, bytes4 selector) private view returns (address) {
        (bool ok, uint256 raw) = _staticWord(target, selector, address(0), 4);
        return !ok || raw > type(uint160).max ? address(0) : address(uint160(raw));
    }

    /// @dev Staticcall of `selector` (len 4) or `selector(arg)` (len 0x24) returning exactly one
    ///      word, as CiretaToken._readWord (shared by every tolerant lookup to save bytecode; the
    ///      calldata is built in scratch space). ok is false on a revert, on code-less `target` and
    ///      on any other return size (malformed return data cannot brick the call path); at
    ///      most 32 bytes are ever copied (no return bomb). `word` is meaningful only when ok.
    function _staticWord(address target, bytes4 selector, address arg, uint256 len)
        private
        view
        returns (bool ok, uint256 word)
    {
        assembly ("memory-safe") {
            // Scratch space 0x00-0x3f: selector at 0x00, the argument word at 0x04-0x23.
            mstore(0x00, selector)
            mstore(0x04, arg)
            // Two statements: Yul evaluates arguments right to left, so returndatasize() must be
            // read after the call returns.
            ok := staticcall(gas(), target, 0x00, len, 0x00, 0x20)
            ok := and(ok, eq(returndatasize(), 0x20))
            word := mload(0x00)
        }
    }
}

@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol

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

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;


    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
    struct AccessControlStorage {
        mapping(bytes32 role => RoleData) _roles;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;

    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
        assembly {
            $.slot := AccessControlStorageLocation
        }
    }

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

    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc ERC165Upgradeable
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

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

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

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

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

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

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

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

        _revokeRole(role, callerConfirmation);
    }

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

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

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

@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol

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

pragma solidity ^0.8.20;

import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
    struct Ownable2StepStorage {
        address _pendingOwner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;

    function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
        assembly {
            $.slot := Ownable2StepStorageLocation
        }
    }

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

    function __Ownable2Step_init() internal onlyInitializing {
    }

    function __Ownable2Step_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        return $._pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        $._pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        delete $._pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

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

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

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

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

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

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

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

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

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

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.22;

import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";

@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (token/ERC1155/ERC1155.sol)

pragma solidity ^0.8.24;

import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC1155MetadataURI} from "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol";
import {ERC1155Utils} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Utils.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../../utils/introspection/ERC165Upgradeable.sol";
import {Arrays} from "@openzeppelin/contracts/utils/Arrays.sol";
import {IERC1155Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the basic standard multi-token.
 * See https://eips.ethereum.org/EIPS/eip-1155
 * Originally based on code by Enjin: https://github.com/enjin/erc-1155
 */
abstract contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155, IERC1155MetadataURI, IERC1155Errors {
    using Arrays for uint256[];
    using Arrays for address[];

    /// @custom:storage-location erc7201:openzeppelin.storage.ERC1155
    struct ERC1155Storage {
        mapping(uint256 id => mapping(address account => uint256)) _balances;

        mapping(address account => mapping(address operator => bool)) _operatorApprovals;

        // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
        string _uri;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC1155")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC1155StorageLocation = 0x88be536d5240c274a3b1d3a1be54482fd9caa294f08c62a7cde569f49a3c4500;

    function _getERC1155Storage() private pure returns (ERC1155Storage storage $) {
        assembly {
            $.slot := ERC1155StorageLocation
        }
    }

    /**
     * @dev See {_setURI}.
     */
    function __ERC1155_init(string memory uri_) internal onlyInitializing {
        __ERC1155_init_unchained(uri_);
    }

    function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing {
        _setURI(uri_);
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165) returns (bool) {
        return
            interfaceId == type(IERC1155).interfaceId ||
            interfaceId == type(IERC1155MetadataURI).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC1155MetadataURI-uri}.
     *
     * This implementation returns the same URI for *all* token types. It relies
     * on the token type ID substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
     *
     * Clients calling this function must replace the `\{id\}` substring with the
     * actual token type ID.
     */
    function uri(uint256 /* id */) public view virtual returns (string memory) {
        ERC1155Storage storage $ = _getERC1155Storage();
        return $._uri;
    }

    /// @inheritdoc IERC1155
    function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
        ERC1155Storage storage $ = _getERC1155Storage();
        return $._balances[id][account];
    }

    /**
     * @dev See {IERC1155-balanceOfBatch}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] memory accounts,
        uint256[] memory ids
    ) public view virtual returns (uint256[] memory) {
        if (accounts.length != ids.length) {
            revert ERC1155InvalidArrayLength(ids.length, accounts.length);
        }

        uint256[] memory batchBalances = new uint256[](accounts.length);

        for (uint256 i = 0; i < accounts.length; ++i) {
            batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
        }

        return batchBalances;
    }

    /// @inheritdoc IERC1155
    function setApprovalForAll(address operator, bool approved) public virtual {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /// @inheritdoc IERC1155
    function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
        ERC1155Storage storage $ = _getERC1155Storage();
        return $._operatorApprovals[account][operator];
    }

    /// @inheritdoc IERC1155
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
        _checkAuthorized(_msgSender(), from);
        _safeTransferFrom(from, to, id, value, data);
    }

    /// @inheritdoc IERC1155
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) public virtual {
        _checkAuthorized(_msgSender(), from);
        _safeBatchTransferFrom(from, to, ids, values, data);
    }

    /// @dev Checks if `operator` is authorized to transfer tokens owned by `owner`. Reverts with {ERC1155MissingApprovalForAll} if not.
    function _checkAuthorized(address operator, address owner) internal view virtual {
        if (owner != operator && !isApprovedForAll(owner, operator)) {
            revert ERC1155MissingApprovalForAll(operator, owner);
        }
    }

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
     * (or `to`) is the zero address.
     *
     * Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
     *   or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
     * - `ids` and `values` must have the same length.
     *
     * NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
     */
    function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
        ERC1155Storage storage $ = _getERC1155Storage();
        if (ids.length != values.length) {
            revert ERC1155InvalidArrayLength(ids.length, values.length);
        }

        address operator = _msgSender();

        for (uint256 i = 0; i < ids.length; ++i) {
            uint256 id = ids.unsafeMemoryAccess(i);
            uint256 value = values.unsafeMemoryAccess(i);

            if (from != address(0)) {
                uint256 fromBalance = $._balances[id][from];
                if (fromBalance < value) {
                    revert ERC1155InsufficientBalance(from, fromBalance, value, id);
                }
                unchecked {
                    // Overflow not possible: value <= fromBalance
                    $._balances[id][from] = fromBalance - value;
                }
            }

            if (to != address(0)) {
                $._balances[id][to] += value;
            }
        }

        if (ids.length == 1) {
            uint256 id = ids.unsafeMemoryAccess(0);
            uint256 value = values.unsafeMemoryAccess(0);
            emit TransferSingle(operator, from, to, id, value);
        } else {
            emit TransferBatch(operator, from, to, ids, values);
        }
    }

    /**
     * @dev Version of {_update} that performs the token acceptance check by calling
     * {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
     * contains code (eg. is a smart contract at the moment of execution).
     *
     * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
     * update to the contract state after this function would break the check-effect-interaction pattern. Consider
     * overriding {_update} instead.
     *
     * NOTE: This version is kept for backward compatibility. We recommend calling the alternative version with a boolean
     * flag in order to achieve better control over which hook to call.
     */
    function _updateWithAcceptanceCheck(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal virtual {
        _updateWithAcceptanceCheck(from, to, ids, values, data, ids.length != 1);
    }

    /**
     * @dev Version of {_update} that performs the token acceptance check by calling
     * {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
     * contains code (eg. is a smart contract at the moment of execution).
     *
     * IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
     * update to the contract state after this function would break the check-effect-interaction pattern. Consider
     * overriding {_update} instead.
     */
    function _updateWithAcceptanceCheck(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data,
        bool batch
    ) internal virtual {
        _update(from, to, ids, values);
        if (to != address(0)) {
            address operator = _msgSender();
            if (batch) {
                ERC1155Utils.checkOnERC1155BatchReceived(operator, from, to, ids, values, data);
            } else {
                uint256 id = ids.unsafeMemoryAccess(0);
                uint256 value = values.unsafeMemoryAccess(0);
                ERC1155Utils.checkOnERC1155Received(operator, from, to, id, value, data);
            }
        }
    }

    /**
     * @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(from, to, ids, values, data, false);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     * - `ids` and `values` must have the same length.
     */
    function _safeBatchTransferFrom(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        _updateWithAcceptanceCheck(from, to, ids, values, data, true);
    }

    /**
     * @dev Sets a new URI for all token types, by relying on the token type ID
     * substitution mechanism
     * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
     *
     * By this mechanism, any occurrence of the `\{id\}` substring in either the
     * URI or any of the values in the JSON file at said URI will be replaced by
     * clients with the token type ID.
     *
     * For example, the `https://token-cdn-domain/\{id\}.json` URI would be
     * interpreted by clients as
     * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
     * for token type ID 0x4cce0.
     *
     * See {uri}.
     *
     * Because these URIs cannot be meaningfully represented by the {URI} event,
     * this function emits no events.
     */
    function _setURI(string memory newuri) internal virtual {
        ERC1155Storage storage $ = _getERC1155Storage();
        $._uri = newuri;
    }

    /**
     * @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(address(0), to, ids, values, data, false);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - `to` cannot be the zero address.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
        if (to == address(0)) {
            revert ERC1155InvalidReceiver(address(0));
        }
        _updateWithAcceptanceCheck(address(0), to, ids, values, data, true);
    }

    /**
     * @dev Destroys a `value` amount of tokens of type `id` from `from`
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `value` amount of tokens of type `id`.
     */
    function _burn(address from, uint256 id, uint256 value) internal {
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        (uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
        _updateWithAcceptanceCheck(from, address(0), ids, values, "", false);
    }

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `from` must have at least `value` amount of tokens of type `id`.
     * - `ids` and `values` must have the same length.
     */
    function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
        if (from == address(0)) {
            revert ERC1155InvalidSender(address(0));
        }
        _updateWithAcceptanceCheck(from, address(0), ids, values, "", true);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `operator` cannot be the zero address.
     */
    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
        ERC1155Storage storage $ = _getERC1155Storage();
        if (owner == address(0)) {
            revert ERC1155InvalidApprover(address(0));
        }
        if (operator == address(0)) {
            revert ERC1155InvalidOperator(address(0));
        }
        $._operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Creates an array in memory with only one value for each of the elements provided.
     */
    function _asSingletonArrays(
        uint256 element1,
        uint256 element2
    ) private pure returns (uint256[] memory array1, uint256[] memory array2) {
        assembly ("memory-safe") {
            // Load the free memory pointer
            array1 := mload(0x40)
            // Set array length to 1
            mstore(array1, 1)
            // Store the single element at the next word after the length (where content starts)
            mstore(add(array1, 0x20), element1)

            // Repeat for next array locating it right after the first array
            array2 := add(array1, 0x40)
            mstore(array2, 1)
            mstore(add(array2, 0x20), element2)

            // Update the free memory pointer by pointing after the second array
            mstore(0x40, add(array2, 0x40))
        }
    }
}

@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

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

        uint256 _totalSupply;

        string _name;
        string _symbol;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;

    function _getERC20Storage() private pure returns (ERC20Storage storage $) {
        assembly {
            $.slot := ERC20StorageLocation
        }
    }

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        ERC20Storage storage $ = _getERC20Storage();
        $._name = name_;
        $._symbol = symbol_;
    }

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

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

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

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._balances[account];
    }

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

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        ERC20Storage storage $ = _getERC20Storage();
        return $._allowances[owner][spender];
    }

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

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

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

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

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

        emit Transfer(from, to, value);
    }

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

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

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

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

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

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

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

@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol

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

pragma solidity ^0.8.20;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/access/IAccessControl.sol

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

pragma solidity >=0.8.4;

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/interfaces/IERC1967.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)

pragma solidity >=0.4.11;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

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

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

@openzeppelin/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/interfaces/draft-IERC1822.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/interfaces/draft-IERC6093.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)

pragma solidity >=0.8.4;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

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

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

@openzeppelin/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

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

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

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * @custom:stateless
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

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

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

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

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

@openzeppelin/contracts/token/ERC1155/IERC1155.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Required interface of an ERC-1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[ERC].
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

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

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the zero address.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {IERC1155Receiver-onERC1155Received} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `value` amount.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * WARNING: This function can potentially allow a reentrancy attack when transferring tokens
     * to an untrusted contract, when invoking {IERC1155Receiver-onERC1155BatchReceived} on the receiver.
     * Ensure to follow the checks-effects-interactions pattern and consider employing
     * reentrancy guards when interacting with untrusted contracts.
     *
     * Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
     *
     * Requirements:
     *
     * - `ids` and `values` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external;
}

@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface of the optional ERC1155MetadataExtension interface, as defined
 * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
 */
interface IERC1155MetadataURI is IERC1155 {
    /**
     * @dev Returns the URI for token type `id`.
     *
     * If the `\{id\}` substring is present in the URI, it must be replaced by
     * clients with the actual token type ID.
     */
    function uri(uint256 id) external view returns (string memory);
}

@openzeppelin/contracts/token/ERC1155/utils/ERC1155Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/utils/ERC1155Utils.sol)

pragma solidity ^0.8.20;

import {IERC1155Receiver} from "../IERC1155Receiver.sol";
import {IERC1155Errors} from "../../../interfaces/draft-IERC6093.sol";

/**
 * @dev Library that provide common ERC-1155 utility functions.
 *
 * See https://eips.ethereum.org/EIPS/eip-1155[ERC-1155].
 *
 * _Available since v5.1._
 */
library ERC1155Utils {
    /**
     * @dev Performs an acceptance check for the provided `operator` by calling {IERC1155Receiver-onERC1155Received}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC1155Received(
        address operator,
        address from,
        address to,
        uint256 id,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
                if (response != IERC1155Receiver.onERC1155Received.selector) {
                    // Tokens rejected
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC1155Receiver implementer
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(reason, 0x20), mload(reason))
                    }
                }
            }
        }
    }

    /**
     * @dev Performs a batch acceptance check for the provided `operator` by calling {IERC1155Receiver-onERC1155BatchReceived}
     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
     *
     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
     * Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
     * the transfer.
     */
    function checkOnERC1155BatchReceived(
        address operator,
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values,
        bytes memory data
    ) internal {
        if (to.code.length > 0) {
            try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
                bytes4 response
            ) {
                if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
                    // Tokens rejected
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                }
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    // non-IERC1155Receiver implementer
                    revert IERC1155Errors.ERC1155InvalidReceiver(to);
                } else {
                    assembly ("memory-safe") {
                        revert(add(reason, 0x20), mload(reason))
                    }
                }
            }
        }
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

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

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

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

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

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

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

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

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

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

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

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

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

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.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);
        }
        if (LowLevelCall.callNoReturn(recipient, amount, "")) {
            // call successful, nothing to do
            return;
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bool success = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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.
     *
     * NOTE: This function is DEPRECATED and may be removed in the next major release.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        // 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 (success && (returndata.length > 0 || target.code.length > 0)) {
            return returndata;
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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) {
            return returndata;
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }
}

@openzeppelin/contracts/utils/Arrays.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.

pragma solidity ^0.8.24;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new address array in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(address[] memory array, uint256 start) internal pure returns (address[] memory) {
        return slice(array, start, array.length);
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new address array in
     * memory. The `end` argument is truncated to the length of the `array`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // allocate and copy
        address[] memory result = new address[](end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
        }

        return result;
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new bytes32 array in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {
        return slice(array, start, array.length);
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new bytes32 array in
     * memory. The `end` argument is truncated to the length of the `array`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // allocate and copy
        bytes32[] memory result = new bytes32[](end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
        }

        return result;
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new uint256 array in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {
        return slice(array, start, array.length);
    }

    /**
     * @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new uint256 array in
     * memory. The `end` argument is truncated to the length of the `array`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // allocate and copy
        uint256[] memory result = new uint256[](end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
        }

        return result;
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:].
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(address[] memory array, uint256 start) internal pure returns (address[] memory) {
        return splice(array, start, array.length);
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:end]. The
     * `end` argument is truncated to the length of the `array`.
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
            mstore(array, sub(end, start))
        }

        return array;
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
     *
     * Parameters are clamped to valid ranges (e.g. `pos` is clamped to `[0, array.length]`).
     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        address[] memory array,
        uint256 pos,
        address[] memory replacement
    ) internal pure returns (address[] memory) {
        return replace(array, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
     * Copies at most `length` elements from `replacement` to `array`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
     * and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        address[] memory array,
        uint256 pos,
        address[] memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (address[] memory) {
        // sanitize
        pos = Math.min(pos, array.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(
                add(add(array, 0x20), mul(pos, 0x20)),
                add(add(replacement, 0x20), mul(offset, 0x20)),
                mul(length, 0x20)
            )
        }

        return array;
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:].
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {
        return splice(array, start, array.length);
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:end]. The
     * `end` argument is truncated to the length of the `array`.
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
            mstore(array, sub(end, start))
        }

        return array;
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
     *
     * Parameters are clamped to valid ranges (e.g. `pos` is clamped to `[0, array.length]`).
     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        bytes32[] memory array,
        uint256 pos,
        bytes32[] memory replacement
    ) internal pure returns (bytes32[] memory) {
        return replace(array, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
     * Copies at most `length` elements from `replacement` to `array`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
     * and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        bytes32[] memory array,
        uint256 pos,
        bytes32[] memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (bytes32[] memory) {
        // sanitize
        pos = Math.min(pos, array.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(
                add(add(array, 0x20), mul(pos, 0x20)),
                add(add(replacement, 0x20), mul(offset, 0x20)),
                mul(length, 0x20)
            )
        }

        return array;
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:].
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {
        return splice(array, start, array.length);
    }

    /**
     * @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array,
     * and shrinks the array length accordingly, effectively overwriting the array with array[start:end]. The
     * `end` argument is truncated to the length of the `array`.
     *
     * NOTE: This function modifies the provided array in place. If you need to preserve the original array, use {slice} instead.
     */
    function splice(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {
        // sanitize
        end = Math.min(end, array.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
            mstore(array, sub(end, start))
        }

        return array;
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
     *
     * Parameters are clamped to valid ranges (e.g. `pos` is clamped to `[0, array.length]`).
     * If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        uint256[] memory array,
        uint256 pos,
        uint256[] memory replacement
    ) internal pure returns (uint256[] memory) {
        return replace(array, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
     * Copies at most `length` elements from `replacement` to `array`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
     * and the array is returned unchanged.
     *
     * NOTE: This function modifies the provided array in place.
     */
    function replace(
        uint256[] memory array,
        uint256 pos,
        uint256[] memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (uint256[] memory) {
        // sanitize
        pos = Math.min(pos, array.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(
                add(add(array, 0x20), mul(pos, 0x20)),
                add(add(replacement, 0x20), mul(offset, 0x20)),
                mul(length, 0x20)
            )
        }

        return array;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytesSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getStringSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(bytes[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
     */
    function unsafeSetLength(string[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

@openzeppelin/contracts/utils/Comparators.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

@openzeppelin/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

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

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

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

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

@openzeppelin/contracts/utils/LowLevelCall.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

@openzeppelin/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

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

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

@openzeppelin/contracts/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If 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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

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

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

@openzeppelin/contracts/utils/SlotDerivation.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for *;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

@openzeppelin/contracts/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.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 `condition ? a : b`. 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. `condition ? a : b`) 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) {
        unchecked {
            // (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 buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 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 first 16 bytes (most significant half).
        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;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

@openzeppelin/contracts/utils/math/SafeCast.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/access/SingleAdminAccessControlUpgradeable.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";

/**
 * @title SingleAdminAccessControlUpgradeable
 * @notice AccessControl whose DEFAULT_ADMIN_ROLE is held by exactly one account at all times.
 *         On CiretaToken, CiretaFractionToken1155 and IssuerOTCToken that account is platform
 *         governance (the governance TimelockController): the sole upgrader and the admin of
 *         every other role.
 *
 *         - `grantRole` / `revokeRole` / `renounceRole` refuse DEFAULT_ADMIN_ROLE, so governance
 *           can neither add a second admin, revoke itself, nor renounce.
 *         - The role moves only through `transferDefaultAdmin`, which revokes it from the
 *           current holder and grants it to the new one in the same call. The new holder must be
 *           a contract (timelock / Safe), never an EOA or an EIP-7702-delegated EOA.
 *         - Internally, `_grantRole(DEFAULT_ADMIN_ROLE, x)` reverts while an admin exists, so the
 *           initializer can grant it once and no other code path can create a second holder.
 *
 *         A single-step transfer is deliberate: every call is already scheduled through the
 *         governance TimelockController, and the factory that deploys a fraction token hands the
 *         role to governance atomically inside the deploy transaction (a two-step accept would leave every new
 *         fraction waiting for a separate governance transaction).
 * @dev ERC-7201 namespaced storage: inheriting it adds no linear storage slot.
 * @custom:security-contact [email protected]
 */
abstract contract SingleAdminAccessControlUpgradeable is AccessControlUpgradeable {
    /// @custom:storage-location erc7201:cireta.storage.SingleAdminAccessControl
    struct SingleAdminStorage {
        address admin;
    }

    // keccak256(abi.encode(uint256(keccak256("cireta.storage.SingleAdminAccessControl")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant SINGLE_ADMIN_STORAGE =
        0xe148680c06a5a1e510b67398e19bd0c921822b90bc885726c62006b0632a4c00;

    /// @notice DEFAULT_ADMIN_ROLE moved from `previousAdmin` to `newAdmin`.
    event DefaultAdminTransferred(address indexed previousAdmin, address indexed newAdmin);

    /// @notice DEFAULT_ADMIN_ROLE cannot be granted, revoked or renounced; use transferDefaultAdmin.
    error DefaultAdminRoleLocked();
    /// @notice The new admin is zero, the current admin, or not a contract account.
    error InvalidDefaultAdmin(address account);

    function _singleAdminStorage() private pure returns (SingleAdminStorage storage $) {
        assembly {
            $.slot := SINGLE_ADMIN_STORAGE
        }
    }

    /// @notice The single DEFAULT_ADMIN_ROLE holder (platform governance).
    function defaultAdmin() public view returns (address) {
        return _singleAdminStorage().admin;
    }

    /**
     * @notice Move DEFAULT_ADMIN_ROLE (upgrades + role administration) to `newAdmin`, e.g. for a
     *         governance migration. Callable only by the current admin. The caller loses the role
     *         in the same call.
     * @param newAdmin New admin; must be a contract (not an EOA or an EIP-7702-delegated EOA),
     *                 different from the current admin, and acceptable to the inheriting
     *                 contract (`_checkNewDefaultAdmin`).
     */
    function transferDefaultAdmin(address newAdmin) external onlyRole(DEFAULT_ADMIN_ROLE) {
        address old = _singleAdminStorage().admin;
        // The caller must be the recorded single admin: on a proxy upgraded from plain AccessControl
        // the slot is empty, and transferring would leave the legacy holder as an irremovable 2nd admin.
        if (old != _msgSender()) revert InvalidDefaultAdmin(_msgSender());
        // Never self, never this contract (it cannot make calls), never an EOA.
        if (newAdmin == old || newAdmin == address(this) || !_isContractAccount(newAdmin)) {
            revert InvalidDefaultAdmin(newAdmin);
        }
        _checkNewDefaultAdmin(newAdmin);
        _revokeRole(DEFAULT_ADMIN_ROLE, old);
        _grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
        emit DefaultAdminTransferred(old, newAdmin);
    }

    /// @notice Grant a role. DEFAULT_ADMIN_ROLE is refused: it moves only via transferDefaultAdmin.
    function grantRole(bytes32 role, address account) public virtual override {
        if (role == DEFAULT_ADMIN_ROLE) revert DefaultAdminRoleLocked();
        super.grantRole(role, account);
    }

    /// @notice Revoke a role. DEFAULT_ADMIN_ROLE is refused: governance cannot revoke itself.
    function revokeRole(bytes32 role, address account) public virtual override {
        if (role == DEFAULT_ADMIN_ROLE) revert DefaultAdminRoleLocked();
        super.revokeRole(role, account);
    }

    /// @notice Renounce a role. DEFAULT_ADMIN_ROLE is refused (it would orphan upgrades).
    function renounceRole(bytes32 role, address callerConfirmation) public virtual override {
        if (role == DEFAULT_ADMIN_ROLE) revert DefaultAdminRoleLocked();
        super.renounceRole(role, callerConfirmation);
    }

    /// @dev Hook for contract-specific restrictions on the new admin (e.g. never the issuer).
    function _checkNewDefaultAdmin(address newAdmin) internal view virtual {}

    /// @dev Keeps `defaultAdmin()` in sync and refuses a second DEFAULT_ADMIN_ROLE holder.
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        if (role == DEFAULT_ADMIN_ROLE) {
            SingleAdminStorage storage $ = _singleAdminStorage();
            if ($.admin != address(0)) revert DefaultAdminRoleLocked();
            if (account == address(0)) revert InvalidDefaultAdmin(account);
            $.admin = account;
        }
        return super._grantRole(role, account);
    }

    /// @dev Clears `defaultAdmin()` when its holder loses the role (only via transferDefaultAdmin).
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        if (role == DEFAULT_ADMIN_ROLE) {
            SingleAdminStorage storage $ = _singleAdminStorage();
            if ($.admin == account) $.admin = address(0);
        }
        return super._revokeRole(role, account);
    }

    /// @dev True if `account` has code that is not an EIP-7702 delegation designator.
    function _isContractAccount(address account) internal view returns (bool) {
        uint256 size = account.code.length;
        if (size == 0) return false;
        if (size == 23 && bytes3(account.code) == 0xef0100) return false;
        return true;
    }
}

src/fraction/CiretaFractionToken1155.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "../access/SingleAdminAccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Utils.sol";
import "../interfaces/ICiretaIdentityRegistry.sol";

/// @dev The ERC-3643 views the fraction token consults on the project token. Addresses are
///      returned as `address` so the interface is ABI-compatible with any typed return.
interface IFractionProjectToken {
    function identityRegistry() external view returns (address);
    function compliance() external view returns (address);
    function isFrozen(address account) external view returns (bool);
    function paused() external view returns (bool);
}

interface IFractionCompliance {
    function canTransfer(address from, address to, uint256 amount) external view returns (bool);
}

interface IFractionRegistry {
    function isVerified(address account) external view returns (bool);
}

/// @dev Vault hook that moves vesting credit / refund basis with the fractions.
interface IFractionVaultHook {
    function onFractionTransfer(address from, address to, uint256[] calldata ids, uint256[] calldata values) external;
}

/// @dev Live operator lookup: fraction -> vault.sale() -> Sale.operator() (= factory operator).
interface IFractionVaultSale {
    function sale() external view returns (address);
}

interface IFractionSaleOperator {
    function operator() external view returns (address);
}

/// @title CiretaFractionToken1155
/// @notice ERC-1155 claim on project tokens escrowed in a CiretaVault. Two ids:
///         - id 1 (FRACTION_ID_USDC): minted on Sale.buy() — refundable if the sale fails
///         - id 2 (FRACTION_ID_OTC):  minted on Sale.buyOTC() — not refundable on-chain
///
///         Peer transfers enforce the PROJECT TOKEN's own rules: the token is not paused
///         (a trading halt also halts vested positions), sender and recipient verified on
///         the token's identity registry, neither frozen on the token, and
///         `compliance.canTransfer(from, to, amount)`. Every holder-to-holder movement
///         (peer or recovery) first calls the vault so vesting credit and refund basis move
///         with the fractions, and the vault reports the move to the token's
///         compliance escrow ledger so stateful modules see it.
///
///         Roles:
///         - DEFAULT_ADMIN_ROLE: platform governance (timelock). Upgrade authority. Exactly one holder:
///           it cannot be granted, revoked or renounced and moves only through
///           transferDefaultAdmin. The deploying CiretaFractionFactory holds it during the
///           deploy transaction only and hands it to governance with transferDefaultAdmin.
///         - Recovery (forced transfers for lost keys / legal orders): the platform operator,
///           resolved LIVE through vault -> Sale -> CiretaSaleFactory.operator(), so rotating the
///           operator on the factory takes effect here immediately and the previous operator
///           keeps nothing. Governance may additionally grant RECOVERY_ROLE explicitly.
///         - MINTER_ROLE: the Sale. BURNER_ROLE: the vault.
/// @custom:security-contact [email protected]
contract CiretaFractionToken1155 is
    Initializable,
    ERC1155Upgradeable,
    SingleAdminAccessControlUpgradeable,
    UUPSUpgradeable
{
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");

    /// @notice Token ids — keep in sync with Sale.FRACTION_ID_USDC / FRACTION_ID_OTC.
    uint256 public constant ID_USDC = 1;
    uint256 public constant ID_OTC  = 2;

    ICiretaIdentityRegistry public identityRegistry;
    address public projectToken;
    address public vault;
    uint8 public tokenDecimals;     // Snapshot from project token, used by UI

    string public name;
    string public symbol;

    bytes32 public constant RECOVERY_ROLE = keccak256("RECOVERY_ROLE");

    /// @notice Incremented on every UUPS upgrade.
    uint256 public upgradeNonce;

    /// @dev Set only for the duration of the internal `_update` of a recovery transfer.
    bool private _forcedOperation;

    /// @dev Reserved storage gap for future upgrades
    uint256[98] private __gap;

    // --- Events ---
    event FractionsMinted(address indexed to, uint256 indexed id, uint256 amount);
    event FractionsBurned(address indexed from, uint256 indexed id, uint256 amount);
    event FractionsRecovered(
        address indexed from,
        address indexed to,
        uint256 indexed id,
        uint256 amount,
        bytes reason
    );
    event VaultSet(address indexed vault);
    /// @notice Emitted on every UUPS upgrade.
    event ImplementationUpgraded(address indexed newImplementation, uint256 nonce);

    // --- Errors ---
    error ZeroAddress();
    error ZeroAmount();
    error InvalidId();
    error RecipientNotVerified(address to);
    error SenderNotVerified(address from);
    error AccountFrozen(address account);
    error TransferNotCompliant();
    error TokenPaused();
    error VaultAlreadySet();
    error VaultNotSet();
    error RenounceDisabled();

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @param _vault May be zero during the factory's two-step deploy; set once via setVault.
    /// @param admin  Initial DEFAULT_ADMIN_ROLE holder (the deploying factory, which hands it to governance).
    function initialize(
        string memory _name,
        string memory _symbol,
        uint8 _decimals,
        address _identityRegistry,
        address _projectToken,
        address _vault,
        address admin
    ) public initializer {
        __ERC1155_init("");

        if (_identityRegistry == address(0) || _projectToken == address(0) || admin == address(0)) {
            revert ZeroAddress();
        }

        name = _name;
        symbol = _symbol;
        tokenDecimals = _decimals;
        identityRegistry = ICiretaIdentityRegistry(_identityRegistry);
        projectToken = _projectToken;
        vault = _vault;

        _grantRole(DEFAULT_ADMIN_ROLE, admin);
    }

    /// @notice One-shot vault binding for the two-step factory deploy.
    function setVault(address _vault) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (vault != address(0)) revert VaultAlreadySet();
        if (_vault == address(0)) revert ZeroAddress();
        vault = _vault;
        emit VaultSet(_vault);
    }

    /// @notice Mint fractions of a specific id to an investor. Sale-only.
    function mint(address to, uint256 id, uint256 amount, bytes memory data)
        external
        onlyRole(MINTER_ROLE)
    {
        if (id != ID_USDC && id != ID_OTC) revert InvalidId();
        if (amount == 0) revert ZeroAmount();
        if (!identityRegistry.isVerified(to)) revert RecipientNotVerified(to);
        _mint(to, id, amount, data);
        emit FractionsMinted(to, id, amount);
    }

    /// @notice Burn fractions of a specific id from an address. Vault only.
    function burn(address from, uint256 id, uint256 amount)
        external
        onlyRole(BURNER_ROLE)
    {
        if (id != ID_USDC && id != ID_OTC) revert InvalidId();
        if (amount == 0) revert ZeroAmount();
        _burn(from, id, amount);
        emit FractionsBurned(from, id, amount);
    }

    /// @dev Holder-to-holder movements: peer transfers enforce the project token's KYC, freeze
    ///      and compliance rules; every movement (peer or recovery) notifies the vault first so
    ///      vesting credit and refund basis travel with the fractions. Mint/burn skip both.
    function _update(
        address from,
        address to,
        uint256[] memory ids,
        uint256[] memory values
    ) internal override {
        if (from != address(0) && to != address(0)) {
            if (!_forcedOperation) _checkPeerTransfer(from, to, values);
            address v = vault;
            if (v == address(0)) revert VaultNotSet();
            IFractionVaultHook(v).onFractionTransfer(from, to, ids, values);
        }
        super._update(from, to, ids, values);
    }

    /// @dev The fraction is a claim on the project token, so beneficial ownership may only move
    ///      where the project token itself could move.
    function _checkPeerTransfer(address from, address to, uint256[] memory values) internal view {
        IFractionProjectToken t = IFractionProjectToken(projectToken);
        if (t.paused()) revert TokenPaused();
        IFractionRegistry ir = IFractionRegistry(t.identityRegistry());
        if (!ir.isVerified(from)) revert SenderNotVerified(from);
        if (!ir.isVerified(to)) revert RecipientNotVerified(to);
        if (t.isFrozen(from)) revert AccountFrozen(from);
        if (t.isFrozen(to)) revert AccountFrozen(to);
        uint256 amount;
        for (uint256 i = 0; i < values.length; i++) amount += values[i];
        if (!IFractionCompliance(t.compliance()).canTransfer(from, to, amount)) revert TransferNotCompliant();
    }

    /// @notice Force-transfer fractions (lost keys, court orders, inheritance). Bypasses the
    ///         sender checks; the recipient must be verified and not frozen on the project token.
    ///         Vesting credit / refund basis move with the fractions.
    /// @dev The bypass flag is cleared BEFORE the ERC-1155 acceptance callback, so a contract
    ///      recipient cannot re-transfer unchecked from inside onERC1155Received.
    function recoverFractions(
        address from,
        address to,
        uint256 id,
        uint256 amount,
        bytes calldata reason
    ) external {
        if (!hasRole(RECOVERY_ROLE, msg.sender) && !_isLiveOperator(msg.sender)) {
            revert AccessControlUnauthorizedAccount(msg.sender, RECOVERY_ROLE);
        }
        if (id != ID_USDC && id != ID_OTC) revert InvalidId();
        if (amount == 0) revert ZeroAmount();
        if (to == address(0) || from == address(0)) revert ZeroAddress();
        // Never to a registered system contract (verified, but nobody could move them back).
        if (!identityRegistry.isVerified(to) || identityRegistry.isSystemContract(to)) revert RecipientNotVerified(to);
        if (IFractionProjectToken(projectToken).isFrozen(to)) revert AccountFrozen(to);

        uint256[] memory ids = new uint256[](1);
        uint256[] memory values = new uint256[](1);
        ids[0] = id;
        values[0] = amount;

        _forcedOperation = true;
        _update(from, to, ids, values);
        _forcedOperation = false;

        ERC1155Utils.checkOnERC1155Received(_msgSender(), from, to, id, amount, "");
        emit FractionsRecovered(from, to, id, amount, reason);
    }

    /// @notice The platform operator currently allowed to recover fractions (address(0) if it
    ///         cannot be resolved, e.g. before the vault is bound).
    function recoveryOperator() public view returns (address op) {
        address v = vault;
        if (v == address(0)) return address(0);
        address s = _readAddress(v, abi.encodeCall(IFractionVaultSale.sale, ()));
        if (s == address(0)) return address(0);
        op = _readAddress(s, abi.encodeCall(IFractionSaleOperator.operator, ()));
    }

    /// @dev True when `account` is the live platform operator of this fraction's sale.
    function _isLiveOperator(address account) internal view returns (bool) {
        address op = recoveryOperator();
        return op != address(0) && op == account;
    }

    /// @dev Validated address-returning staticcall: returns address(0) on any failure or on
    ///      malformed return data, never reverts.
    function _readAddress(address target, bytes memory data) private view returns (address) {
        if (target.code.length == 0) return address(0);
        (bool ok, bytes memory ret) = target.staticcall(data);
        if (!ok || ret.length != 32) return address(0);
        uint256 raw = abi.decode(ret, (uint256));
        if (raw > type(uint160).max) return address(0);
        return address(uint160(raw));
    }

    /// @notice DEFAULT_ADMIN_ROLE cannot be renounced (it is the only upgrade authority);
    ///         governance moves it with transferDefaultAdmin.
    function renounceRole(bytes32 role, address callerConfirmation) public override {
        if (role == DEFAULT_ADMIN_ROLE) revert RenounceDisabled();
        super.renounceRole(role, callerConfirmation);
    }

    /// @dev Upgrade authority: DEFAULT_ADMIN_ROLE (platform governance timelock).
    function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {
        upgradeNonce++;
        emit ImplementationUpgraded(newImplementation, upgradeNonce);
    }

    /// @notice Contract version.
    function version() external pure returns (string memory) { return "7.1.1"; }

    /// @dev Required for AccessControl + ERC1155 — explicit override for the diamond inheritance.
    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC1155Upgradeable, AccessControlUpgradeable)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }
}

src/interfaces/ICiretaIdentityRegistry.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

/**
 * @title ICiretaIdentityRegistry
 * @dev The platform identity registry surface every Cireta contract depends on.
 *
 *      Investors are registered with a real ISO 3166-1 numeric country code
 *      (never 0). Platform contracts that must hold or receive permissioned tokens
 *      (token, compliance, sale, vault, fraction, OTC token, redemption manager)
 *      are registered separately as system contracts — they are verified but
 *      carry no country and are distinguishable from investors on-chain.
 */
interface ICiretaIdentityRegistry {
    /// @notice True for whitelisted investors and registered system contracts.
    function isVerified(address account) external view returns (bool);

    /// @notice Investor country (ISO 3166-1 numeric). 0 = not an investor.
    function investorCountry(address account) external view returns (uint16);

    /// @notice True only for platform contracts registered via registerSystemContract.
    function isSystemContract(address account) external view returns (bool);

    /// @notice Whitelist a KYC-approved investor wallet. Reverts on country 0.
    function addToWhitelist(address wallet, uint16 country) external;

    /// @notice Register a platform-deployed contract (factories only).
    function registerSystemContract(address account) external;
}

src/otc/IssuerOTCToken.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../access/SingleAdminAccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "../interfaces/ICiretaIdentityRegistry.sol";

/// @dev The deploying IssuerOTCTokenFactory: source of the platform IssuerRegistry
///      and of the platform operator / guardian the issuer may never be.
interface IOTCFactoryRegistry {
    function issuerRegistry() external view returns (address);
    function operator() external view returns (address);
    function guardian() external view returns (address);
}

/// @dev Platform IssuerRegistry surface.
interface IOTCIssuerRegistry {
    function isActiveIssuer(address wallet) external view returns (bool);
    function rotatedTo(address wallet) external view returns (address);
}

/// @title IssuerOTCToken
/// @notice Per-issuer ERC-20 OTC voucher used as payment in Sale.buyOTC().
///         Issuers mint these to investors who paid off-platform; the Sale contract
///         burns them on purchase, converting them into project tokens.
///         Wallet-to-wallet transfers require both sender and recipient to be
///         verified on the platform identity registry.
///
/// @dev Role model:
///      - DEFAULT_ADMIN_ROLE (role admin + sole upgrade authority) = platform governance
///        (TimelockController), supplied by IssuerOTCTokenFactory at deploy time. Exactly one
///        holder: it cannot be granted, revoked or renounced and moves only through
///        transferDefaultAdmin.
///      - MINTER_ROLE = the issuer wallet. The issuer holds no other role and cannot
///        grant roles or upgrade. The issuer wallet is never governance, nor the
///        deploying factory's operator or guardian, at deploy and on every syncIssuer.
///      - Minting requires the issuer wallet to be ACTIVE in the platform
///        IssuerRegistry (read through the deploying factory), so the operator's issuer suspension
///        stops voucher minting at once; after an IssuerRegistry wallet rotation governance
///        (timelock) calls syncIssuer(newWallet) to move issuerWallet and MINTER_ROLE to the new
///        wallet (never permissionless: a non-timelocked rotation must not reach the mint,
///        and the wallet is fixed when governance proposes, never resolved at execution).
/// @custom:security-contact [email protected]
contract IssuerOTCToken is
    Initializable,
    ERC20Upgradeable,
    SingleAdminAccessControlUpgradeable,
    UUPSUpgradeable
{
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    /// @notice Bound on the IssuerRegistry rotation chain syncIssuer follows.
    uint256 public constant MAX_ROTATION_HOPS = 8;

    ICiretaIdentityRegistry public identityRegistry;
    address public issuerWallet;

    /// @notice Incremented on every UUPS upgrade.
    uint256 public upgradeNonce;

    /// @notice The factory that initialized this token (IssuerRegistry source).
    address public factory;

    /// @dev Reserved storage gap for future upgrades
    uint256[99] private __gap;

    // --- Events ---
    event OTCMinted(address indexed to, uint256 amount);
    event OTCBurned(address indexed from, uint256 amount);
    /// @notice Emitted when governance repoints the identity registry.
    event IdentityRegistryUpdated(address indexed oldRegistry, address indexed newRegistry);
    /// @notice Emitted on every UUPS upgrade. ERC1967 also emits `Upgraded(impl)`
    /// from the proxy; this is a parallel marker that includes the nonce when
    /// available, so off-chain monitors can sequence upgrade-related events.
    event ImplementationUpgraded(address indexed newImplementation, uint256 nonce);
    /// @notice issuerWallet and MINTER_ROLE followed an IssuerRegistry rotation.
    event IssuerWalletSynced(address indexed previousWallet, address indexed newWallet);

    // --- Errors ---
    error RecipientNotVerified(address to);
    error SenderNotVerified(address from);
    error ZeroAddress();
    error ZeroAmount();
    error IssuerCannotBeGovernance();
    error CannotRenounceAdmin();
    error IssuerNotActive(address issuer);
    error IssuerNotRotated();
    /// @notice `expected` is not the current end of the registry rotation chain (`current`).
    error RotationTargetMismatch(address expected, address current);
    /// @notice The issuer wallet is the deploying factory's operator or guardian.
    error IssuerIsPlatformRole(address account);
    /// @dev MINTER_ROLE only ever belongs to issuerWallet; it is never granted directly.
    error MinterFollowsIssuer(address account);

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Initialize the OTC token proxy.
    /// @param name               Token name (e.g. "Cireta OTC - Acme Gold")
    /// @param symbol             Token symbol (e.g. "cOTC-ACME")
    /// @param _issuerWallet      Issuer wallet; receives MINTER_ROLE only. Must not be governance,
    ///                           nor the operator / guardian of the deploying factory.
    /// @param _identityRegistry  Platform identity registry used for transfer gating
    /// @param _governance        Platform governance (timelock); receives DEFAULT_ADMIN_ROLE
    ///                           and is the only account that can upgrade this proxy
    function initialize(
        string memory name,
        string memory symbol,
        address _issuerWallet,
        address _identityRegistry,
        address _governance
    ) public initializer {
        if (_issuerWallet == address(0)) revert ZeroAddress();
        if (_identityRegistry == address(0)) revert ZeroAddress();
        if (_governance == address(0)) revert ZeroAddress();
        if (_governance == _issuerWallet) revert IssuerCannotBeGovernance();

        __ERC20_init(name, symbol);

        identityRegistry = ICiretaIdentityRegistry(_identityRegistry);
        issuerWallet = _issuerWallet;
        factory = msg.sender;
        _checkNotPlatformRole(_issuerWallet);

        _grantRole(DEFAULT_ADMIN_ROLE, _governance);
        _grantRole(MINTER_ROLE, _issuerWallet);
    }

    /// @notice 6 decimals to match USDC
    function decimals() public pure override returns (uint8) {
        return 6;
    }

    /// @notice Mint OTC tokens to an investor. Only callable by MINTER_ROLE (issuer), and only
    ///         while the issuer wallet is active in the platform IssuerRegistry. A registry
    ///         that reads as zero refuses too: it fails closed if a factory upgrade loses it.
    /// @param to      Recipient address
    /// @param amount  Amount to mint (6 decimals)
    function mint(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
        if (amount == 0) revert ZeroAmount();
        address reg = _issuerRegistry();
        if (reg == address(0) || !IOTCIssuerRegistry(reg).isActiveIssuer(issuerWallet)) {
            revert IssuerNotActive(issuerWallet);
        }
        _mint(to, amount);
        emit OTCMinted(to, amount);
    }

    /// @notice Burn OTC tokens from an address. Public — Sale contract calls this
    ///         to consume OTC tokens during buyOTC().
    /// @param from    Address to burn from (must have approved this caller)
    /// @param amount  Amount to burn
    function burn(address from, uint256 amount) external {
        if (from != msg.sender) {
            _spendAllowance(from, msg.sender, amount);
        }
        _burn(from, amount);
        emit OTCBurned(from, amount);
    }

    /// @notice Follow an IssuerRegistry wallet rotation: moves issuerWallet and
    ///         MINTER_ROLE to `expectedIssuer`. Governance (timelock) only: a registry rotation is an
    ///         ISSUER_MANAGER_ROLE action with no delay, so it must never hand the voucher mint
    ///         (which counts toward a sale's soft cap) to a new key by itself. Until governance
    ///         syncs, the rotated-out wallet is Suspended and nobody can mint.
    /// @dev The target is bound at proposal time: the call reverts
    ///      `RotationTargetMismatch` unless `expectedIssuer` is the current end of the
    ///      IssuerRegistry.rotatedTo chain from issuerWallet (at most MAX_ROTATION_HOPS hops).
    ///      A further rotation during the timelock therefore makes the scheduled sync fail
    ///      instead of landing on a wallet governance never reviewed. The new wallet may not be
    ///      governance or the factory's operator / guardian.
    /// @param expectedIssuer The wallet governance reviewed; must be the registry's rotation target.
    function syncIssuer(address expectedIssuer) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (expectedIssuer == address(0)) revert ZeroAddress();
        address reg = _issuerRegistry();
        address next = reg == address(0) ? address(0) : IOTCIssuerRegistry(reg).rotatedTo(issuerWallet);
        if (next == address(0)) revert IssuerNotRotated();
        for (uint256 hops = 1; hops < MAX_ROTATION_HOPS; hops++) {
            address further = IOTCIssuerRegistry(reg).rotatedTo(next);
            if (further == address(0)) break;
            next = further;
        }
        if (next != expectedIssuer || IOTCIssuerRegistry(reg).rotatedTo(next) != address(0)) {
            revert RotationTargetMismatch(expectedIssuer, next);
        }
        if (hasRole(DEFAULT_ADMIN_ROLE, next)) revert IssuerCannotBeGovernance();
        _checkNotPlatformRole(next);
        address old = issuerWallet;
        issuerWallet = next;
        _revokeRole(MINTER_ROLE, old);
        _grantRole(MINTER_ROLE, next);
        emit IssuerWalletSynced(old, next);
    }

    /// @dev The IssuerRegistry read through the deploying factory (zero if it exposes none).
    function _issuerRegistry() internal view returns (address) {
        return _readFactory(IOTCFactoryRegistry.issuerRegistry.selector);
    }

    /// @dev Reverts when `wallet` is the deploying factory's operator or guardian. A token
    ///      deployed outside a factory (factory without code or without these views) skips it.
    function _checkNotPlatformRole(address wallet) internal view {
        if (
            wallet == _readFactory(IOTCFactoryRegistry.operator.selector)
                || wallet == _readFactory(IOTCFactoryRegistry.guardian.selector)
        ) revert IssuerIsPlatformRole(wallet);
    }

    /// @dev Address-returning view on the deploying factory; zero on any failure or malformed return.
    function _readFactory(bytes4 selector) internal view returns (address) {
        address f = factory;
        if (f.code.length == 0) return address(0);
        (bool ok, bytes memory ret) = f.staticcall(abi.encodeWithSelector(selector));
        if (!ok || ret.length != 32) return address(0);
        uint256 raw = abi.decode(ret, (uint256));
        return raw > type(uint160).max ? address(0) : address(uint160(raw));
    }

    /// @dev MINTER_ROLE only ever goes to the current issuerWallet (it follows initialize /
    ///      syncIssuer), so no platform seat can mint vouchers that count toward a soft cap.
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        if (role == MINTER_ROLE && account != issuerWallet) revert MinterFollowsIssuer(account);
        return super._grantRole(role, account);
    }

    /// @dev transferDefaultAdmin never hands governance to the issuer wallet.
    function _checkNewDefaultAdmin(address newAdmin) internal view virtual override {
        if (newAdmin == issuerWallet) revert IssuerCannotBeGovernance();
    }

    /// @notice Repoint transfer gating to a new platform identity registry. Governance only.
    /// @param newRegistry The new identity registry (non-zero)
    function setIdentityRegistry(address newRegistry) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (newRegistry == address(0)) revert ZeroAddress();
        address old = address(identityRegistry);
        identityRegistry = ICiretaIdentityRegistry(newRegistry);
        emit IdentityRegistryUpdated(old, newRegistry);
    }

    /// @notice Renouncing DEFAULT_ADMIN_ROLE would brick upgrades and role management,
    ///         so it is disabled (governance moves it with transferDefaultAdmin). Other
    ///         roles can still be renounced.
    /// @param role              Role to renounce
    /// @param callerConfirmation Must equal msg.sender (OZ convention)
    function renounceRole(bytes32 role, address callerConfirmation) public override {
        if (role == DEFAULT_ADMIN_ROLE) revert CannotRenounceAdmin();
        super.renounceRole(role, callerConfirmation);
    }

    /// @notice Transfer gating — wallet-to-wallet transfers require both sides to be
    ///         verified. Mint (from == 0) and burn (to == 0) are always allowed.
    function _update(
        address from,
        address to,
        uint256 amount
    ) internal override {
        if (from != address(0) && to != address(0)) {
            if (!identityRegistry.isVerified(from)) revert SenderNotVerified(from);
            if (!identityRegistry.isVerified(to)) revert RecipientNotVerified(to);
        }
        super._update(from, to, amount);
    }

    /// @dev Upgrades are governance-only (DEFAULT_ADMIN_ROLE is never held by the issuer).
    function _authorizeUpgrade(address newImplementation) internal override onlyRole(DEFAULT_ADMIN_ROLE) {
        upgradeNonce++;
        emit ImplementationUpgraded(newImplementation, upgradeNonce);
    }

    /// @notice Contract version.
    function version() external pure returns (string memory) { return "7.3.1"; }
}

src/vault/CiretaVault.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;

import "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../fraction/CiretaFractionToken1155.sol";
import "../interfaces/ICiretaIdentityRegistry.sol";

/// @dev ERC-3643 views of the project token used for primary-issuance eligibility.
interface IVaultProjectToken {
    function paused() external view returns (bool);
    function isFrozen(address account) external view returns (bool);
    function identityRegistry() external view returns (address);
    function compliance() external view returns (address);
}

/// @dev Project-token compliance: transfer rules plus the escrow ledger.
interface IVaultEscrowCompliance {
    function canTransfer(address from, address to, uint256 amount) external view returns (bool);
    function escrowMoved(address from, address to, uint256 amount) external;
}

/// @dev The Sale surface the vault reads (live operator, failed-sale flag, its factory).
interface IVaultSale {
    function operator() external view returns (address);
    function refundsActive() external view returns (bool);
    function factory() external view returns (address);
}

/// @dev Issuer-status reads for the settleOtc issuer payout: the platform IssuerRegistry
///      through the SaleFactory, and the project token's live issuer / suspension.
interface IVaultIssuerChecks {
    function issuerRegistry() external view returns (address);
    function isActiveIssuer(address wallet) external view returns (bool);
    function issuer() external view returns (address);
    function isIssuerSuspended() external view returns (bool);
}

/// @title CiretaVault
/// @notice Escrows the ERC-3643 project tokens that back a vested sale's ERC-1155 fractions.
///
///         Invariants:
///         - `totalLocked - totalReleased >= totalMintedFractions` while the sale is not
///           FinalizedFailed: every fraction in circulation is backed 1:1 by escrowed project
///           tokens. `recordAllocation` and `startVesting` enforce it, and nothing else can
///           reduce `totalLocked` below it before a failure. After a failure,
///           `returnDeposit` sends the issuer everything except the backing of outstanding OTC
///           (ID-2) fractions, so only `totalLocked - totalReleased >= outstandingOtc` holds: the
///           remaining ID-1 fractions are refund claims on the Sale's USDC, not on project tokens,
///           and are burned by claimRefund / claimRefundFor.
///         - Vesting credit and the ID-1 refund basis (`refundBasis`) move with the fractions on
///           every transfer (`onFractionTransfer`), so moving fractions between wallets can
///           neither accelerate vesting nor strand refunds.
///         - Vesting credit is tracked WAD-scaled (raw project-token units * 1e18). Splitting it
///           pro-rata on a transfer therefore rounds by at most 1e-18 of a raw unit, so even a
///           0-decimal project token cannot be drained of lock-up by many 1-unit transfers.
///
///         Eligibility and escrow ledger:
///         - Primary issuance follows the project token's rules: a vested buy is refused
///           unless the vault could deliver the tokens to the buyer right now (token not paused,
///           buyer verified on the token's registry and not frozen, compliance.canTransfer(vault,
///           buyer, amount)). Every position is reported to the token's compliance escrow ledger
///           (credit on buy, move on fraction transfer, debit on claim / refund / settlement), so
///           holder caps, balance caps and stateful modules see vested positions.
///         - claimUpTo lets a holder claim part of its vested amount.
///         - On a failed sale the escrow backing outstanding OTC (ID-2) fractions stays here; the
///           operator settles each ID-2 holder (settleOtc), it never goes back to the issuer with
///           the rest of the deposit.
///         - Vesting schedules are bounded by MAX_VESTING_DURATION.
///
///         Roles:
///         - owner (platform governance timelock, Ownable2Step, renounce disabled): upgrades only.
///         - sale: deposits, allocation records, vesting start, refund settlement, deposit return,
///           excess withdrawal, issuer sync (follows Sale.syncIssuer).
///         - operator (resolved live through the Sale): OTC settlement of a failed sale.
///         - issuer (the sale issuer): receives unsold / returned project tokens.
/// @custom:security-contact [email protected]
contract CiretaVault is Initializable, Ownable2StepUpgradeable, UUPSUpgradeable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    struct VestingConfig {
        uint256 cliffDuration;
        uint256 vestingDuration;
    }

    // --- State ---
    IERC20 public projectToken;
    CiretaFractionToken1155 public fractionToken;
    VestingConfig public vestingConfig;
    address public sale;
    address public issuer;
    bool public finalized;

    uint256 public totalLocked;
    uint256 public totalReleased;
    uint256 public vestingStartTime;

    ICiretaIdentityRegistry public identityRegistry;

    /// @notice Fractions currently outstanding across both IDs (minted - claimed - refunded).
    uint256 public totalMintedFractions;

    /// @dev Vesting credit already released against the fractions a holder currently owns,
    ///      WAD-scaled (raw project-token units * CREDIT_SCALE). Moves pro-rata with
    ///      transferred fractions. Read via claimedByHolder() / claimedCreditWad().
    mapping(address => uint256) private _creditWad;

    /// @notice Payment-token amount refundable against the ID-1 fractions a holder owns if the
    ///         sale fails. Recorded at purchase, moves pro-rata with transferred ID-1 fractions.
    mapping(address => uint256) public refundBasis;

    /// @notice Incremented on every UUPS upgrade.
    uint256 public upgradeNonce;

    /// @notice Outstanding OTC (ID-2) fractions: their backing never returns to the issuer with a
    ///         failed sale's deposit.
    uint256 public outstandingOtc;

    /// @dev Reserved storage gap for future upgrades
    uint256[99] private __gap;

    /// @notice Fixed-point scale of the vesting credit.
    uint256 public constant CREDIT_SCALE = 1e18;

    /// @notice Upper bound on the vesting duration (and so the cliff).
    uint256 public constant MAX_VESTING_DURATION = 3650 days;

    /// @notice Upper bound on the fractions ever recorded (outstanding + released). The
    ///         vesting math runs at `held * CREDIT_SCALE`; above this bound it would overflow and
    ///         lock every claim of the vault, so such an allocation is refused at purchase.
    uint256 public constant MAX_TOTAL_FRACTIONS = type(uint256).max / CREDIT_SCALE;

    // --- Events ---
    event TokensLocked(uint256 amount);
    event TokensClaimed(address indexed investor, uint256 fractionsBurned, uint256 projectTokensReleased);
    event VestingStarted(uint256 timestamp);
    event IssuerExcessWithdrawn(address indexed issuer, uint256 amount);
    /// @notice Emitted on every Sale-driven fraction mint.
    event AllocationRecorded(uint256 indexed id, uint256 fractionAmount, uint256 newTotal);
    /// @notice Emitted when a failed sale refunds a holder's ID-1 fractions.
    event RefundSettled(address indexed holder, uint256 fractionsBurned, uint256 refundAmount);
    /// @notice Emitted when the escrow of a Draft / Rejected / failed sale is returned to the issuer.
    event DepositReturned(address indexed issuer, uint256 amount);
    /// @notice Emitted on every UUPS upgrade.
    event ImplementationUpgraded(address indexed newImplementation, uint256 nonce);
    /// @notice The Sale moved the issuer to its rotated wallet.
    event IssuerUpdated(address indexed previousIssuer, address indexed newIssuer);
    /// @notice A failed sale's OTC holder was settled by the operator.
    event OtcSettled(address indexed holder, uint256 amount, bool delivered);

    // --- Errors ---
    error NotFinalized();
    error AlreadyFinalized();
    error NothingToClaim();
    error OnlySale();
    error OnlyIssuer();
    error OnlyFractionToken();
    error ZeroAddress();
    error InvalidVestingConfig();
    error KYCRequired();
    error InvalidId();
    error Undercollateralized();
    error RenounceDisabled();
    error BuyerNotEligible(address buyer);
    error TokenPaused();
    error OnlyOperator();
    error SaleNotFailed();
    error AllocationTooLarge();
    error IssuerNotActive(address issuer);

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() { _disableInitializers(); }

    /// @param _projectToken     ERC-3643 token escrowed by this vault (must equal Sale.token()).
    /// @param _fractionToken    The ERC-1155 fraction token whose supply this vault backs.
    /// @param _identityRegistry Platform identity registry (claim-time KYC).
    /// @param _sale             The Sale proxy allowed to drive the vault.
    /// @param _issuer           The sale issuer; receives unsold or returned project tokens.
    /// @param _governance       Platform governance (timelock) — owner / upgrade authority.
    function initialize(
        address _projectToken,
        address _fractionToken,
        address _identityRegistry,
        uint256 _cliffDuration,
        uint256 _vestingDuration,
        address _sale,
        address _issuer,
        address _governance
    ) public initializer {
        __Ownable_init(_governance);
        __Ownable2Step_init();

        if (_projectToken == address(0) || _fractionToken == address(0) || _identityRegistry == address(0)) {
            revert ZeroAddress();
        }
        if (_sale == address(0) || _issuer == address(0)) revert ZeroAddress();
        // cliff == vesting is valid: lock-up-only variant (all tokens unlock at once at t=start+cliff).
        if (_vestingDuration == 0 || _cliffDuration > _vestingDuration || _vestingDuration > MAX_VESTING_DURATION) {
            revert InvalidVestingConfig();
        }

        projectToken = IERC20(_projectToken);
        fractionToken = CiretaFractionToken1155(_fractionToken);
        identityRegistry = ICiretaIdentityRegistry(_identityRegistry);
        vestingConfig = VestingConfig(_cliffDuration, _vestingDuration);
        sale = _sale;
        issuer = _issuer;
    }

    modifier onlySale() {
        if (msg.sender != sale) revert OnlySale();
        _;
    }

    /// @notice Disabled: the vault must always have a governance owner.
    function renounceOwnership() public pure override {
        revert RenounceDisabled();
    }

    // ──────────────────────────────────────────────
    //  SALE HOOKS
    // ──────────────────────────────────────────────

    /// @notice Pull `amount` project tokens from the Sale into escrow. Sale-only.
    function depositTokens(uint256 amount) external onlySale {
        if (finalized) revert AlreadyFinalized();
        projectToken.safeTransferFrom(msg.sender, address(this), amount);
        totalLocked += amount;
        emit TokensLocked(amount);
    }

    /// @notice Record a Sale-driven fraction mint. Reverts if the escrow would no longer
    ///         back every outstanding fraction 1:1, if the vault's total would leave the
    ///         range its vesting math supports (MAX_TOTAL_FRACTIONS), or if the buyer is
    ///         not eligible to receive the project token from this vault right now.
    ///         Credits the position to the buyer on the token's compliance escrow ledger.
    /// @param buyer          Fraction recipient.
    /// @param id             1 = payment-token purchase, 2 = OTC purchase.
    /// @param fractionAmount Fractions minted (project-token raw units).
    /// @param paidAmount     Payment-token amount paid (ID 1 only; refundable on failure).
    function recordAllocation(address buyer, uint256 id, uint256 fractionAmount, uint256 paidAmount)
        external
        onlySale
    {
        if (id != 1 && id != 2) revert InvalidId();
        if (finalized) revert AlreadyFinalized();
        uint256 newOutstanding = totalMintedFractions + fractionAmount;
        if (newOutstanding + totalReleased > MAX_TOTAL_FRACTIONS) revert AllocationTooLarge();
        if (totalLocked - totalReleased < newOutstanding) revert Undercollateralized();
        IVaultEscrowCompliance c = _requireEligible(buyer, fractionAmount);
        totalMintedFractions = newOutstanding;
        if (id == 1) refundBasis[buyer] += paidAmount;
        else outstandingOtc += fractionAmount;
        c.escrowMoved(address(0), buyer, fractionAmount);
        emit AllocationRecorded(id, fractionAmount, newOutstanding);
    }

    /// @dev Primary issuance follows the token's own rules: the buyer must be able to
    ///      receive `amount` project tokens from this vault right now.
    function _requireEligible(address buyer, uint256 amount) internal view returns (IVaultEscrowCompliance c) {
        IVaultProjectToken t = IVaultProjectToken(address(projectToken));
        if (t.paused()) revert TokenPaused();
        c = IVaultEscrowCompliance(t.compliance());
        if (
            t.isFrozen(buyer) || !ICiretaIdentityRegistry(t.identityRegistry()).isVerified(buyer)
                || !c.canTransfer(address(this), buyer, amount)
        ) revert BuyerNotEligible(buyer);
    }

    /// @dev The project token's compliance (escrow ledger).
    function _escrowLedger() internal view returns (IVaultEscrowCompliance) {
        return IVaultEscrowCompliance(IVaultProjectToken(address(projectToken)).compliance());
    }

    /// @notice Mark the sale successful and start the vesting clock. Sale-only.
    ///         Re-checks full collateralisation.
    function startVesting() external onlySale {
        if (finalized) revert AlreadyFinalized();
        if (totalLocked - totalReleased < totalMintedFractions) revert Undercollateralized();
        finalized = true;
        vestingStartTime = block.timestamp;
        emit VestingStarted(block.timestamp);
    }

    /// @notice Failed-sale refund for `holder`: burns all its ID-1 fractions and returns the
    ///         payment-token amount the Sale must pay out (its refund basis). Sale-only.
    /// @return refund Payment-token amount owed to `holder` (0 if nothing to refund).
    function settleRefund(address holder) external onlySale returns (uint256 refund) {
        if (finalized) revert AlreadyFinalized();
        uint256 idUsdc = fractionToken.ID_USDC();
        uint256 held = fractionToken.balanceOf(holder, idUsdc);
        refund = refundBasis[holder];
        refundBasis[holder] = 0;
        if (held > 0) {
            totalMintedFractions -= held;
            _escrowLedger().escrowMoved(holder, address(0), held);
            fractionToken.burn(holder, idUsdc, held);
        }
        emit RefundSettled(holder, held, refund);
    }

    /// @notice Return the escrow to the issuer, except what backs outstanding OTC (ID-2) fractions
    ///         (those holders paid off-chain and are settled by the operator). Sale-only; the
    ///         Sale allows it only while Draft (nothing sold), Rejected, or FinalizedFailed.
    /// @return amount Project tokens returned.
    function returnDeposit() external onlySale nonReentrant returns (uint256 amount) {
        if (finalized) revert AlreadyFinalized();
        uint256 available = totalLocked - totalReleased;
        uint256 reserved = outstandingOtc;
        if (available <= reserved) return 0;
        amount = available - reserved;
        totalLocked -= amount;
        projectToken.safeTransfer(issuer, amount);
        emit DepositReturned(issuer, amount);
    }

    /**
     * @notice Settle one OTC (ID-2) holder of a FAILED sale. Burns all its ID-2 fractions
     *         and releases the backing project tokens either to the holder (`deliver` = true: the
     *         issuer keeps the off-chain payment, the buyer gets what it paid for) or to the issuer
     *         (`deliver` = false: the issuer refunded the buyer off-chain). Platform operator
     *         (resolved live through the Sale) only.
     * @param holder  ID-2 fraction holder.
     * @param deliver True to deliver the tokens to `holder`, false to return them to the issuer.
     */
    function settleOtc(address holder, bool deliver) external nonReentrant {
        if (msg.sender != IVaultSale(sale).operator()) revert OnlyOperator();
        if (finalized || !IVaultSale(sale).refundsActive()) revert SaleNotFailed();
        uint256 idOtc = fractionToken.ID_OTC();
        uint256 held = fractionToken.balanceOf(holder, idOtc);
        if (held == 0) revert NothingToClaim();
        outstandingOtc -= held;
        totalMintedFractions -= held;
        totalReleased += held;
        // Paying the issuer needs the same check as every Sale payout (_isActiveIssuer): after a
        // registry rotation or suspension the vault may still name the old (e.g. compromised) key
        // until Sale.syncIssuer runs. Sync first, or settle with deliver = true.
        if (!deliver && !_issuerActive()) revert IssuerNotActive(issuer);
        _escrowLedger().escrowMoved(holder, address(0), held);
        fractionToken.burn(holder, idOtc, held);
        projectToken.safeTransfer(deliver ? holder : issuer, held);
        emit OtcSettled(holder, held, deliver);
    }

    /// @dev Mirrors Sale._isActiveIssuer for `issuer`: still the token's issuer, active in the platform
    ///      IssuerRegistry (read through the Sale's factory; skipped when none is configured), and not
    ///      suspended on the token. A failed or malformed read counts as not active (fail closed).
    function _issuerActive() internal view returns (bool) {
        (bool ok, address live) = _readAddress(address(projectToken), abi.encodeCall(IVaultIssuerChecks.issuer, ()));
        if (ok && live != address(0) && live != issuer) return false;
        (bool fOk, address fac) = _readAddress(sale, abi.encodeCall(IVaultSale.factory, ()));
        if (!fOk) return false;
        (bool rOk, address reg) = _readAddress(fac, abi.encodeCall(IVaultIssuerChecks.issuerRegistry, ()));
        if (rOk && reg != address(0)) {
            (bool aOk, bytes memory a) = reg.staticcall(abi.encodeCall(IVaultIssuerChecks.isActiveIssuer, (issuer)));
            if (!aOk || a.length != 32 || !abi.decode(a, (bool))) return false;
        }
        (bool sOk, bytes memory s) = address(projectToken).staticcall(abi.encodeCall(IVaultIssuerChecks.isIssuerSuspended, ()));
        return !(sOk && s.length == 32 && abi.decode(s, (bool)));
    }

    function _readAddress(address target, bytes memory data) private view returns (bool, address) {
        (bool ok, bytes memory ret) = target.staticcall(data);
        if (!ok || ret.length != 32) return (false, address(0));
        return (true, abi.decode(ret, (address)));
    }

    /// @notice Follow the Sale's issuer rotation (Sale.syncIssuer). Sale-only.
    /// @param newIssuer The Sale's new issuer.
    function setIssuer(address newIssuer) external onlySale {
        if (newIssuer == address(0)) revert ZeroAddress();
        emit IssuerUpdated(issuer, newIssuer);
        issuer = newIssuer;
    }

    /// @notice Send unsold project tokens (escrow not backing any outstanding fraction) to the
    ///         issuer after a successful sale. Sale-only (Sale.withdrawUnsoldTokens, which gates
    ///         on an active, unsuspended issuer); always pays `issuer`.
    function withdrawExcess() external nonReentrant onlySale {
        if (!finalized) revert NotFinalized();

        uint256 remainingLocked = totalLocked - totalReleased;
        if (remainingLocked <= totalMintedFractions) revert NothingToClaim();
        uint256 excess = remainingLocked - totalMintedFractions;

        totalLocked -= excess;
        projectToken.safeTransfer(issuer, excess);
        emit IssuerExcessWithdrawn(issuer, excess);
    }

    // ──────────────────────────────────────────────
    //  FRACTION HOOK
    // ──────────────────────────────────────────────

    /// @notice Called by the fraction token before every holder-to-holder movement (peer and
    ///         forced/recovery). Moves the sender's vesting credit and ID-1 refund basis pro-rata
    ///         with the fractions, using pre-transfer balances.
    function onFractionTransfer(address from, address to, uint256[] calldata ids, uint256[] calldata values)
        external
    {
        if (msg.sender != address(fractionToken)) revert OnlyFractionToken();
        uint256 moved;
        uint256 movedUsdc;
        for (uint256 i = 0; i < ids.length; i++) {
            moved += values[i];
            if (ids[i] == 1) movedUsdc += values[i];
        }
        if (moved == 0 || from == to) return;
        // The beneficial position moves with the fractions: compliance state hooks run.
        _escrowLedger().escrowMoved(from, to, moved);

        uint256 credit = _creditWad[from];
        if (credit > 0) {
            uint256 heldBefore = fractionToken.balanceOf(from, 1) + fractionToken.balanceOf(from, 2);
            // Exact pro-rata share at 1e-18 raw-unit precision. Rounding up moves at most
            // 1e-18 of a raw unit of extra credit per transfer, which is negligible at any
            // token decimals (a 1-raw-unit split no longer moves a whole raw unit).
            uint256 share = moved >= heldBefore ? credit : Math.mulDiv(credit, moved, heldBefore, Math.Rounding.Ceil);
            if (share > credit) share = credit;
            _creditWad[from] = credit - share;
            _creditWad[to] += share;
        }

        uint256 basis = refundBasis[from];
        if (movedUsdc > 0 && basis > 0) {
            uint256 heldUsdc = fractionToken.balanceOf(from, 1);
            uint256 share = movedUsdc >= heldUsdc ? basis : Math.mulDiv(basis, movedUsdc, heldUsdc);
            refundBasis[from] = basis - share;
            refundBasis[to] += share;
        }
    }

    // ──────────────────────────────────────────────
    //  CLAIM (called by investor)
    // ──────────────────────────────────────────────

    /// @notice Claim vested project tokens. Burns fractions (ID 1 first, then ID 2) from the
    ///         caller and releases project tokens 1:1. KYC re-verified at claim time.
    function claim() external nonReentrant {
        _claim(type(uint256).max);
    }

    /// @notice Claim at most `maxAmount` of the caller's vested project tokens, so a per-transfer
    ///         or balance limit can never block a holder's whole claim.
    /// @param maxAmount Upper bound on the project tokens released by this call.
    function claimUpTo(uint256 maxAmount) external nonReentrant {
        _claim(maxAmount);
    }

    function _claim(uint256 maxAmount) internal {
        if (!finalized) revert NotFinalized();
        if (!identityRegistry.isVerified(msg.sender)) revert KYCRequired();

        uint256 balUsdc = fractionToken.balanceOf(msg.sender, 1);
        uint256 balOtc  = fractionToken.balanceOf(msg.sender, 2);
        uint256 totalHeld = balUsdc + balOtc;
        if (totalHeld == 0) revert NothingToClaim();

        // Effective balance = held + already-claimed credit (credit moves with transfers).
        uint256 claimable = _claimable(totalHeld, _creditWad[msg.sender]);
        if (claimable > maxAmount) claimable = maxAmount;
        if (claimable == 0) revert NothingToClaim();

        uint256 burnUsdc = balUsdc >= claimable ? claimable : balUsdc;
        uint256 burnOtc = claimable - burnUsdc;

        // Effects
        _creditWad[msg.sender] += claimable * CREDIT_SCALE;
        totalMintedFractions -= claimable;
        totalReleased += claimable;

        if (burnOtc > 0) outstandingOtc -= burnOtc;

        // Interactions: debit the escrow position, burn fractions, release project tokens
        _escrowLedger().escrowMoved(msg.sender, address(0), claimable);
        if (burnUsdc > 0) fractionToken.burn(msg.sender, 1, burnUsdc);
        if (burnOtc > 0) fractionToken.burn(msg.sender, 2, burnOtc);
        projectToken.safeTransfer(msg.sender, claimable);

        emit TokensClaimed(msg.sender, claimable, claimable);
    }

    // ──────────────────────────────────────────────
    //  VIEW FUNCTIONS
    // ──────────────────────────────────────────────

    /// @notice How many project tokens the holder can claim right now.
    function getClaimable(address holder) public view returns (uint256) {
        if (!finalized) return 0;
        uint256 totalHeld = fractionToken.balanceOf(holder, 1) + fractionToken.balanceOf(holder, 2);
        if (totalHeld == 0) return 0;
        return _claimable(totalHeld, _creditWad[holder]);
    }

    /// @notice Vesting credit already released against `holder`'s current fractions, in raw
    ///         project-token units (rounded down; the exact value is claimedCreditWad / 1e18).
    function claimedByHolder(address holder) external view returns (uint256) {
        return _creditWad[holder] / CREDIT_SCALE;
    }

    /// @notice Exact vesting credit of `holder`, WAD-scaled (raw units * CREDIT_SCALE).
    function claimedCreditWad(address holder) external view returns (uint256) {
        return _creditWad[holder];
    }

    /// @notice Per-id breakdown of claimable amounts (proportional to balance ratio).
    function getClaimableById(address holder) external view returns (uint256 usdc, uint256 otc) {
        if (!finalized) return (0, 0);
        uint256 balUsdc = fractionToken.balanceOf(holder, 1);
        uint256 balOtc  = fractionToken.balanceOf(holder, 2);
        uint256 totalHeld = balUsdc + balOtc;
        if (totalHeld == 0) return (0, 0);
        uint256 claimable = getClaimable(holder);
        if (claimable == 0) return (0, 0);
        usdc = Math.mulDiv(claimable, balUsdc, totalHeld);
        otc  = claimable - usdc;
    }

    /// @notice Total vested amount for holder (effective balance = held + claimed credit).
    function getVested(address holder) external view returns (uint256) {
        if (!finalized) return 0;
        uint256 totalHeld = fractionToken.balanceOf(holder, 1) + fractionToken.balanceOf(holder, 2);
        return _calculateVested(totalHeld * CREDIT_SCALE + _creditWad[holder]) / CREDIT_SCALE;
    }

    // ──────────────────────────────────────────────
    //  INTERNAL
    // ──────────────────────────────────────────────

    /// @dev Whole raw units claimable now for `held` fractions carrying `creditWad` credit.
    ///      Computed at WAD precision and rounded down, so a holder never releases more than
    ///      vested(held + credit) - credit.
    function _claimable(uint256 held, uint256 creditWad) internal view returns (uint256 c) {
        uint256 vestedWad = _calculateVested(held * CREDIT_SCALE + creditWad);
        if (vestedWad <= creditWad) return 0;
        c = (vestedWad - creditWad) / CREDIT_SCALE;
        if (c > held) c = held;
    }

    /// @dev Vesting math (unit-agnostic: raw or WAD-scaled). Cliff + linear when cliff < vesting; lock-up-only when cliff == vesting.
    function _calculateVested(uint256 balance) internal view returns (uint256) {
        if (vestingStartTime == 0 || balance == 0) return 0;
        uint256 elapsed = block.timestamp - vestingStartTime;
        if (elapsed < vestingConfig.cliffDuration) return 0;
        if (elapsed >= vestingConfig.vestingDuration || vestingConfig.cliffDuration == vestingConfig.vestingDuration) {
            return balance;
        }
        uint256 linearElapsed = elapsed - vestingConfig.cliffDuration;
        uint256 linearDuration = vestingConfig.vestingDuration - vestingConfig.cliffDuration;
        return Math.mulDiv(balance, linearElapsed, linearDuration);
    }

    /// @dev Upgrade authority: platform governance (timelock) only.
    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {
        upgradeNonce++;
        emit ImplementationUpgraded(newImplementation, upgradeNonce);
    }

    /// @notice Contract version.
    function version() external pure returns (string memory) { return "7.2.0"; }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 100,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.