Skip to content
Verified contractPartialUNLICENSED

PositionManagerViews

Address0x8fe7af14db9bef814c4c8fbc0ce206cb17f25e8e
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 1 runs
EVM version
london
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,125,158
Creation transaction
0xd5d2685d8e…16e27dce29

48 files

src/core/PositionManagerViews.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "../interfaces/IVersioned.sol";
import "../interfaces/IPositionManagerViews.sol";
import "../interfaces/IPositionManager.sol";
import "../interfaces/IPositionManagerCore.sol";
import "../interfaces/ILoanOperationsManager.sol";
import "../interfaces/ICollateralManager.sol";
import "../interfaces/ILiquidationManager.sol";
import "../interfaces/ITermManager.sol";
import "../interfaces/ICircuitBreakerModule.sol";
import "../interfaces/IAdminModule.sol";
import "../interfaces/IBTCSpendAuthorizer.sol";
import "../interfaces/ILITActionValidator.sol";
import "../interfaces/IOperationAuthorizationRegistry.sol";
import "../interfaces/IPausableView.sol";
import "../interfaces/IUCDController.sol";
import "../libraries/LoanStatus.sol";
import "../libraries/SafeCalculations.sol";
import "../libraries/ExtensionValidationHelper.sol";
import "../roles/Roles.sol";
import "../libraries/PositionManagerErrors.sol";
/**
 * @title PositionManagerViews
 * @dev Handles all view and query functions for position management
 * @notice This contract provides read-only access to position data and system state
 * @custom:version 1.0.0
 * @custom:security-contact [email protected]
 */
// Payable surface is OZ UUPS `upgradeToAndCall` only; this module does not custody ETH (aderyn contract-locks-ether).
// aderyn-fp-next-line(contract-locks-ether)
contract PositionManagerViews is
    Initializable,
    UUPSUpgradeable,
    AccessControlEnumerableUpgradeable,
    PausableUpgradeable,
    ReentrancyGuardUpgradeable,
    IVersioned,
    IPositionManagerViews
{
    // =============================================================================
    // CONSTANTS & IMMUTABLES
    // =============================================================================

    bytes32 public constant ADMIN_ROLE = Roles.ADMIN_ROLE;
    /// @notice Deprecated as of v1.1.0 — no longer consulted by any function in this contract.
    ///         Retained on the ABI for backwards-compatibility with off-chain tooling that still reads the constant.
    ///         Admin functions are now gated by `msg.sender == adminModule` (direct address check); see `onlyAdminModule`.
    bytes32 public constant ADMIN_MODULE_ROLE = Roles.ADMIN_MODULE_ROLE;
    bytes32 public constant EMERGENCY_PAUSE_ROLE = Roles.EMERGENCY_PAUSE_ROLE;

    string public constant VERSION = "1.1.2";
    uint256 public constant BASIS_POINTS = 1e4;

    // ── Gas-griefing protection ─────────────────────────────────────────────────
    /// @notice Maximum number of positions returned / iterated in a single call to
    ///         getUserPositions().  Prevents unbounded external-call loops when a user
    ///         holds many positions.  Use getUserPositionsPaginated() for full lists.
    uint256 public constant MAX_POSITIONS_PER_QUERY = 50;

    /// @notice Approximate gas per position entry fetched via getPositionDetails()
    ///         (used by the gas-estimation view function).
    uint256 public constant GAS_PER_POSITION_QUERY = 1e4;

    /// @notice Approximate base gas for a getUserPositions-style operation.
    uint256 public constant GAS_BASE_POSITION_QUERY = 25_000;

    /// @dev Issue codes returned by validatePositionIntegrity (uint8[]).
    uint8 private constant INTEGRITY_ISSUE_POSITION_NOT_FOUND = 1;
    uint8 private constant INTEGRITY_ISSUE_PKP_MISMATCH = 2;
    /// @dev Max distinct issues collected in one validatePositionIntegrity pass (working buffer size).
    uint8 private constant INTEGRITY_ISSUES_BUFFER_CAPACITY = 10;
    uint8 private constant SINGLE_INTEGRITY_ISSUE_LEN = 1;
    // ────────────────────────────────────────────────────────────────────────────

    // =============================================================================
    // STATE VARIABLES
    // =============================================================================

    IPositionManagerCore public core;
    ILoanOperationsManager public loanOps;
    ICollateralManager public collateralManager;
    ILiquidationManager public liquidationManager;
    ITermManager public termManager;

    // Reference to main position manager for state access
    IPositionManager public positionManager;

    // Circuit breaker module for system limits and daily volume data
    ICircuitBreakerModule public circuitBreaker;

    /// @notice The AdminModule proxy authorised to call admin functions on this contract (v1.1.0+).
    address public adminModule;

    // Storage gap invariant: used_slots (8) + __gap (42) = 50.
    // v1.1.0: appended `adminModule` (1 slot) — decremented __gap by 1.
    // See contracts/scripts/shared/verify-gap-invariant.ts and CLAUDE.md "Storage Gap Invariant".
    // When adding a storage var, decrement __gap by the number of new slots — do not recompute.
    // aderyn-fp-next-line(unused-state-variable)
    uint256[42] private __gap;

    modifier onlyAdminModule() {
        if (msg.sender != adminModule) {
            revert PositionManagerErrors.NotAdminModule();
        }
        _;
    }

    function _grantRoleOrRevert(bytes32 role, address account) private {
        if (!_grantRole(role, account)) revert PositionManagerErrors.UnexpectedRoleGrantFailure();
    }

    // =============================================================================
    // INITIALIZER
    // =============================================================================

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

    function initialize(
        address _positionManager,
        address _core,
        address _loanOps,
        address _collateral,
        address _liquidation,
        address _termManager,
        address _admin,
        address _circuitBreaker,
        address _adminModule
    ) external initializer {
        __AccessControl_init();
        __AccessControlEnumerable_init();
        __Pausable_init();
        __ReentrancyGuard_init();
        __UUPSUpgradeable_init();

        if (_positionManager == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_core == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_loanOps == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_collateral == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_liquidation == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_termManager == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_admin == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_circuitBreaker == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_adminModule == address(0)) revert PositionManagerErrors.InvalidAddress();

        positionManager = IPositionManager(_positionManager);
        core = IPositionManagerCore(_core);
        loanOps = ILoanOperationsManager(_loanOps);
        collateralManager = ICollateralManager(_collateral);
        liquidationManager = ILiquidationManager(_liquidation);
        termManager = ITermManager(_termManager);
        circuitBreaker = ICircuitBreakerModule(_circuitBreaker);

        _grantRoleOrRevert(DEFAULT_ADMIN_ROLE, _admin);
        _grantRoleOrRevert(ADMIN_ROLE, _admin);
        // ADMIN_MODULE_ROLE is deprecated (v1.1.0+) but still granted for ABI compat with off-chain tooling.
        _grantRoleOrRevert(ADMIN_MODULE_ROLE, _adminModule);
        _grantRoleOrRevert(EMERGENCY_PAUSE_ROLE, _admin);

        adminModule = _adminModule;
        emit AdminModuleUpdated(address(0), _adminModule);
    }

    /// @notice v1.1.0 migration initialiser. Called once via upgradeToAndCall on existing v1.0.x proxies.
    function initializeV2(address _adminModule) external reinitializer(2) onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_adminModule == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (_adminModule.code.length == 0) revert PositionManagerErrors.NotContract();
        address old = adminModule;
        adminModule = _adminModule;
        emit AdminModuleUpdated(old, _adminModule);
    }

    /// @notice Rotate the AdminModule proxy. Gated by `onlyAdminModule`.
    function setAdminModule(address newAdminModule) external onlyAdminModule {
        if (newAdminModule == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (newAdminModule.code.length == 0) revert PositionManagerErrors.NotContract();
        address old = adminModule;
        adminModule = newAdminModule;
        emit AdminModuleUpdated(old, newAdminModule);
    }

    event AdminModuleUpdated(address indexed oldAdminModule, address indexed newAdminModule);
    event ContractPaused(address indexed caller, uint256 timestamp);
    event ContractUnpaused(address indexed caller, uint256 timestamp);
    event ContractUpgraded(
        address indexed oldImplementation,
        address indexed newImplementation,
        string version,
        uint256 timestamp
    );

    event PositionManagerReferenceUpdated(
        address indexed oldPositionManager,
        address indexed newPositionManager,
        address indexed caller
    );
    event CircuitBreakerReferenceUpdated(
        address indexed oldCircuitBreaker,
        address indexed newCircuitBreaker,
        address indexed caller
    );

    function pause() external onlyRole(EMERGENCY_PAUSE_ROLE) {
        _pause();
        emit ContractPaused(msg.sender, block.timestamp);
    }

    function unpause() external onlyAdminModule {
        _unpause();
        emit ContractUnpaused(msg.sender, block.timestamp);
    }

    /// @inheritdoc IPositionManagerViews
    function getProtocolPauseStatus()
        external
        view
        returns (IPositionManager.ProtocolPauseStatus memory s)
    {
        s.positionManagerPaused             = _safePaused(address(positionManager));
        s.positionManagerLiquidationsPaused = _safeLiquidationPaused(address(positionManager));
        s.positionManagerCorePaused         = _safePaused(address(core));
        s.loanOperationsPaused              = _safePaused(address(loanOps));
        s.collateralManagerPaused           = _safePaused(address(collateralManager));
        s.liquidationManagerPaused          = _safePaused(address(liquidationManager));
        s.circuitBreakerPaused              = _safePaused(address(circuitBreaker));
        s.termManagerPaused                 = _safePaused(address(termManager));
        s.adminModulePaused                 = _safePaused(_safeAdminModule());
        s.btcSpendAuthorizerPaused          = _safePaused(_safeBtcSpendAuthorizer());
        s.litActionValidatorPaused          = _safePaused(_safeLitActionValidator());
        s.ucdControllerPaused               = _safePaused(_safeUcdController());
        s.ucdTokenPaused                    = _safePaused(_safeUcdToken());
        s.simplePsmPaused                   = _safePaused(_safeSimplePsm());
    }

    /// @dev Aggregate pause view only: if `target` is not pausable or the call reverts, returns false (soft-fail; no state change).
    function _safePaused(address target) private view returns (bool) {
        if (target == address(0)) return false;
        try IPausableView(target).paused() returns (bool p) {
            return p;
        } catch {
            return false;
        }
    }

    function _safeLiquidationPaused(address target) private view returns (bool) {
        if (target == address(0)) return false;
        try IPositionManager(target).liquidationPaused() returns (bool p) { return p; }
        catch { return false; }
    }

    function _safeAdminModule() private view returns (address) {
        try positionManager.admin() returns (IAdminModule a) { return address(a); }
        catch { return address(0); }
    }

    function _safeBtcSpendAuthorizer() private view returns (address) {
        try loanOps.btcSpendAuthorizer() returns (IBTCSpendAuthorizer a) { return address(a); }
        catch { return address(0); }
    }

    function _safeLitActionValidator() private view returns (address) {
        try core.litActionValidator() returns (ILITActionValidator a) { return address(a); }
        catch { return address(0); }
    }

    function _safeUcdController() private view returns (address) {
        try loanOps.getUcdController() returns (address a) { return a; }
        catch { return address(0); }
    }

    function _safeUcdToken() private view returns (address) {
        try loanOps.ucdToken() returns (address a) { return a; }
        catch { return address(0); }
    }

    function _safeSimplePsm() private view returns (address) {
        try positionManager.simplePsm() returns (address a) { return a; }
        catch { return address(0); }
    }

    /// @inheritdoc IPositionManagerViews
    function validateExtensionMetrics(
        IPositionManagerCore.Position memory position,
        uint256 selectedTerm,
        uint256 btcPrice,
        uint256 availableBTCBalance,
        uint256 proRataRenewalFee
    )
        external
        view
        returns (
            uint256 extensionFee,
            uint256 newTotalDebt,
            uint256 newCollateralRatio,
            uint256 newTotalTerm
        )
    {
        // slither-disable-next-line unused-return
        (, uint88 extensionFeeBps) = termManager.getTermFees(selectedTerm);
        uint256 maxRenewalFee = (position.ucdDebt * extensionFeeBps) / BASIS_POINTS;
        if (proRataRenewalFee > maxRenewalFee) {
            revert PositionManagerErrors.FeeTooHigh(proRataRenewalFee, maxRenewalFee);
        }

        // H-4: the pro-rata credit is for unused origination fees paid this term, so it can
        // never exceed what the borrower actually paid. Floor the renewal fee at
        // (fresh extension fee - origination fees paid this term); a buggy or compromised
        // Lit Action cannot drive the fee below this without the borrower having self-funded
        // the credit. A legitimately fully-credited extension still settles at the floor.
        uint256 creditCap = core.originationFeesPaidThisTerm(position.positionId);
        uint256 minRenewalFee = maxRenewalFee > creditCap
            ? maxRenewalFee - creditCap
            : 0;
        if (proRataRenewalFee < minRenewalFee) {
            revert PositionManagerErrors.FeeTooLow(proRataRenewalFee, minRenewalFee);
        }

        (
            extensionFee,
            newTotalDebt,
            newCollateralRatio,
            newTotalTerm
        ) = ExtensionValidationHelper.calculateExtensionMetrics(
            position,
            selectedTerm,
            btcPrice,
            availableBTCBalance,
            proRataRenewalFee,
            loanOps
        );
    }

    /// @inheritdoc IPositionManagerViews
    function validateExtensionTimingView(
        IPositionManagerCore.Position memory position,
        uint256 selectedTerm,
        bool restrictionDisabled
    ) external view {
        ExtensionValidationHelper.validateExtensionTiming(
            position,
            selectedTerm,
            restrictionDisabled
        );
    }

    function setPositionManager(address _positionManager) external onlyAdminModule whenNotPaused {
        if (_positionManager == address(0)) revert PositionManagerErrors.InvalidAddress();
        address old = address(positionManager);
        positionManager = IPositionManager(_positionManager);
        emit PositionManagerReferenceUpdated(old, _positionManager, msg.sender);
    }

    function setCircuitBreakerModule(address _circuitBreaker) external onlyAdminModule whenNotPaused {
        if (_circuitBreaker == address(0)) revert PositionManagerErrors.InvalidAddress();
        address old = address(circuitBreaker);
        circuitBreaker = ICircuitBreakerModule(_circuitBreaker);
        emit CircuitBreakerReferenceUpdated(old, _circuitBreaker, msg.sender);
    }

    /// @notice Update the LoanOperationsManager reference used by view aggregators.
    /// @dev Needed when LoanOps is fresh-redeployed — without this, `getSystemStatus()`
    ///      reads from the stale LoanOps and returns garbage for its view getters.
    function setLoanOps(address _loanOps) external onlyAdminModule whenNotPaused {
        if (_loanOps == address(0)) revert PositionManagerErrors.InvalidAddress();
        address old = address(loanOps);
        loanOps = ILoanOperationsManager(_loanOps);
        emit LoanOpsReferenceUpdated(old, _loanOps, msg.sender);
    }

    event LoanOpsReferenceUpdated(address indexed oldLoanOps, address indexed newLoanOps, address indexed caller);

    // =============================================================================
    // VIEW FUNCTIONS - POSITION QUERIES
    // =============================================================================

    /**
     * @dev Calculate current collateral ratio for a position
     * @param positionId Position to calculate for
     * @return ratio Collateral ratio in basis points (10000 = 100%)
     * @return isHealthy Whether position meets minimum collateral requirements
     */
    function calculateCollateralRatio(
        bytes32 positionId,
        uint256 currentBtcPrice,
        uint256 btcAmount
    ) external view returns (uint256 ratio, bool isHealthy) {
        IPositionManagerCore.Position memory position = core.getPositionDetails(
            positionId
        );
        if (position.borrower == address(0)) revert PositionManagerErrors.PositionNotFound();
        
        // Get outstanding debt from core position
        uint256 outstandingDebt = position.ucdDebt;
        
        if (outstandingDebt == 0) {
            return (0, true); // No debt, position is healthy
        }

        // Calculate ratio: (collateral value / outstanding debt) * 10000
        uint256 collateralValue = SafeCalculations.safeCollateralValue(
            btcAmount,
            currentBtcPrice
        );
        ratio = SafeCalculations.safeCollateralRatio(collateralValue, outstandingDebt);
        
        // Check if ratio meets liquidation threshold
        uint256 liquidationThresholdBps = loanOps.liquidationThreshold();
        isHealthy = ratio >= liquidationThresholdBps;
    }

    /**
     * @dev Get comprehensive position details by position ID
     * @param positionId Position to query
     * @return position Complete position data structure
     */
    function getPositionById(
        bytes32 positionId
    ) external view returns (IPositionManagerCore.Position memory) {
        IPositionManagerCore.Position memory position = core.getPositionDetails(
            positionId
        );
        if (position.borrower == address(0)) revert PositionManagerErrors.PositionNotFound();
        return position;
    }

    /// @inheritdoc IPositionManagerViews
    function getPositionByIdAsManager(
        bytes32 positionId
    ) external view returns (IPositionManager.Position memory) {
        IPositionManagerCore.Position memory c = core.getPositionDetails(positionId);
        return
            IPositionManager.Position({
                positionId: c.positionId,
                pkpId: c.pkpId,
                ucdDebt: c.ucdDebt,
                borrower: c.borrower,
                createdAt: c.createdAt,
                lastUpdated: c.lastUpdated,
                selectedTerm: c.selectedTerm,
                expiryAt: c.expiryAt,
                status: c.status
            });
    }

    /**
     * @dev Get position ID associated with a PKP
     * @param pkpId PKP identifier
     * @return bytes32 Position ID (zero if no position found)
     */
    function getPositionByPKP(bytes32 pkpId) external view returns (bytes32) {
        return core.getPositionByPKP(pkpId);
    }

    /**
     * @dev Get all positions for a user
     * @param user User address
     * @return positionIds Array of position IDs owned by user
     * @return activeCount Number of currently active positions
     */
    function getUserPositions(
        address user
    ) external view returns (bytes32[] memory positionIds, uint256 activeCount) {
        positionIds = core.getUserPositions(user);

        // Gas-griefing protection: cap the number of external calls in the loop.
        // If the user owns more than MAX_POSITIONS_PER_QUERY positions, only the
        // first MAX_POSITIONS_PER_QUERY are inspected here.  Call
        // getUserPositionsPaginated() to iterate the full list safely.
        uint256 iterLimit = positionIds.length > MAX_POSITIONS_PER_QUERY
            ? MAX_POSITIONS_PER_QUERY
            : positionIds.length;

        for (uint256 i = 0; i < iterLimit; i++) {
            IPositionManagerCore.Position memory position = core.getPositionDetails(
                positionIds[i]
            );
            LoanStatusLib.LoanStatus status = position.status;
            if (status == LoanStatusLib.LoanStatus.ACTIVE ||
                status == LoanStatusLib.LoanStatus.PENDING_MINT ||
                status == LoanStatusLib.LoanStatus.PENDING_DEPOSIT) {
                activeCount++;
            }
        }
    }

    /**
     * @notice Paginated position lookup for a user.
     * @dev Each call returns at most MAX_POSITIONS_PER_QUERY position IDs with their
     *     details, keeping the per-call gas cost bounded regardless of how many
     *     positions the user holds.  Iterate by incrementing offset by the returned
     *     pageSize until offset >= total.
     * @param user    User address to query.
     * @param offset  Index of the first position to return (0-based).
     * @param limit   Maximum positions to return; silently capped at MAX_POSITIONS_PER_QUERY.
     * @return page       Slice of position IDs.
     * @return activeCount Number of active positions in the returned slice.
     * @return total      Total number of positions owned by user (for paging math).
     */
    function getUserPositionsPaginated(
        address user,
        uint256 offset,
        uint256 limit
    ) external view returns (bytes32[] memory page, uint256 activeCount, uint256 total) {
        bytes32[] memory allIds = core.getUserPositions(user);
        total = allIds.length;

        if (offset >= total || limit == 0) {
            return (new bytes32[](0), 0, total);
        }

        // Cap per-call work to avoid runaway gas cost.
        if (limit > MAX_POSITIONS_PER_QUERY) limit = MAX_POSITIONS_PER_QUERY;

        uint256 end = offset + limit;
        if (end > total) end = total;
        uint256 pageSize = end - offset;

        page = new bytes32[](pageSize);
        for (uint256 i = 0; i < pageSize; i++) {
            bytes32 pid = allIds[offset + i];
            page[i] = pid;
            IPositionManagerCore.Position memory position = core.getPositionDetails(pid);
            LoanStatusLib.LoanStatus status = position.status;
            if (status == LoanStatusLib.LoanStatus.ACTIVE ||
                status == LoanStatusLib.LoanStatus.PENDING_MINT ||
                status == LoanStatusLib.LoanStatus.PENDING_DEPOSIT) {
                activeCount++;
            }
        }
    }

    /**
     * @notice Estimate gas required for a getUserPositions call for a given user.
     * @dev Returns a conservative approximation based on current position count.
     *      The estimate is capped at MAX_POSITIONS_PER_QUERY entries because
     *      getUserPositions() itself only iterates that many.
     * @param user Address to estimate for.
     * @return estimatedGas Approximate gas units.
     * @return positionCount Total positions held (needed for full pagination).
     */
    function estimateGetUserPositionsGas(
        address user
    ) external view returns (uint256 estimatedGas, uint256 positionCount) {
        positionCount = core.getUserPositions(user).length;
        uint256 iterCount = positionCount > MAX_POSITIONS_PER_QUERY
            ? MAX_POSITIONS_PER_QUERY
            : positionCount;
        estimatedGas = GAS_BASE_POSITION_QUERY + iterCount * GAS_PER_POSITION_QUERY;
    }

    // =============================================================================
    // VIEW FUNCTIONS - TERM MANAGEMENT
    // =============================================================================

    /**
     * @dev Get fees for a specific term length
     * @param termMonths Term length in months
     * @return originationFee Fee charged when loan is created (basis points)
     * @return extensionFee Fee charged when loan is extended (basis points)
     */
    function getTermFees(uint256 termMonths) external view returns (uint88 originationFee, uint88 extensionFee) {
        // slither-disable-next-line unused-return
        return termManager.getTermFees(termMonths);
    }

    /**
     * @dev Check if a term length is valid
     * @param termMonths Term length to validate
     * @return bool True if term is supported
     */
    function isValidTerm(uint256 termMonths) external view returns (bool) {
        return termManager.isValidTerm(termMonths);
    }

    /**
     * @dev Get all valid terms with their associated fees
     * @return terms Array of valid term lengths (months)
     * @return originationFees Array of origination fees (basis points)
     * @return extensionFees Array of extension fees (basis points)
     */
    function getValidTermsWithFees() external view returns (
        uint256[] memory terms,
        uint88[] memory originationFees,
        uint88[] memory extensionFees
    ) {
        // slither-disable-next-line unused-return
        return termManager.getValidTermsWithFees();
    }

    // =============================================================================
    // VIEW FUNCTIONS - SYSTEM STATE
    // =============================================================================

    /**
     * @dev Get current system limits from the circuit breaker module
     * @return maxSingleLoanValue Maximum UCD per individual loan
     * @return dailyVolumeLimit Maximum daily UCD volume across all operations
     */
    function getSystemLimits() external view returns (
        uint256 maxSingleLoanValue,
        uint256 dailyVolumeLimit
    ) {
        if (address(circuitBreaker) == address(0)) return (0, 0);
        maxSingleLoanValue = circuitBreaker.maxSingleLoanValue();
        dailyVolumeLimit   = circuitBreaker.dailyVolumeLimit();
    }

    /**
     * @dev Get daily volume statistics from the circuit breaker module
     * @param day Unix day number (block.timestamp / 1 days) to query
     * @return ucdVolume Total UCD volume minted/burned for the day
     * @return percentOfLimit Volume as a percentage of the daily limit (basis points, 10000 = 100%)
     */
    function getDailyVolume(uint256 day) external view returns (
        uint256 ucdVolume,
        uint256 percentOfLimit
    ) {
        if (address(circuitBreaker) == address(0)) return (0, 0);
        ucdVolume = circuitBreaker.dailyUcdVolume(day);
        uint256 limit = circuitBreaker.dailyVolumeLimit();
        if (limit > 0) {
            percentOfLimit = (ucdVolume * BASIS_POINTS) / limit;
        }
    }

    /**
     * @dev Get circuit breaker status from the circuit breaker module
     * @return active Whether circuit breaker is currently triggered
     * @return activatedAt Timestamp when circuit breaker was last activated (0 if never)
     * @return reason Reserved for future use; always 0 in current implementation
     */
    function getCircuitBreakerStatus() external view returns (
        bool active,
        uint256 activatedAt,
        uint256 reason
    ) {
        if (address(circuitBreaker) == address(0)) return (false, 0, 0);
        active      = circuitBreaker.circuitBreakerActive();
        activatedAt = circuitBreaker.circuitBreakerActivatedAt();
        reason      = 0; // ICircuitBreakerModule does not expose a reason code
    }

    /**
     * @dev Aggregate system health check for dashboards and monitoring.
     *      Pause states are intentionally excluded — use `getProtocolPauseStatus()` for those.
     *      All cross-contract calls use soft-fail semantics: zero values are returned for
     *      unset modules or calls that revert (e.g. stale proxy, missing function selector).
     */
    function getSystemStatus() external view returns (IPositionManager.SystemStatus memory s) {
        // Assign module wiring flags first
        s.coreSet           = address(core) != address(0);
        s.loanOpsSet        = address(loanOps) != address(0);
        s.collateralSet     = address(collateralManager) != address(0);
        s.liquidationSet    = address(liquidationManager) != address(0);
        s.termManagerSet    = address(termManager) != address(0);
        s.circuitBreakerSet = address(circuitBreaker) != address(0);

        // Fetch core metrics
        if (s.coreSet) {
            try core.getTotalPositions() returns (uint256 n) { s.totalPositions = n; } catch {}
        }

        // Fetch loan operations constraints
        if (s.loanOpsSet) {
            try loanOps.liquidationThreshold()  returns (uint256 v) { s.liquidationThreshold  = v; } catch {}
            try loanOps.minimumLoanValueUcd()   returns (uint256 v) { s.minimumLoanValueUcd   = v; } catch {}
            try loanOps.maximumLoanValueUcd()   returns (uint256 v) { s.maximumLoanValueUcd   = v; } catch {}
            try loanOps.minBtcPriceBound()      returns (uint256 v) { s.minBtcPriceBound      = v; } catch {}
            try loanOps.maxBtcPriceBound()      returns (uint256 v) { s.maxBtcPriceBound      = v; } catch {}

            // Fetch UCD supply metrics
            address ucdCtrl = _safeUcdController();
            if (ucdCtrl != address(0)) {
                IUCDController ctrl = IUCDController(ucdCtrl);
                try ctrl.getCurrentSupply()  returns (uint256 v) { s.ucdTotalSupply   = v; } catch {}
                try ctrl.maxSupply()         returns (uint256 v) { s.ucdMaxSupply     = v; } catch {}
                try ctrl.dailyMinted()       returns (uint256 v) { s.ucdDailyMinted   = v; } catch {}
                try ctrl.dailyBurned()       returns (uint256 v) { s.ucdDailyBurned   = v; } catch {}
                try ctrl.dailyMintLimit()    returns (uint256 v) { s.ucdDailyMintLimit = v; } catch {}
                try ctrl.dailyBurnLimit()    returns (uint256 v) { s.ucdDailyBurnLimit = v; } catch {}
            }
        }

        // Fetch circuit breaker metrics
        if (s.circuitBreakerSet) {
            try circuitBreaker.circuitBreakerActivatedAt() returns (uint256 v) { s.circuitBreakerActivatedAt = v; } catch {}
            try circuitBreaker.dailyUcdVolume(block.timestamp / 1 days) returns (uint256 v) { s.cbDailyVolumeToday = v; } catch {}
            try circuitBreaker.dailyVolumeLimit()        returns (uint256 v) { s.cbDailyVolumeLimit      = v; } catch {}
            try circuitBreaker.maxSingleLoanValue()      returns (uint256 v) { s.cbMaxSingleLoanValue    = v; } catch {}
        }

        // Fetch liquidation stats
        if (s.liquidationSet) {
            try liquidationManager.getGlobalLiquidationStats() returns (uint256 count, uint256 vol) {
                s.totalLiquidations      = count;
                s.totalLiquidationVolume = vol;
            } catch {}
        }

        // Assign boolean flags last
        s.isPaused             = paused();
        if (s.circuitBreakerSet) {
            try circuitBreaker.circuitBreakerActive() returns (bool b) { s.circuitBreakerActive = b; } catch {}
        }
    }

    // =============================================================================
    // VIEW FUNCTIONS - VALIDATION
    // =============================================================================

    /**
     * @dev Validate position integrity
     * @param positionId Position to validate
     * @return valid True if position passes all integrity checks
     * @return issues Array of issue codes if validation fails
     */
    function validatePositionIntegrity(bytes32 positionId) external view returns (
        bool valid,
        uint8[] memory issues
    ) {
        IPositionManagerCore.Position memory position = core.getPositionDetails(
            positionId
        );
        if (position.borrower == address(0)) {
            uint8[] memory singleIssue = new uint8[](SINGLE_INTEGRITY_ISSUE_LEN);
            singleIssue[0] = INTEGRITY_ISSUE_POSITION_NOT_FOUND;
            return (false, singleIssue);
        }

        // Check various integrity conditions
        uint8[] memory potentialIssues = new uint8[](INTEGRITY_ISSUES_BUFFER_CAPACITY);
        uint256 issueCount = 0;

        // Check PKP association
        bytes32 associatedPosition = core.getPositionByPKP(position.pkpId);
        if (associatedPosition != positionId) {
            potentialIssues[issueCount++] = INTEGRITY_ISSUE_PKP_MISMATCH;
        }

        // Check status consistency (basic check only)
        // Use core.getPositionById(positionId).status instead of getPositionStatus

        // Collateral consistency check removed - tracking moved to mint time

        // Return results
        valid = (issueCount == 0);
        issues = new uint8[](issueCount);
        for (uint256 i = 0; i < issueCount; i++) {
            issues[i] = potentialIssues[i];
        }
    }

    /**
     * @dev Get total number of positions in the system
     * @return uint256 Total position count
     */
    function getTotalPositions() external view returns (uint256) {
        return core.getTotalPositions();
    }

    /**
     * @dev Get position IDs with pagination support
     * @param offset Starting index for pagination
     * @param limit Maximum number of positions to return
     * @return bytes32[] Array of position IDs
     */
    function getPositionIds(uint256 offset, uint256 limit) external view returns (bytes32[] memory) {
        return core.getPositionIds(offset, limit);
    }

    /// @inheritdoc IPositionManagerViews
    function getBackingVaults(
        uint256 offset,
        uint256 limit
    ) external view returns (BackingVault[] memory vaults, uint256 nextOffset, uint256 total) {
        // A zero limit would return nextOffset == offset and loop a paging client forever.
        if (limit == 0) revert PositionManagerErrors.InvalidAmount();
        if (limit > MAX_POSITIONS_PER_QUERY) limit = MAX_POSITIONS_PER_QUERY;

        total = core.getTotalPositions();
        bytes32[] memory ids = core.getPositionIds(offset, limit);
        uint256 scanned = ids.length;
        nextOffset = offset + scanned;

        vaults = new BackingVault[](scanned);
        uint256 count = 0;
        for (uint256 i = 0; i < scanned; i++) {
            IPositionManagerCore.Position memory position = core.getPositionDetails(ids[i]);
            if (position.ucdDebt != 0) {
                vaults[count++] = BackingVault({
                    positionId: position.positionId,
                    vaultAddress: position.vaultAddress,
                    ucdDebt: position.ucdDebt,
                    status: uint8(position.status)
                });
            }
        }
        // Trim to the debt-bearing entries (shrinks the length word only).
        assembly ("memory-safe") {
            mstore(vaults, count)
        }
    }

    /**
     * @dev Get contract version
     * @return string Contract version
     */
    function getVersion() external pure returns (string memory) {
        return VERSION;
    }

    // =============================================================================
    // DIAGNOSTICS
    // =============================================================================

    /// @dev diagnoseMintUCD: assumed BTC/USD quote lower bound ($10k at 8-decimal feed scale, i.e. 1e12).
    uint256 private constant DIAGNOSTIC_BTC_PRICE_MIN = 1e12;
    /// @dev diagnoseMintUCD: assumed BTC/USD quote upper bound ($1M at 8-decimal feed scale, i.e. 1e14).
    uint256 private constant DIAGNOSTIC_BTC_PRICE_MAX = 1e14;
    /// @dev Base-10 radix for decimal string encoding helpers.
    uint256 private constant DECIMAL_BASE = 10;
    /// @dev ASCII code unit for digit '0' (used in hex and decimal string helpers).
    uint8 private constant ASCII_CODE_ZERO = 48;
    /// @dev Maps hex nibble 10..15 to lowercase 'a'..'f' via `ASCII_HEX_LETTER_BASE + nibble`.
    uint8 private constant ASCII_HEX_LETTER_BASE = 87;

    uint256 private constant MAX_MINT_TIMESTAMP_SKEW = 5 minutes;

    /**
     * @dev Diagnose potential mintUCD failure reasons
     * @notice This function helps identify why a mint transaction might revert
     */
    function diagnoseMintUCD(
        bytes32 positionId,
        uint256 mintAmount,
        uint256 mintFee,
        uint256 newDebt,
        uint256 newCollateral,
        uint256 btcPrice,
        bytes32 authorizedSpendsHash,
        bytes32 ucdDebtHash,
        bytes32 contractHash,
        uint256 quantumTimestamp,
        bytes calldata mintValidatorSignature
    ) external view returns (string memory) {
        // Test 1: Basic parameter validation (non-zero)
        if (positionId == bytes32(0)) return "Validation 1: positionId is zero";
        if (mintAmount == 0) return "Validation 1: mintAmount is zero";
        if (newDebt == 0) return "Validation 1: newDebt is zero";
        if (btcPrice == 0) return "Validation 1: btcPrice is zero";
        if (contractHash == bytes32(0)) return "Validation 1: contractHash is zero";
        if (mintValidatorSignature.length == 0) return "Validation 1: signature empty";

        // Test 2: Protocol Limits
        // We can't access protocol config easily here without importing struct, 
        // but we can skip this check or approximate it if needed.
        // Or fetch from loanOps if possible.
        // For diagnostics, skipping strict protocol limit check is okay if complex.
        
        // Test 3: Price bounds
        if (btcPrice < DIAGNOSTIC_BTC_PRICE_MIN) {
            return "Validation 3: btcPrice < DIAGNOSTIC_BTC_PRICE_MIN";
        }
        if (btcPrice > DIAGNOSTIC_BTC_PRICE_MAX) {
            return "Validation 3: btcPrice > DIAGNOSTIC_BTC_PRICE_MAX";
        }

        // Test 4: Quantum timestamp
        if (quantumTimestamp == 0) {
            return "Validation 4: quantumTimestamp == 0";
        }

        // Test 6: Quantum timestamp window
        if (quantumTimestamp + MAX_MINT_TIMESTAMP_SKEW < block.timestamp) {
            return "Validation 6: quantumTimestamp too old (quantumTimestamp + MAX_SKEW < block.timestamp)";
        }
        if (quantumTimestamp > block.timestamp + MAX_MINT_TIMESTAMP_SKEW) {
            return "Validation 6: quantumTimestamp too far in future (quantumTimestamp > block.timestamp + MAX_SKEW)";
        }

        // Test 7: Contract hash
        bytes32 expectedContractHash = _contractBundleHash();
        if (contractHash != expectedContractHash) {
            return string(
                bytes.concat(
                    bytes("Validation 7: Contract hash mismatch. Expected: "),
                    bytes(_bytes32ToHexString(expectedContractHash)),
                    bytes(", Got: "),
                    bytes(_bytes32ToHexString(contractHash))
                )
            );
        }

        // Test 8: Position existence and debt hash
        IPositionManagerCore.Position memory corePosition = core
            .getPositionDetails(positionId);
        if (corePosition.positionId == bytes32(0)) {
            return "Validation 8: Position not found (positionId == bytes32(0))";
        }
        bytes32 expectedDebtHash = keccak256(abi.encode(corePosition.ucdDebt));
        if (ucdDebtHash != expectedDebtHash) {
            return string(
                bytes.concat(
                    bytes("Validation 8: Debt hash mismatch. Expected: "),
                    bytes(_bytes32ToHexString(expectedDebtHash)),
                    bytes(", Got: "),
                    bytes(_bytes32ToHexString(ucdDebtHash)),
                    bytes(", Current debt: "),
                    bytes(_uint256ToString(corePosition.ucdDebt))
                )
            );
        }

        // Test 9: Signature verification — same digest as `mintUCD` / `LoanOperationsManager.eip712DigestMintUcd`
        bytes32 messageHash = loanOps.eip712DigestMintUcd(
            positionId,
            mintAmount,
            mintFee,
            newDebt,
            newCollateral,
            btcPrice,
            authorizedSpendsHash,
            ucdDebtHash,
            contractHash,
            quantumTimestamp,
            corePosition.borrower
        );
        
        // Call verifyAuthorization on the registry wired in PositionManager.
        IOperationAuthorizationRegistry registry = positionManager.authorizationRegistry();
        try registry.verifyAuthorization(
            // We need the selector of mintUCD. We can hardcode it or calculate it.
            // mintUCD selector: bytes4(keccak256("mintUCD(bytes32,uint256,uint256,uint256,uint256,uint256,bytes32,bytes32,bytes32,uint256,bytes)"))
            // Or use interface selector if available.
            // Let's use the explicit selector calculation to be safe and match PositionManager.
            bytes4(keccak256("mintUCD(bytes32,uint256,uint256,uint256,uint256,uint256,bytes32,bytes32,bytes32,uint256,bytes)")),
            messageHash,
            mintValidatorSignature
        ) {} catch {
            return "Validation 9: verifyAuthorization call failed";
        }

        return "All validations passed";
    }

    /**
     * @dev Calculate contract bundle hash for validation
     */
    function _contractBundleHash() private view returns (bytes32) {
        // We need ucdController address. PositionManager gets it from loanOps.
        // loanOps is ILoanOperationsManager. Does it have getUcdController()?
        // It's likely in ILoanOperationsManager.
        // If not, we can try to get it.
        // Assuming ILoanOperationsManager has getUcdController() or similar.
        // Actually, `core/PositionManager.sol` uses `ucdController` state variable which is set via `loanOps.getUcdController()`.
        // Let's assume we can call loanOps.getUcdController().
        // If interface doesn't have it, we might need low-level call.
        // Or we can assume it's set in this contract? No, Views doesn't have ucdController state.
        
        // Low-level call to get ucdController from loanOps
        address ucdControllerAddress = address(0);
        try loanOps.getUcdController() returns (address addr) {
            ucdControllerAddress = addr;
        } catch {
            // Fallback or error
            return bytes32(0); 
        }

        return keccak256(abi.encode(
            address(positionManager), // PositionManager address
            address(loanOps),
            address(termManager),
            ucdControllerAddress
        ));
    }

    /**
     * @dev Helper function to convert bytes32 to hex string
     */
    function _bytes32ToHexString(bytes32 value) private pure returns (string memory) {
        bytes memory buffer = new bytes(66);
        buffer[0] = '0';
        buffer[1] = 'x';
        for (uint256 i = 0; i < 32; i++) {
            uint8 byteValue = uint8(value[i]);
            uint8 highNibble = byteValue >> 4;
            uint8 lowNibble = byteValue & 0x0f;
            buffer[2 + i * 2] = _nibbleToChar(highNibble);
            buffer[3 + i * 2] = _nibbleToChar(lowNibble);
        }
        return string(buffer);
    }

    /**
     * @dev Helper function to convert nibble to hex character
     */
    function _nibbleToChar(uint8 nibble) private pure returns (bytes1) {
        if (nibble < DECIMAL_BASE) {
            return bytes1(uint8(ASCII_CODE_ZERO + nibble)); // '0'-'9'
        } else {
            return bytes1(uint8(ASCII_HEX_LETTER_BASE + nibble)); // 'a'-'f'
        }
    }

    /**
     * @dev Helper function to convert uint256 to string
     */
    function _uint256ToString(uint256 value) private pure returns (string memory) {
        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= DECIMAL_BASE;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(ASCII_CODE_ZERO + uint256(value % DECIMAL_BASE)));
            value /= DECIMAL_BASE;
        }
        return string(buffer);
    }

    // =============================================================================
    // INTERNAL FUNCTIONS
    // =============================================================================

    /**
     * @dev UUPS upgrade authorization. H-3 (2026-05-17): migrated from
     *      `onlyRole(DEFAULT_ADMIN_ROLE)` → `onlyAdminModule`. PositionManagerViews exposes the
     *      protocol's view-layer source of truth (extension fee/collateral checks for H-4,
     *      renewal-restriction H-5 check, pause status read by LIT Actions, position lookups
     *      consumed by mint/repay/withdraw/liquidate flows). A malicious upgrade can forge any
     *      of those reads, so the upgrade gate must route through the AdminModule 24h timelock
     *      like every other UUPS proxy in the protocol.
     */
    function _authorizeUpgrade(address newImplementation)
        internal
        override
        onlyAdminModule
    {
        if (newImplementation == address(0)) revert PositionManagerErrors.InvalidAddress();
        if (newImplementation.code.length == 0) revert PositionManagerErrors.NotContract();
        emit ContractUpgraded(
            ERC1967Utils.getImplementation(),
            newImplementation,
            VERSION,
            block.timestamp
        );
    }
}

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../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 IERC165
    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/extensions/AccessControlEnumerableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {IAccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol";
import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerable, AccessControlUpgradeable {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControlEnumerable
    struct AccessControlEnumerableStorage {
        mapping(bytes32 role => EnumerableSet.AddressSet) _roleMembers;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlEnumerable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessControlEnumerableStorageLocation = 0xc1f6fe24621ce81ec5827caf0253cadb74709b061630e6b55e82371705932000;

    function _getAccessControlEnumerableStorage() private pure returns (AccessControlEnumerableStorage storage $) {
        assembly {
            $.slot := AccessControlEnumerableStorageLocation
        }
    }

    function __AccessControlEnumerable_init() internal onlyInitializing {
    }

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

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        return $._roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        return $._roleMembers[role].length();
    }

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

    /**
     * @dev Overload {AccessControl-_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        bool granted = super._grantRole(role, account);
        if (granted) {
            $._roleMembers[role].add(account);
        }
        return granted;
    }

    /**
     * @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        AccessControlEnumerableStorage storage $ = _getAccessControlEnumerableStorage();
        bool revoked = super._revokeRole(role, account);
        if (revoked) {
            $._roleMembers[role].remove(account);
        }
        return revoked;
    }
}

@openzeppelin/contracts-upgradeable/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-upgradeable/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.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.
 */
abstract contract UUPSUpgradeable is Initializable, 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();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @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 virtual 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-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 "../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/PausableUpgradeable.sol

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

pragma solidity ^0.8.20;

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

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

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

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

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

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

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

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

    function __Pausable_init() internal onlyInitializing {
    }

    function __Pausable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

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

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

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

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

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

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.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].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // 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;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

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

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

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

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

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

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

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

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

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

@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 "../../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/access/extensions/IAccessControlEnumerable.sol

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

pragma solidity >=0.8.4;

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

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

@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/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/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.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://eth.wiki/json-rpc/API#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/utils/Address.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/Arrays.sol

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

pragma solidity ^0.8.20;

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 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, of 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, of 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, of 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, of 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, of 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/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/SlotDerivation.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 bytes32;
 *
 *     // 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.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

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

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

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

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

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

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

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

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

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

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

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

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

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

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

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

                // Divide [high low] by twos.
                low := div(low, twos)

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

            // Shift in bits from high into low.
            low |= high * twos;

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

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

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

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

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

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

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

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/structs/EnumerableSet.sol

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

pragma solidity ^0.8.20;

import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
     * using it may render the function uncallable if the set grows to the point where clearing it consumes too much
     * gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

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

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

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

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

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

            uint256 len = end - start;
            bytes32[] memory result = new bytes32[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

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

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

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

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

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

        return result;
    }

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

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

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

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

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

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

        return result;
    }

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

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

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

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

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

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

        return result;
    }

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

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

        return result;
    }

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(StringSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(StringSet storage set, string memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

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

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

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

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

            uint256 len = end - start;
            string[] memory result = new string[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(BytesSet storage set) internal {
        uint256 len = length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
        return set._positions[value] != 0;
    }

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

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

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

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

            uint256 len = end - start;
            bytes[] memory result = new bytes[](len);
            for (uint256 i = 0; i < len; ++i) {
                result[i] = Arrays.unsafeAccess(set._values, start + i).value;
            }
            return result;
        }
    }
}

src/interfaces/IAdminModule.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title IAdminModule
 * @dev Interface for admin functionality
 */
interface IAdminModule {
    // Module management
    function updateModules(
        bytes32 proposalHash,
        address _core,
        address _loanOps,
        address _collateral,
        address _liquidation,
        address _termManager,
        address _circuitBreaker
    ) external;
    
    // Upgrade functions
    function validateUpgrade(address newImplementation) external view returns (bool);
    function setUpgradeValidator(address _upgradeValidator) external;
    
    // Emergency functions
    function pause() external;
    function unpause() external;
    function pauseAllProtocol() external;
    function pauseAllUCD() external;

    // Pause address configuration
    function setPositionManager(address _positionManager) external;
    function setBTCSpendAuthorizer(address _btcSpendAuthorizer) external;
    function setSimplePSMV2(address _simplePSMV2) external;
    function setUCDController(address _ucdController) external;
    function setUCDToken(address _ucdToken) external;

    // View functions
    function VERSION() external view returns (string memory);
    
    // Events
    event ModulesUpdated(
        address indexed oldCore,
        address indexed newCore,
        address oldLoanOps,
        address newLoanOps,
        address oldCollateral,
        address newCollateral,
        address oldLiquidation,
        address newLiquidation,
        address oldTermManager,
        address newTermManager,
        address oldCircuitBreaker,
        address newCircuitBreaker
    );

    event ContractUpgraded(
        address indexed oldImplementation,
        address indexed newImplementation,
        string version,
        uint256 timestamp
    );

    event ContractPaused(
        address indexed caller,
        uint256 timestamp
    );

    event ContractUnpaused(
        address indexed caller,
        uint256 timestamp
    );

    event ProtocolEmergencyPaused(
        address indexed caller,
        uint256 timestamp
    );

    event UCDEmergencyPaused(
        address indexed caller,
        uint256 timestamp
    );

    /// @dev Emitted when bulk-pause wiring addresses are rotated via timelock.
    event PositionManagerAddressUpdated(
        address indexed oldAddress,
        address indexed newAddress
    );
    event BTCSpendAuthorizerAddressUpdated(
        address indexed oldAddress,
        address indexed newAddress
    );
    event SimplePSMV2AddressUpdated(
        address indexed oldAddress,
        address indexed newAddress
    );
    event UCDControllerAddressUpdated(
        address indexed oldAddress,
        address indexed newAddress
    );
    event UCDTokenAddressUpdated(
        address indexed oldAddress,
        address indexed newAddress
    );
}

src/interfaces/IBTCSpendAuthorizer.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title IBTCSpendAuthorizer
 * @dev Interface for BTCSpendAuthorizer contract
 * @notice Manages authorized BTC spend records and UTXO authorization for positions
 */
interface IBTCSpendAuthorizer {
    // ==============================
    // Struct definitions
    // ==============================

    struct AuthorizedSpend {
        string txid; // Representative vault outpoint: funding tx ID
        uint32 vout; // Representative vault outpoint: output index
        // TOTAL input value (sats) the authorized consolidation consumes across
        // the vault's confirmed UTXO set — NOT the representative outpoint's
        // own value (for a multi-UTXO vault the aggregate exceeds it; Phase 1
        // signs vaultSatoshis = newCollateral + totalDeduction). targetAmount
        // must not exceed it (TargetExceedsInputValue); equality is a full
        // sweep with no change output. The network fee is carved out of
        // targetAmount by the signer, not added on top of it.
        uint256 satoshis;
        string targetAddress; // Where BTC goes (recipient)
        // GROSS amount deducted from the vault (satoshis); the recipient receives
        // targetAmount - networkFee. Must be > 0 and <= satoshis.
        uint256 targetAmount;
        uint256 authorizedAt; // Timestamp when authorized
    }

    // ==============================
    // Write functions (onlyLoanOps)
    // ==============================

    /**
     * @notice Authorize a BTC UTXO for spending
     * @param positionId Position identifier
     * @param txid Bitcoin UTXO transaction ID
     * @param vout Output index in the transaction
     * @param satoshis Total input value (sats) the authorized consolidation consumes (>= every single referenced outpoint's value)
     * @param targetAddress Destination Bitcoin address
     * @param targetAmount Gross amount deducted from the vault (satoshis); the recipient receives targetAmount - networkFee. Must be > 0 and <= the aggregate satoshis (equality = full sweep, no change output)
     * @param litSignature ECDSA signature from the protocol PKP validator over EIP-712 `BtcSpendAuth` (see `eip712DigestBtcSpendAuth`)
     * @return authIndex Index of the new authorized spend entry
     */
    function authorizeBTCSpend(
        bytes32 positionId,
        string calldata txid,
        uint32 vout,
        uint256 satoshis,
        string calldata targetAddress,
        uint256 targetAmount,
        bytes calldata litSignature
    ) external returns (uint256 authIndex);

    // ==============================
    // View functions
    // ==============================

    /**
     * @notice Compute hash of all authorized spends for a position
     * @param positionId Position identifier
     * @return Hash committing to the entire authorized spends array
     */
    function computeAuthorizedSpendsHash(
        bytes32 positionId
    ) external view returns (bytes32);

    /**
     * @notice Get total authorized satoshis for a position
     * @param positionId Position identifier
     * @return Total satoshis across all authorized spends
     */
    function getTotalAuthorizedSats(
        bytes32 positionId
    ) external view returns (uint256);

    /**
     * @notice Get all authorized spends for a position
     * @param positionId Position identifier
     * @return Array of AuthorizedSpend structs
     */
    function getAuthorizedSpends(
        bytes32 positionId
    ) external view returns (AuthorizedSpend[] memory);

    /**
     * @notice Paginated view of authorized spends for a position
     * @param positionId Position to query
     * @param offset Index of the first element to return (0-based)
     * @param limit Maximum number of elements to return
     * @return page The requested slice of authorized spends
     * @return total Total number of authorized spends in storage
     */
    function getAuthorizedSpendsPaginated(
        bytes32 positionId,
        uint256 offset,
        uint256 limit
    ) external view returns (AuthorizedSpend[] memory page, uint256 total);

    /**
     * @notice Filter UTXOs to find which ones are not yet authorized
     * @param positionId Position identifier
     * @param allTxids Array of UTXO transaction IDs to check
     * @param allVouts Array of output indices to check
     * @return available Boolean array: true if UTXO is NOT yet authorized
     */
    function getAvailableUTXOs(
        bytes32 positionId,
        string[] calldata allTxids,
        uint32[] calldata allVouts
    ) external view returns (bool[] memory available);

    /**
     * @notice Estimate gas for authorized-spends iteration operations
     * @param positionId Position to estimate for
     * @return estimatedGas Approximate gas units required
     * @return spendCount Current number of authorized spends
     */
    function estimateAuthorizedSpendsGas(
        bytes32 positionId
    ) external view returns (uint256 estimatedGas, uint256 spendCount);

    /**
     * @notice Check if a nonce has been used for a position
     * @param positionId Position identifier
     * @param nonce Nonce value to check
     * @return True if nonce has been used
     */
    function isNonceUsed(
        bytes32 positionId,
        uint256 nonce
    ) external view returns (bool);

    /**
     * @notice Get the last recorded nonce for a position
     * @param positionId Position identifier
     * @return Last used nonce value
     */
    function getLastNonce(bytes32 positionId) external view returns (uint256);

    /**
     * @notice Check if a specific UTXO is authorized for spending
     * @param positionId Position identifier
     * @param txid Bitcoin transaction ID
     * @param vout Output index
     * @return True if UTXO is authorized
     */
    function isUTXOAuthorized(
        bytes32 positionId,
        string calldata txid,
        uint32 vout
    ) external view returns (bool);

    /// @notice EIP-712 digest for `BtcSpendAuth` (`verifyingContract` = BTCSpendAuthorizer proxy).
    function eip712DigestBtcSpendAuth(
        bytes32 positionId,
        string calldata txid,
        uint32 vout,
        uint256 satoshis,
        string calldata targetAddress,
        uint256 targetAmount
    ) external view returns (bytes32);

    // ==============================
    // Production Sentinel
    // ==============================

    /// @notice Returns true on production implementations. Test bypasses return false.
    /// Called by setBTCSpendAuthorizer to prevent installing test-only stubs on live deployments.
    function IS_PRODUCTION_AUTHORIZER() external pure returns (bool);

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

    /**
     * @notice Cancel a stale authorized spend whose broadcast step never completed
     * @param positionId Position identifier
     * @param utxoKey keccak256(abi.encodePacked(txid, vout)) — pre-computed by the caller
     */
    function cancelStaleSpend(
        bytes32 positionId,
        bytes32 utxoKey
    ) external;

    /**
     * @notice Mark an authorized spend as consumed by a verified Bitcoin broadcast.
     * @dev Identical state mutation to cancelStaleSpend (removes the entry from the
     *      authorized array and clears the lookup) but emits BTCSpendConsumed instead of
     *      BTCSpendCancelled so the on-chain audit trail distinguishes successful consumption
     *      from a user-initiated cancellation. Phase-1 already debited the position balance,
     *      so this call is bookkeeping/UX cleanup — not a value-bearing operation.
     * @param positionId Position identifier
     * @param utxoKey keccak256(abi.encodePacked(txid, vout)) — pre-computed by the caller
     * @param broadcastTxid The Bitcoin txid of the broadcast that consumed this UTXO
     *        (not validated on-chain; surfaced via the event for off-chain indexers/explorers)
     */
    function markSpent(
        bytes32 positionId,
        bytes32 utxoKey,
        string calldata broadcastTxid
    ) external;

    /// @notice Permissionless LIT-attested stale-spend recovery (v1.6.0+, audit #62210 follow-up).
    function cancelStaleSpendWithProof(
        bytes32 positionId,
        bytes32 utxoKey,
        uint256 authorizedAt,
        string calldata invalidatorTxid,
        uint256 attestationTimestamp,
        bytes calldata litSignature
    ) external;

    /// @notice ADMIN_ROLE emergency override for stale-spend recovery (v1.6.0+).
    function cancelStaleSpendByAdmin(
        bytes32 positionId,
        bytes32 utxoKey,
        string calldata reason
    ) external;

    /// @notice Rotate the LIT validator authorised to sign stale-spend recovery attestations (v1.6.0+).
    function setStaleSpendValidator(address validator) external;

    /// @notice EIP-712 digest of a `StaleSpendRecovery` attestation (v1.6.0+).
    function eip712DigestStaleSpendRecovery(
        bytes32 positionId,
        bytes32 utxoKey,
        uint256 authorizedAt,
        string calldata invalidatorTxid,
        uint256 attestationTimestamp
    ) external view returns (bytes32);

    /// @notice Current LIT validator address authorised to sign stale-spend recovery attestations.
    function staleSpendValidatorAddress() external view returns (address);

    /// @notice Maximum age (seconds) of a stale-spend attestation accepted by `cancelStaleSpendWithProof`.
    function MAX_ATTESTATION_AGE() external view returns (uint256);

    event BTCSpendAuthorized(
        bytes32 indexed positionId,
        string txid,
        uint32 vout,
        uint256 satoshis,
        string targetAddress,
        uint256 targetAmount,
        uint256 authIndex
    );

    event BTCSpendCancelled(
        bytes32 indexed positionId,
        bytes32 utxoKey,
        uint256 satoshis,
        address indexed caller,
        uint256 timestamp
    );

    event BTCSpendConsumed(
        bytes32 indexed positionId,
        bytes32 utxoKey,
        string broadcastTxid,
        uint256 satoshis,
        address indexed caller,
        uint256 timestamp
    );
}

src/interfaces/ICircuitBreakerModule.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @title ICircuitBreakerModule
 * @dev Interface for circuit breaker functionality
 */
interface ICircuitBreakerModule is IERC165 {
    // Circuit breaker validation (state-changing to atomically consume capacity)
    function circuitBreakerCheck(uint256 ucdAmount) external;

    /// @notice OZ Pausable: halts `circuitBreakerCheck` while paused (independent of `circuitBreakerActive`).
    function pause() external;

    function unpause() external;

    function paused() external view returns (bool);

    // Limit management (routes through AdminModule 24h timelock)
    function setLimits(
        uint256 newMaxLoanValue,
        uint256 newDailyLimit
    ) external;

    // Circuit breaker control
    function activateCircuitBreaker() external;
    function deactivateCircuitBreaker() external;
    function signCircuitBreakerDeactivation() external;

    // View functions
    function maxSingleLoanValue() external view returns (uint256);
    function dailyVolumeLimit() external view returns (uint256);
    function circuitBreakerActive() external view returns (bool);
    function circuitBreakerActivatedAt() external view returns (uint256);
    function dailyUcdVolume(uint256 day) external view returns (uint256);

    // Events
    event CircuitBreakerActivated(address indexed admin);
    event CircuitBreakerDeactivated(address indexed admin);
    event CircuitBreakerDeactivationSigned(address indexed signer, uint256 totalSignatures);
    event LimitsUpdated(
        uint256 oldMaxLoanValue,
        uint256 newMaxLoanValue,
        uint256 oldDailyLimit,
        uint256 newDailyLimit
    );
    event DailyLimitApproached(uint256 currentVolume, uint256 limit, uint256 percentage);
}

src/interfaces/ICollateralManager.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "../libraries/BitcoinAddressValidator.sol";

/**
 * @title ICollateralManager
 * @dev Interface for CollateralManager contract
 * @notice Defines functions for Bitcoin collateral management
 */
interface ICollateralManager is IERC165 {
    /**
     * @dev Struct for BTC withdrawal parameters (optimized for stack depth)
     * @param positionId Position identifier
     * @param actionHash keccak256("withdraw-btc") - operation type binding
     * @param authorizedSpendsHash keccak256(authorizedSpendsSats) - race prevention
     * @param ucdDebtHash keccak256(ucdDebt) - replay prevention after repay
     * @param contractBundleHash keccak256(PositionManager, LoanOpsManager, TermManager) - upgrade flexibility
     * @param withdrawalAddress Bitcoin destination address
     * @param totalDeduction Amount removed from vault (sats)
     * @param newCollateral Post-withdrawal BTC balance (sats)
     * @param quantumTimestamp Quantum window timestamp
     * @param btcPrice BTC price in USD (18 decimals)
     * @param utxoTxid Bitcoin UTXO transaction ID to spend
     * @param utxoVout Bitcoin UTXO output index to spend
     */
    struct WithdrawalParams {
        bytes32 positionId;
        bytes32 actionHash;
        bytes32 authorizedSpendsHash;
        bytes32 ucdDebtHash;
        bytes32 contractBundleHash;
        string withdrawalAddress;
        uint256 totalDeduction;
        uint256 newCollateral;
        uint256 quantumTimestamp;
        uint256 btcPrice;
        string utxoTxid;
        uint32 utxoVout;
    }

    // Collateral operations
    // addCollateral removed - BTC balance is now queried on-chain via lit-actions with signature validation
    /// @param withdrawalValidatorSignature Registry / `withdrawBTC` authorization (full bundle hash)
    /// @param btcSpendAuthSignature EIP-712 `BtcSpendAuth` signature for `authorizeBTCSpend`. Required (65 bytes, signed by `btcSpendValidatorAddress`); the bypass for an unset validator was removed in C-5.
    function withdrawBTC(
        WithdrawalParams calldata params,
        bytes calldata withdrawalValidatorSignature,
        bytes calldata btcSpendAuthSignature
    ) external returns (bool);

    // View functions
    function getBitcoinAddressInfo(
        string memory bitcoinAddress
    )
        external
        pure
        returns (BitcoinAddressValidator.ValidationResult memory result);

    function cancelStaleSpend(bytes32 positionId, bytes32 utxoKey) external;

    // Events
    // CollateralAdded event removed - addCollateral functionality removed
    event BTCWithdrawn(
        bytes32 indexed positionId,
        string withdrawalAddress,
        uint256 amount
    );
}

src/interfaces/ILITActionValidator.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title ILITActionValidator
 * @dev Interface for LIT Action validation contract defining validation methods
 * @notice This interface defines the validation methods required for PKP-based Bitcoin custody operations
 */
interface ILITActionValidator {
    // M-03 (v2.3.0): `validateLITActionSignature` removed. The function was dead code
    // gated by a privileged `LIT_PROTOCOL_ROLE`; production flows route through
    // `OperationAuthorizationRegistry.verifyAuthorization` instead.

    /**
     * @dev Verifies PKP signing conditions meet protocol requirements
     * @param conditions Signing conditions to verify
     * @return bool True if conditions are valid, false otherwise
     * @notice Validates 2-of-3 threshold signature, Bitcoin transaction capability, and burn capability
     */
    function verifySigningConditions(
        bytes memory conditions
    ) external view returns (bool);

    /**
     * @dev Checks if PKP has been burned or is still active
     * @param pkpId PKP identifier to check
     * @return bool True if PKP is burned, false if still active
     */
    function checkPKPBurnStatus(bytes32 pkpId) external view returns (bool);

    /**
     * @dev Get main action ID for a PKP
     * @param pkpId PKP identifier
     * @return bytes32 Main action ID
     */
    function getMainActionForPKP(bytes32 pkpId) external view returns (bytes32);

    /**
     * @dev Check if main action is authorized
     * @param mainActionId Main action identifier
     * @return bool True if authorized
     */
    function isAuthorizedMainAction(
        bytes32 mainActionId
    ) external view returns (bool);

    /**
     * @dev Get PKP validator address for signature verification
     * @param pkpId PKP identifier
     * @return address PKP validator address for signature verification
     * @notice Returns the address that should have signed messages for this PKP
     */
    function getPKPValidatorAddress(
        bytes32 pkpId
    ) external view returns (address);

    /**
     * @dev Get current owner of a PKP
     * @param pkpId PKP identifier
     * @return address Current owner address (zero if unregistered)
     */
    function pkpOwners(bytes32 pkpId) external view returns (address);

    /**
     * @dev Transfer PKP ownership to a new address (liquidation path only).
     * @param pkpId PKP identifier
     * @param newOwner New owner address
     * @notice Restricted to the configured liquidationManager address (H-6 fix).
     */
    function transferPKPOwnership(bytes32 pkpId, address newOwner) external;

    /**
     * @dev Get expected CID for PKP validation message
     * @param pkpId PKP identifier
     * @return string Expected CID that should be included in validation message
     * @notice Returns the CID that should be used in PKP validation message format
     */
    function getExpectedCidForPKP(
        bytes32 pkpId
    ) external view returns (string memory);

    /**
     * @dev Get the AdminModule proxy authorised to call admin functions on this contract (v2.1.0+).
     * @return address The AdminModule proxy address, or `address(0)` on proxies not yet upgraded to v2.1.0.
     */
    function adminModule() external view returns (address);

    /**
     * @dev The single LiquidationManager authorised to call `transferPKPOwnership` (H-6 fix).
     */
    function liquidationManager() external view returns (address);

    /**
     * @dev Rotate the AdminModule proxy authorised to call admin functions (v2.1.0+).
     * @param newAdminModule Replacement AdminModule proxy address. Must be a contract.
     * @notice Gated by `msg.sender == adminModule` — only the current AdminModule can rotate.
     */
    function setAdminModule(address newAdminModule) external;

    /**
     * @dev Wire or rotate the LiquidationManager authorised to call `transferPKPOwnership`.
     * @param newLiquidationManager LiquidationManager proxy address. Must be a contract.
     * @notice Gated by `onlyAdminModule`.
     */
    function setLiquidationManager(address newLiquidationManager) external;

    // Events
    event PKPOwnershipTransferred(bytes32 indexed pkpId, address indexed oldOwner, address indexed newOwner);
    // M-03 (v2.3.0): LITActionValidated and ValidationFailed removed alongside `validateLITActionSignature`.
    // LOW-8: SigningConditionsVerified and PKPBurnStatusChecked removed — never emitted.
    // L-2: ValidationProofGenerated removed alongside executeLITActionValidation/generateValidationProof.
    event AdminModuleUpdated(address indexed oldAdminModule, address indexed newAdminModule);
    event LiquidationManagerUpdated(address indexed oldLiquidationManager, address indexed newLiquidationManager);
}

src/interfaces/ILiquidationManager.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @title ILiquidationManager
 * @dev Interface for LiquidationManager contract
 * @notice Defines functions for position liquidation
 */
interface ILiquidationManager is IERC165 {
    // Liquidation operations
    function commitLiquidation(bytes32 positionId, uint256 quantumTimestamp, uint256 btcPrice, uint256 btcAmountSats, address liquidatorAddress) external;
    function revealAndLiquidate(
        bytes32 positionId,
        uint256 quantumTimestamp,
        uint256 btcPrice,
        uint256 btcAmountSats,
        bytes calldata liquidationValidatorSignature,
        uint256 deadline,
        address liquidatorAddress
    ) external returns (bool);

    // View functions (require LIQUIDATOR_ROLE)
    function isLiquidatable(
        bytes32 positionId,
        uint256 quantumTimestamp,
        uint256 btcPrice,
        uint256 btcAmountSats,
        bytes calldata liquidationValidatorSignature
    ) external view returns (bool);

    /// @notice EIP-712 digest for standard liquidation authorization (Lit ↔ `isLiquidatable` / commit / reveal).
    function eip712DigestLiquidation(
        bytes32 positionId,
        uint256 quantumTimestamp,
        uint256 btcPrice,
        uint256 btcVaultBalance,
        address liquidator
    ) external view returns (bytes32);

    // PKP ownership helper
    function getPkpOwner(bytes32 pkpId) external view returns (address);

    // Global stats
    function getGlobalLiquidationStats() external view returns (uint256 liquidationCount, uint256 totalVolume);

    // Parameter view functions
    function liquidationThreshold() external view returns (uint256);
    function maxLiquidationAmount() external view returns (uint256);
    function liquidationTimeout() external view returns (uint256);

    // Expired loan escalation parameter view functions
    function expiryLiquidationIncrementBps() external view returns (uint256);
    function expiredLoanGracePeriodDays() external view returns (uint256);
    function maxEscalatedThreshold() external view returns (uint256);
    /// @dev Deprecated: no longer used by commit logic (no steal until stale). Kept for storage layout / ABI compatibility.
    function commitOverrideDelay() external view returns (uint256);

    // Expired loan escalation parameter setters (ADMIN_MODULE_ROLE)
    function setExpiryLiquidationIncrement(uint256 newIncrementBps) external;
    function setExpiredLoanGracePeriod(uint256 newGracePeriodDays) external;
    function setMaxEscalatedThreshold(uint256 newMaxThreshold) external;
    
    // Events
    event PositionLiquidated(
        bytes32 indexed positionId,
        address indexed liquidator,
        uint256 collateralRatio,
        uint256 debtRepaid,
        uint256 collateralValue,
        bool wasExpired,
        uint256 timestamp
    );
}

src/interfaces/ILoanOperationsManager.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "./IBTCSpendAuthorizer.sol";
import "./ICollateralManager.sol";

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @title ILoanOperationsManager
 * @dev Interface for LoanOperationsManager contract
 * @notice Defines functions for UCD minting, loan repayment, and debt management
 */
interface ILoanOperationsManager is IERC165 {
    /// @notice audit #3 (v1.6.0): feed-staleness policy passed by callers to `validateBtcPrice`.
    ///         Exempt = no staleness gate (renew/repay); Borrow / Liquidation select the matching
    ///         `maxBtcFeedAge*` threshold. ABI decoding reverts on an out-of-range value (type-safe).
    enum BtcPricePolicy { Exempt, Borrow, Liquidation }

    // Core loan operations
    function mintUCD(
        bytes32 positionId,
        address borrower,
        uint256 mintAmount,
        uint256 mintFee,
        uint256 newDebt,
        uint256 newCollateral,
        uint256 btcPrice,
        bytes32 authorizedSpendsHash,
        bytes32 ucdDebtHash,
        uint256 quantumTimestamp
    ) external returns (bool);

    function processPayment(
        bytes32 positionId,
        uint256 paymentAmount,
        uint256 quantumTimestamp,
        uint256 btcPrice
    ) external returns (bool);

    // updatePosition removed — testnet-only debug function.

    // Fee accumulation + sweep (M-8 fix)
    function transferFee(
        address recipient,
        uint256 amount
    ) external returns (uint256 transferred);
    function mintExtensionFee(uint256 amount) external returns (bool);
    function feeBalance() external view returns (uint256);
    function setFeeRecipientRegistry(address registry) external;
    function feeRecipientRegistry() external view returns (address);

    // BTC spend authorization
    function authorizeBTCSpend(
        bytes32 positionId,
        string calldata txid,
        uint32 vout,
        uint256 satoshis,
        string calldata targetAddress,
        uint256 targetAmount,
        bytes calldata litSignature
    ) external returns (uint256 authIndex);

    // View functions
    function liquidationThreshold() external view returns (uint256);
    function minimumLoanValueWei() external view returns (uint256);
    function minimumLoanValueUcd() external view returns (uint256);
    function maximumLoanValueUcd() external view returns (uint256);
    function perUserDailyMintLimit() external view returns (uint256);
    function perUserDailyMintEnabled() external view returns (bool);
    function setPerUserDailyMintEnabled(bool enabled) external;
    function minBtcPriceBound() external view returns (uint256);
    function maxBtcPriceBound() external view returns (uint256);
    function getBtcPriceBounds() external view returns (uint256 minPrice, uint256 maxPrice);
    function ucdToken() external view returns (address);
    function getUcdController() external view returns (address);

    // M-3 (v1.4.0): Chainlink BTC/USD cross-check
    function btcUsdPriceFeed() external view returns (address);
    function priceDeviationToleranceBps() external view returns (uint16);
    function validateBtcPriceWithOracle(uint256 signedPrice) external view;
    function isBtcPriceValid(uint256 signedPrice) external view returns (bool);
    function setBtcUsdPriceFeed(address newFeed) external;
    function setPriceDeviationToleranceBps(uint16 newBps) external;

    // audit #3 (v1.6.0): Chainlink feed staleness gate
    function maxBtcFeedAgeBorrow() external view returns (uint32);
    function maxBtcFeedAgeLiquidation() external view returns (uint32);
    /// @notice Revert-style validation with a per-operation staleness policy (single dispatch entry).
    function validateBtcPrice(uint256 signedPrice, BtcPricePolicy policy) external view;
    function setMaxBtcFeedAgeBorrow(uint32 newAge) external;
    function setMaxBtcFeedAgeLiquidation(uint32 newAge) external;

    /// @notice Governance timelock address (production dependency updates must be executed via this caller).
    function timelock() external view returns (address);

    /// @notice EIP-712 digests for registry-backed borrower flows (`verifyingContract` = LOM proxy).
    function eip712DigestMintUcd(
        bytes32 positionId,
        uint256 mintAmount,
        uint256 mintFee,
        uint256 newDebt,
        uint256 newCollateral,
        uint256 btcPrice,
        bytes32 authorizedSpendsHash,
        bytes32 ucdDebtHash,
        bytes32 contractHash,
        uint256 quantumTimestamp,
        address borrower
    ) external view returns (bytes32);

    function eip712DigestPartialPayment(
        bytes32 positionId,
        uint256 quantumTimestamp,
        uint256 btcPrice,
        uint256 paymentAmount,
        address borrower
    ) external view returns (bytes32);

    function eip712DigestExtendPosition(
        bytes32 positionId,
        uint256 selectedTerm,
        uint256 btcPrice,
        uint256 availableBTCBalance,
        uint256 proRataRenewalFee,
        uint256 quantumTimestamp,
        address borrower
    ) external view returns (bytes32);

    function eip712DigestBalanceConfirmation(
        bytes32 positionId,
        uint256 collateralValue,
        uint256 btcPrice,
        uint256 quantumTimestamp,
        address borrower
    ) external view returns (bytes32);

    function eip712DigestWithdrawalAuthorization(
        ICollateralManager.WithdrawalParams calldata params,
        address caller
    ) external view returns (bytes32);

    // Governance
    function updateBtcPriceBounds(uint256 newMinBtcPriceBound, uint256 newMaxBtcPriceBound) external;

    // Dynamic collateral helper functions
    function getAuthorizedSpendsHash(
        bytes32 positionId
    ) external view returns (bytes32);
    function getTotalAuthorizedSats(
        bytes32 positionId
    ) external view returns (uint256);

    // BTC Spend Authorizer sub-module
    function btcSpendAuthorizer() external view returns (IBTCSpendAuthorizer);
    function setBTCSpendAuthorizer(address newAuthorizer) external;

    // ERC165 interface support
    function supportsInterface(bytes4 interfaceId) external view returns (bool);

    // Events
    event BtcPriceBoundsUpdated(
        uint256 oldMinBound,
        uint256 newMinBound,
        uint256 oldMaxBound,
        uint256 newMaxBound,
        address indexed caller,
        uint256 timestamp
    );

    // M-3 (v1.4.0): Chainlink BTC/USD cross-check events
    event BtcPriceOracleFeedUpdated(
        address indexed oldFeed,
        address indexed newFeed,
        address indexed admin,
        uint256 timestamp
    );
    event BtcPriceDeviationToleranceUpdated(
        uint16 oldBps,
        uint16 newBps,
        address indexed admin,
        uint256 timestamp
    );
    // audit #3 (v1.6.0): Chainlink feed-staleness threshold updates
    event MaxBtcFeedAgeBorrowUpdated(
        uint32 oldAge,
        uint32 newAge,
        address indexed admin,
        uint256 timestamp
    );
    event MaxBtcFeedAgeLiquidationUpdated(
        uint32 oldAge,
        uint32 newAge,
        address indexed admin,
        uint256 timestamp
    );

    event PositionRepaid(
        bytes32 indexed positionId,
        uint256 amount,
        address indexed repayer
    );
    event PositionUpdated(
        bytes32 indexed positionId,
        uint256 newDebt,
        uint256 newRatio
    );

    function cancelStaleSpend(bytes32 positionId, bytes32 utxoKey) external;
    function cancelStaleSpendByOwner(bytes32 positionId, bytes32 utxoKey) external;
}

src/interfaces/IOperationAuthorizationRegistry.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title IOperationAuthorizationRegistry
 * @notice Interface for operation authorization registry
 */
interface IOperationAuthorizationRegistry {
    struct Validator {
        address pkpAddress;
        uint256 version;
        bool active;
    }

    struct PendingValidatorUpdate {
        bytes4   selector;
        address  pkpAddress;
        uint256  version;
        uint256  proposedAt;
        uint256  sigCount;
        bool     executed;
        bool     cancelled;
    }

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

    event ValidatorSet(
        bytes4 indexed selector,
        address indexed pkpAddress,
        uint256 version,
        address indexed setBy
    );

    event ValidatorDeactivated(
        bytes4 indexed selector,
        address indexed deactivatedBy
    );

    event ValidatorUpdateProposed(
        bytes32 indexed proposalHash,
        bytes4 indexed selector,
        address indexed pkpAddress,
        uint256 version,
        address proposer,
        uint256 proposedAt
    );

    event ValidatorUpdateSigned(
        bytes32 indexed proposalHash,
        address indexed signer,
        uint256 totalSignatures
    );

    event ValidatorUpdateExecuted(
        bytes32 indexed proposalHash,
        bytes4 indexed selector,
        address indexed pkpAddress,
        uint256 version,
        address executor
    );

    event ValidatorUpdateCancelled(
        bytes32 indexed proposalHash,
        address indexed canceller
    );

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

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

    event AuthorizedSignerAdded(
        address indexed signer,
        address indexed addedBy
    );

    event AuthorizedSignerRemoved(
        address indexed signer,
        address indexed removedBy
    );

    /// @notice audit F1: emitted when the AdminModule grants/revokes a quantum-consumer authorization.
    event AuthorizedQuantumConsumerUpdated(address indexed consumer, bool allowed);

    // ============================================================================
    // Ownership
    // ============================================================================

    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function transferOwnership(address newOwner) external;
    function acceptOwnership() external;

    // ============================================================================
    // Authorized Signers
    // ============================================================================

    function authorizedSigners(address signer) external view returns (bool);
    function requiredSignatures() external view returns (uint256);
    function addAuthorizedSigner(address signer) external;
    function removeAuthorizedSigner(address signer) external;

    // ============================================================================
    // Timelocked Validator Management
    // ============================================================================

    function proposeSetValidator(
        bytes4 selector,
        address pkpAddress,
        uint256 version
    ) external returns (bytes32 proposalHash);

    function signSetValidator(bytes32 proposalHash) external;

    function executeSetValidator(bytes32 proposalHash) external;

    function cancelSetValidator(bytes32 proposalHash) external;

    // ============================================================================
    // Emergency (immediate)
    // ============================================================================

    function deactivateValidator(bytes4 selector) external;

    // ============================================================================
    // View Functions
    // ============================================================================

    function getValidator(
        bytes4 selector
    ) external view returns (Validator memory);

    function isValidatorActive(bytes4 selector) external view returns (bool);

    function getPendingUpdate(
        bytes32 proposalHash
    ) external view returns (PendingValidatorUpdate memory);

    // ============================================================================
    // Quantum Window
    // ============================================================================

    function getCurrentQuantum() external view returns (uint256);

    function isInDeadZone(uint256 timestamp) external pure returns (bool);

    function validateQuantum(
        bytes32 positionId,
        uint256 quantumTimestamp
    ) external;

    /// @notice Selector-scoped quantum validation. Consumes quantum for a specific operation lane.
    function validateQuantumForOperation(
        bytes32 positionId,
        bytes4 selector,
        uint256 quantumTimestamp
    ) external;

    /// @notice Read-only quantum validation — does NOT consume the quantum window.
    /// @return True if the quantum is within the valid window and has not been used.
    function isQuantumValid(
        bytes32 positionId,
        uint256 quantumTimestamp
    ) external view returns (bool);

    /// @notice Selector-scoped read-only quantum validation.
    function isQuantumValidForOperation(
        bytes32 positionId,
        bytes4 selector,
        uint256 quantumTimestamp
    ) external view returns (bool);

    /// @notice audit F1: deny-by-default allowlist gate for the state-mutating validate* entrypoints.
    function authorizedQuantumConsumers(address consumer) external view returns (bool);

    /// @notice audit F1: AdminModule-gated setter to authorize a quantum-lane consumer (e.g. PositionManager).
    function setAuthorizedQuantumConsumer(address consumer, bool allowed) external;

    // ============================================================================
    // Signature Verification
    // ============================================================================

    /// @notice Revert-only: success returns nothing; failure reverts with SignatureVerificationFailed or ValidatorNotActive
    function verifyAuthorization(
        bytes4 selector,
        bytes32 messageHash,
        bytes calldata signature
    ) external view;

    // ============================================================================
    // Production Sentinel
    // ============================================================================

    /// @notice Returns true on production implementations. Test bypasses return false.
    /// Called by setAuthorizationRegistry to prevent installing test-only stubs on live deployments.
    function IS_PRODUCTION_REGISTRY() external pure returns (bool);
}

src/interfaces/IPausableView.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title IPausableView
 * @notice Minimal view for OpenZeppelin Pausable `paused()` on external contracts.
 */
interface IPausableView {
    function paused() external view returns (bool);
}

src/interfaces/IPositionManager.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import {LoanStatusLib} from "../libraries/LoanStatus.sol";
import "./IPositionManagerCore.sol";
import "./IOperationAuthorizationRegistry.sol";
import "./IAdminModule.sol";

/**
 * @title IPositionManager
 * @dev Interface for position management contract defining core position operations
 * @notice This interface defines the core position management functions for the Diamond Hands Protocol
 */
interface IPositionManager {
    struct Position {
        // Slot 0: 32 bytes
        bytes32 positionId;
        // Slot 1: 32 bytes
        bytes32 pkpId;
        // Slot 2: 32 bytes
        uint256 ucdDebt;
        // Slot 3+: dynamic size (mainnetVaultAddress in core Position struct)
        // Slot N+: dynamic size (regtestVaultAddress in core Position struct)
        // Slot X: 32 bytes packed (gas optimized)
        address borrower; // 20 bytes
        uint40 createdAt; // 5 bytes
        uint40 lastUpdated; // 5 bytes
        uint16 selectedTerm; // 2 bytes - Loan term in months
        // Slot N+1: 6 bytes used, 26 bytes free for future upgrades
        uint40 expiryAt; // 5 bytes - Loan expiry timestamp
        LoanStatusLib.LoanStatus status; // 1 byte (enum stored as uint8)
    }

    struct PKPPositionData {
        bytes32 positionId;
        address borrower;
        uint256 amount;
        uint32 requestedCollateralRatio;
        uint16 selectedTerm;
        uint40 createdAt;
    }

    /// @notice Aggregated pause flags for Lit Actions / SDK fast-fail (TOCTOU: on-chain checks remain authoritative).
    struct ProtocolPauseStatus {
        bool positionManagerPaused;
        bool positionManagerLiquidationsPaused;
        bool positionManagerCorePaused;
        bool loanOperationsPaused;
        bool collateralManagerPaused;
        bool liquidationManagerPaused;
        bool circuitBreakerPaused;
        bool ucdControllerPaused;
        bool ucdTokenPaused;
        bool simplePsmPaused;
        bool termManagerPaused;
        bool adminModulePaused;
        bool btcSpendAuthorizerPaused;
        bool litActionValidatorPaused;
    }

    /// @notice Aggregated operational health metrics for dashboards and monitoring.
    /// @dev Pause states are intentionally excluded — use `getProtocolPauseStatus()` for those.
    /// @dev All uint256 fields grouped first, then bool fields at end for correct ABI encoding.
    struct SystemStatus {
        // --- Numeric fields (uint256) ---
        uint256 totalPositions;
        uint256 liquidationThreshold;   // basis points
        uint256 minimumLoanValueUcd;
        uint256 maximumLoanValueUcd;
        uint256 minBtcPriceBound;
        uint256 maxBtcPriceBound;
        uint256 circuitBreakerActivatedAt;
        uint256 cbDailyVolumeToday;
        uint256 cbDailyVolumeLimit;
        uint256 cbMaxSingleLoanValue;
        uint256 ucdTotalSupply;
        uint256 ucdMaxSupply;
        uint256 ucdDailyMinted;
        uint256 ucdDailyBurned;
        uint256 ucdDailyMintLimit;
        uint256 ucdDailyBurnLimit;
        uint256 totalLiquidations;
        uint256 totalLiquidationVolume;

        // --- Boolean fields (bool) ---
        bool coreSet;
        bool loanOpsSet;
        bool collateralSet;
        bool liquidationSet;
        bool termManagerSet;
        bool circuitBreakerSet;
        bool isPaused;
        bool circuitBreakerActive;
    }

    /**
     * @dev Creates new borrowing position with PKP integration and validator signature
     * @param pkpId PKP identifier for position
     * @param validatorSignature PKP validator signature for verification
     * @param mainnetVaultAddress Bitcoin mainnet address (from validator signature)
     * @param regtestVaultAddress Bitcoin regtest address (from validator signature)
     * @param selectedTermMonths Loan term in months
     * @param validatorVersion PKP validator version to use for signature verification
     * @return bytes32 Position ID of the created position
     * @notice PKP must be validated through ILITActionValidator
     */
    function createPosition(
        bytes32 pkpId,
        bytes calldata validatorSignature,
        string calldata mainnetVaultAddress,
        string calldata regtestVaultAddress,
        uint256 selectedTermMonths,
        uint256 validatorVersion,
        bytes calldata pkpPublicKey
    ) external returns (bytes32);

    /**
     * @dev Mint UCD tokens against a position using signed BTC price from Lit Action
     * @param positionId Position identifier to mint against
     * @param mintAmount UCD amount to mint
     * @param mintFee Minting fee in UCD
     * @param newDebt New total debt after minting
     * @param newCollateral New collateral amount in satoshis
     * @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
     * @param authorizedSpendsHash Hash of authorized Bitcoin spends
     * @param ucdDebtHash Hash of current UCD debt (prevents replay)
     * @param contractHash Hash of the contract bundle (prevents replay across deployments)
     * @param quantumTimestamp Quantum timestamp for replay protection
     * @param mintValidatorSignature Signature from mint Lit Action validator
     * @return bool True if mint successful
     * @notice This function handles all signature validation before delegating to internal mintUCD()
     */
    function mintUCD(
        bytes32 positionId,
        uint256 mintAmount,
        uint256 mintFee,
        uint256 newDebt,
        uint256 newCollateral,
        uint256 btcPrice,
        bytes32 authorizedSpendsHash,
        bytes32 ucdDebtHash,
        bytes32 contractHash,
        uint256 quantumTimestamp,
        bytes calldata mintValidatorSignature
    ) external returns (bool);

    // updateDebtFromLoanOps removed — testnet-only debug function.

    /**
     * @dev Increase position debt as part of a UCD mint. Verifies that UCD supply increased
     *      by exactly (newDebt - currentDebt) before recording the debt. Only callable by
     *      LoanOperationsManager while the per-position lock is held.
     * @param positionId Position identifier to update.
     * @param newDebt New total UCD debt (must be > currentDebt).
     * @param termStartTimestamp Quantum-certified term start timestamp.
     * @param mintFee Origination fee charged on this mint (EIP-712-signed); accumulated into
     *        the position's current-term origination-fee total for the H-4 renewal-fee floor.
     */
    function increaseDebtFromMint(
        bytes32 positionId,
        uint256 newDebt,
        uint256 termStartTimestamp,
        uint256 mintFee
    ) external;

    /**
     * @dev Decrease position debt as part of a UCD payment or repayment. Burns the difference
     *      from UCD held by PositionManager. Only callable by LoanOperationsManager while the
     *      per-position lock is held.
     * @param positionId Position identifier to update.
     * @param newDebt New total UCD debt (must be <= currentDebt).
     * @param termStartTimestamp Quantum-certified term start timestamp.
     */
    function decreaseDebtFromPayment(
        bytes32 positionId,
        uint256 newDebt,
        uint256 termStartTimestamp
    ) external;

    /**
     * @dev Helper function for LoanOperationsManager to update position status
     * @param positionId Position identifier
     * @param newStatus New status to set
     */
    function updatePositionStatusFromLoanOps(
        bytes32 positionId,
        LoanStatusLib.LoanStatus newStatus
    ) external;

    /**
     * @dev Returns complete position details
     * @param positionId Position to query
     * @return Position Complete position data structure
     */
    function getPositionById(
        bytes32 positionId
    ) external view returns (Position memory);

    /**
     * @dev Make payment on a loan using signed BTC price from Lit Action
     * @param positionId Position identifier to make payment on
     * @param paymentAmount UCD amount for payment
     * @param quantumTimestamp Quantum timestamp for replay protection
     * @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
     * @param paymentValidatorSignature Signature from payment Lit Action validator
     * @return bool True if payment successful
     * @notice This function handles all signature validation before delegating to internal processPayment()
     */
    function makePayment(
        bytes32 positionId,
        uint256 paymentAmount,
        uint256 quantumTimestamp,
        uint256 btcPrice,
        bytes calldata paymentValidatorSignature
    ) external returns (bool);

    /**
     * @dev Extend loan term by adding additional months in exchange for extension fee
     * @param positionId Position identifier to extend
     * @param selectedTerm Additional term in months to add to existing term
     * @param quantumTimestamp Quantum timestamp for replay protection
     * @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
     * @param availableBTCBalance Available BTC collateral in satoshis (signed by Lit Action)
     * @param proRataRenewalFee Pro-rata renewal fee (18 decimals) computed off-chain by Lit Action
     * @param extensionValidatorSignature Signature from extension Lit Action validator
     * @return bool True if extension successful
     */
    function extendPosition(
        bytes32 positionId,
        uint256 selectedTerm,
        uint256 quantumTimestamp,
        uint256 btcPrice,
        uint256 availableBTCBalance,
        uint256 proRataRenewalFee,
        bytes calldata extensionValidatorSignature
    ) external returns (bool);

    function authorizationRegistry() external view returns (IOperationAuthorizationRegistry);

    function getProtocolPauseStatus() external view returns (ProtocolPauseStatus memory);

    function liquidationPaused() external view returns (bool);

    function simplePsm() external view returns (address);

    function admin() external view returns (IAdminModule);

    /// @param simplePsmAddress Pausable PSM (e.g. SimplePSMV2) or zero to ignore in `getProtocolPauseStatus`.
    function setSimplePsm(address simplePsmAddress) external;

    function pause() external;

    function unpause() external;

    function pauseLiquidations() external;

    function unpauseLiquidations() external;

    // Events
    event PositionCreated(
        bytes32 indexed positionId,
        bytes32 indexed pkpId,
        address indexed borrower,
        // btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
        uint256 requestedCollateralRatio,
        uint256 selectedTerm,
        uint256 expiryAt
    );

    /**
     * @dev Emitted alongside `PositionCreated` so off-chain indexers (subgraph) can recover
     * the secp256k1 public key needed for BTC signing without depending on SDK in-memory cache.
     * The publicKey is bound to pkpId on-chain via Ethereum-style address derivation.
     */
    event PositionPkpPublicKeyRegistered(
        bytes32 indexed positionId,
        bytes32 indexed pkpId,
        bytes pkpPublicKey
    );
    event UCDMinted(bytes32 indexed positionId, uint256 amount, bytes proof);
    event PositionLiquidated(
        bytes32 indexed positionId,
        address indexed liquidator,
        uint256 collateralRatio,
        uint256 debtRepaid,
        uint256 collateralValue,
        bool wasExpired,
        uint256 timestamp
    );
    // NOTE: CollateralRatioUpdated event removed - collateral ratios are not calculated on-chain
    event PositionUpdated(
        bytes32 indexed positionId,
        uint256 oldDebt,
        uint256 newDebt
    );
    event PositionRepaid(
        bytes32 indexed positionId,
        address indexed borrower,
        uint256 repaymentAmount,
        uint256 timestamp
    );
    event PositionClosed(
        bytes32 indexed positionId,
        address indexed borrower,
        uint256 withdrawalAmount, // Amount withdrawn (not stored btcAmount)
        string withdrawalAddress,
        uint256 timestamp
    );
    // CollateralAdded event removed - addCollateral functionality removed
    // BTC balance is now queried on-chain via lit-actions with signature validation
    event PositionStatusUpdated(
        bytes32 indexed positionId,
        LoanStatusLib.LoanStatus oldStatus,
        LoanStatusLib.LoanStatus newStatus
    );
    event PKPLogicValidated(bytes32 indexed pkpId, bool isValid);
    event PositionRenewed(
        bytes32 indexed positionId,
        address indexed borrower,
        uint256 selectedTerm,
        uint256 extensionFee,
        uint256 newExpiryDate,
        uint256 timestamp
    );
    /// @param payer The account whose UCD funded the payment — always the position's stored
    ///        borrower, never the transaction submitter. Phase B left the submitter
    ///        unrestricted, so the two are no longer interchangeable: indexers must treat this
    ///        as the paying party and must NOT infer who broadcast the transaction from it.
    event PartialPaymentMade(
        bytes32 indexed positionId,
        address indexed payer,
        uint256 paymentAmount,
        uint256 remainingDebt,
        uint256 timestamp
    );
    event PositionHealthUpdated(
        bytes32 indexed positionId,
        uint256 collateralRatio,
        uint256 remainingDebt,
        address indexed updater,
        uint256 timestamp
    );

    event BalanceConfirmed(
        bytes32 indexed positionId,
        uint256 collateralValue,
        uint256 quantumTimestamp,
        uint256 confirmedAt
    );

    event LiquidationsPaused(address indexed account);
    event LiquidationsUnpaused(address indexed account);
}

src/interfaces/IPositionManagerCore.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import {LoanStatusLib} from "../libraries/LoanStatus.sol";
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import "./ILITActionValidator.sol";

/**
 * @title IPositionManagerCore
 * @dev Interface for core position management functionality
 * @notice Defines the core position operations for the modular PositionManager
 */
interface IPositionManagerCore is IERC165 {
    /**
     * @dev Core position record stored on-chain.
     *
     * Off-chain BTC balance model (M-6 design intent):
     * BTC collateral is intentionally NOT stored in this struct. Bitcoin UTXO state lives on the
     * Bitcoin network. Storing a `btcBalance` field here would become stale the moment a new UTXO
     * confirms, creating a false sense of accuracy.
     *
     * Instead, each balance-dependent operation (updateBalance, mintUCD, withdrawBTC, etc.) requires
     * a fresh LIT Action query of the Bitcoin UTXO set. The LIT Action signs the result; the contract
     * verifies the signature. The signed value is used for the operation and then discarded — it is
     * the cryptographic signature, not stored state, that acts as the on-chain trust anchor.
     *
     * `ucdDebt` is stored because it is purely Ethereum-native state that we own; it never goes stale.
     */
    struct Position {
        // Slot 0: 32 bytes
        bytes32 positionId;
        // Slot 1: 32 bytes
        bytes32 pkpId;
        // Slot 2: 32 bytes
        uint256 ucdDebt;
        // Slot 3+: dynamic size
        string vaultAddress; // Bitcoin vault address (mainnet or regtest based on contract deploy mode)
        // Slot X: 32 bytes packed
        address borrower; // 20 bytes
        uint40 createdAt; // 5 bytes
        uint40 lastUpdated; // 5 bytes
        uint16 selectedTerm; // 2 bytes — current segment in months (matches TermManager allowed terms; does NOT accumulate across renewals)
        // Slot X+1: 18 bytes used, 14 bytes free for future upgrades
        uint40 expiryAt; // 5 bytes - Loan expiry timestamp
        LoanStatusLib.LoanStatus status; // 1 byte (enum stored as uint8)
        uint40 previousExpiryAt; // 5 bytes — expiryAt before the most recent renewal; 0 if never renewed
        uint16 totalTerm; // 2 bytes — total accumulated loan months (e.g. 24 after one 12-month renewal); 0 before first renewal
        uint40 lastRenewedAt; // 5 bytes — block.timestamp of the most recent renewal; createdAt at origination. 0 for positions created before the H-5 upgrade (callers must fall back to createdAt).
    }

    /**
     * @dev Lightweight PKP position view used for PKP-centric queries
     * @notice Struct layout must match the return type of getPKPPositionData
     */
    struct PKPPositionData {
        bytes32 positionId;
        address borrower;
        uint16 selectedTerm;
        uint40 expiryAt;
        bool hasActiveLoan;
        LoanStatusLib.LoanStatus status;
    }

    /**
     * @dev Creates new borrowing position with PKP integration
     * @param pkpId PKP identifier for position
     * @param validatorSignature PKP validator signature for verification
     * @param borrower Address of the borrower
     * @param mainnetVaultAddress Bitcoin mainnet address (from validator signature)
     * @param regtestVaultAddress Bitcoin regtest address (from validator signature)
     * @return bytes32 Position ID of the created position
     */
    function createPosition(
        bytes32 pkpId,
        bytes calldata validatorSignature,
        address borrower,
        string calldata mainnetVaultAddress,
        string calldata regtestVaultAddress,
        uint256 selectedTermMonths
    ) external returns (bytes32);

    /**
     * @dev Returns complete position details
     * @param positionId Position to query
     * @return Position Complete position data structure
     */
    function getPositionDetails(
        bytes32 positionId
    ) external view returns (Position memory);

    /**
     * @dev Get only the Bitcoin vault address for a position. Gas-light: avoids decoding the
     *      full Position struct (used by `commitLiquidation` for the C-2 vaultAddress binding).
     *      Returns "" for a nonexistent position.
     */
    function getVaultAddress(
        bytes32 positionId
    ) external view returns (string memory);

    /**
     * @dev Get position ID by PKP ID
     * @param pkpId PKP identifier
     * @return bytes32 Position ID
     */
    function getPositionByPKP(bytes32 pkpId) external view returns (bytes32);

    /**
     * @dev Get user positions
     * @param user User address
     * @return bytes32[] Array of position IDs
     */
    function getUserPositions(
        address user
    ) external view returns (bytes32[] memory);

    /**
     * @dev Get PKP position data by PKP ID
     * @param pkpId PKP identifier
     * @return PKPPositionData Position data for the PKP
     */
    function getPKPPositionData(
        bytes32 pkpId
    ) external view returns (PKPPositionData memory);

    /**
     * @dev Get PKP loan parameters by PKP ID
     * @param pkpId PKP identifier
     * @return selectedTerm Loan term in months
     * @return ucdDebt Current UCD debt
     */
    function getPKPLoanParams(
        bytes32 pkpId
    ) external view returns (uint16 selectedTerm, uint256 ucdDebt);

    /**
     * @dev Get the current loan status for a position
     * @param positionId Position identifier
     * @return LoanStatus Current status of the position
     */
    function getPositionStatus(
        bytes32 positionId
    ) external view returns (LoanStatusLib.LoanStatus);

    /**
     * @dev Validates PKP logic for position operations
     * @param pkpId PKP identifier to validate
     * @return bool True if PKP logic is valid
     */
    function validatePKPLogic(bytes32 pkpId) external view returns (bool);

    /**
     * @dev Update position status with state machine validation
     * @param positionId Position to update
     * @param newStatus New status to set
     */
    function updatePositionStatus(
        bytes32 positionId,
        LoanStatusLib.LoanStatus newStatus
    ) external;

    /**
     * @dev Get total number of positions in the system
     * @return uint256 Total position count
     */
    function getTotalPositions() external view returns (uint256);

    /**
     * @dev Whether this deployment runs against Bitcoin mainnet (set once at initialization).
     *      Used by PositionManager to forbid disabling the renewal restriction on production.
     * @return bool True if the deploy-time Bitcoin network mode is "mainnet".
     */
    function isMainnet() external view returns (bool);

    /**
     * @dev Get position IDs with pagination support
     * @param offset Starting index for pagination
     * @param limit Maximum number of positions to return
     * @return bytes32[] Array of position IDs
     */
    function getPositionIds(
        uint256 offset,
        uint256 limit
    ) external view returns (bytes32[] memory);

    /**
     * @dev Update position debt amount
     * @param positionId Position to update
     * @param newDebt New debt amount
     */
    function updatePositionDebt(bytes32 positionId, uint256 newDebt) external;

    /**
     * @dev Set term start timestamp for position
     * @param positionId Position to update
     * @param termStartTimestamp Quantum timestamp when term starts
     */
    function setTermStart(
        bytes32 positionId,
        uint256 termStartTimestamp
    ) external;

    /**
     * @dev Update position term (for loan renewals)
     * @param positionId Position to update
     * @param newSelectedTerm New selected term in months
     */
    function updatePositionTerm(
        bytes32 positionId,
        uint256 newSelectedTerm
    ) external;


    /**
     * @dev Updates position expiry timestamp (for loan renewals)
     * @param positionId Position to update
     * @param newExpiryAt New expiry timestamp
     */
    function updatePositionExpiryAt(
        bytes32 positionId,
        uint256 newExpiryAt
    ) external;

    /**
     * @dev Records the expiryAt value before the most recent renewal (for post-renewal mint tail fee)
     * @param positionId Position to update
     * @param value Previous expiry timestamp (set to current expiryAt just before extending)
     */
    function updatePositionPreviousExpiry(
        bytes32 positionId,
        uint40 value
    ) external;

    /**
     * @dev Updates the total accumulated loan term in months (increments on each renewal)
     * @param positionId Position to update
     * @param value New total term in months (e.g. 24 after one 12-month renewal)
     */
    function updatePositionTotalTerm(
        bytes32 positionId,
        uint16 value
    ) external;

    /**
     * @dev Batched core writes for loan extension (single `msg.sender` check; shrinks PositionManager bytecode).
     * @param newExpiryAt Must match `ProtocolConstants.calculateExpiryTimestamp(previousExpiryAt, incomingSelectedTerm)`.
     */
    function applyExtensionCoreUpdates(
        bytes32 positionId,
        uint256 newTotalDebt,
        uint256 positionSelectedTerm,
        uint256 incomingSelectedTerm,
        uint16 newAccumulatedTotalTerm,
        uint40 previousExpiryAt,
        uint256 newExpiryAt
    ) external;

    /**
     * @dev Batched core writes after a successful UCD mint (single auth check; shrinks PositionManager bytecode).
     * @param previousDebt Debt recorded in core before this call — must match `positions[positionId].ucdDebt`.
     */
    /// @param mintFee Origination fee charged on this mint (EIP-712-signed). Accumulated into
    ///        `originationFeesPaidThisTerm` so `extendPosition` can independently bound the
    ///        pro-rata renewal credit to fees actually paid this term.
    function finalizeMintDebtIncrease(
        bytes32 positionId,
        uint256 newDebt,
        uint256 termStartTimestamp,
        uint256 previousDebt,
        uint256 mintFee
    ) external;

    /// @dev Origination fees charged to a position within its current term. Reset to zero by
    ///      `applyExtensionCoreUpdates` when the position rolls into a new term.
    function originationFeesPaidThisTerm(bytes32 positionId) external view returns (uint256);

    // addCollateral function removed - BTC balance is now queried on-chain via lit-actions with signature validation

    function litActionValidator() external view returns (ILITActionValidator);

    // Events
    event PositionCreated(
        bytes32 indexed positionId,
        bytes32 indexed pkpId,
        address indexed borrower,
        // btcAmount removed - balance is now queried on-chain via lit-actions with signature validation
        uint256 requestedCollateralRatio,
        uint256 selectedTerm,
        uint256 expiryAt
    );

    event PositionStatusUpdated(
        bytes32 indexed positionId,
        LoanStatusLib.LoanStatus oldStatus,
        LoanStatusLib.LoanStatus newStatus
    );
}

src/interfaces/IPositionManagerViews.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "../libraries/LoanStatus.sol";
import "./IPositionManager.sol";
import "./IPositionManagerCore.sol";

interface IPositionManagerViews {

    function calculateCollateralRatio(
        bytes32 positionId,
        uint256 currentBtcPrice,
        uint256 btcAmount
    ) external view returns (uint256 ratio, bool isHealthy);

    function getPositionById(
        bytes32 positionId
    ) external view returns (IPositionManagerCore.Position memory);

    /// @notice Maps core position to `IPositionManager.Position` (same as `PositionManager.getPositionById`).
    function getPositionByIdAsManager(
        bytes32 positionId
    ) external view returns (IPositionManager.Position memory);

    function getPositionByPKP(bytes32 pkpId) external view returns (bytes32);

    function getUserPositions(
        address user
    ) external view returns (bytes32[] memory positionIds, uint256 activeCount);

    function getTermFees(uint256 termMonths) external view returns (uint88 originationFee, uint88 extensionFee);

    function isValidTerm(uint256 termMonths) external view returns (bool);

    function getValidTermsWithFees() external view returns (
        uint256[] memory terms,
        uint88[] memory originationFees,
        uint88[] memory extensionFees
    );

    function getSystemLimits() external view returns (
        uint256 maxSingleLoanValue,
        uint256 dailyVolumeLimit
    );

    function getDailyVolume(uint256 day) external view returns (
        uint256 ucdVolume,
        uint256 percentOfLimit
    );

    function getCircuitBreakerStatus() external view returns (
        bool active,
        uint256 activatedAt,
        uint256 reason
    );

    function validatePositionIntegrity(bytes32 positionId) external view returns (
        bool valid,
        uint8[] memory issues
    );

    function getTotalPositions() external view returns (uint256);

    function getPositionIds(uint256 offset, uint256 limit) external view returns (bytes32[] memory);

    /// @notice One entry of the Proof of Reserve backing set: a position that carries UCD debt.
    /// @param positionId Position identifier.
    /// @param vaultAddress Bitcoin vault address stored at creation (verified against the PKP validator signature).
    /// @param ucdDebt Outstanding UCD debt (18 decimals); always non-zero in a returned entry.
    /// @param status `LoanStatusLib.LoanStatus` as uint8. Reported, never filtered on.
    struct BackingVault {
        bytes32 positionId;
        string vaultAddress;
        uint256 ucdDebt;
        uint8 status;
    }

    /**
     * @notice The Proof of Reserve backing set, paged: every position with `ucdDebt > 0`, whatever its status.
     * @dev Scans `allPositionIds[offset, offset + limit)` and returns only the debt-bearing positions, so
     *      `vaults.length` may be less than the number scanned. A liquidated position never appears: its
     *      debt is zeroed in the liquidation transaction, and BTC left in its vault is the liquidator's.
     *      Reserves are the confirmed UTXOs at each `vaultAddress`, read from Bitcoin by the consumer.
     *      Position ids are append-only, but debt and status change between blocks: read every page at the
     *      same block.
     * @param offset Index of the first position to scan (0-based).
     * @param limit  Maximum positions to scan; capped at MAX_POSITIONS_PER_QUERY. Reverts if zero.
     * @return vaults     Debt-bearing positions in the scanned slice.
     * @return nextOffset `offset` plus the number scanned. The scan is complete when `nextOffset >= total`.
     * @return total      Total number of positions.
     */
    function getBackingVaults(
        uint256 offset,
        uint256 limit
    ) external view returns (BackingVault[] memory vaults, uint256 nextOffset, uint256 total);

    /// @notice Aggregated operational health metrics (excludes pause states — use `getProtocolPauseStatus()` for those).
    function getSystemStatus() external view returns (IPositionManager.SystemStatus memory);

    function getVersion() external pure returns (string memory);

    /**
     * @dev Diagnose potential mintUCD failure reasons
     */
    function diagnoseMintUCD(
        bytes32 positionId,
        uint256 mintAmount,
        uint256 mintFee,
        uint256 newDebt,
        uint256 newCollateral,
        uint256 btcPrice,
        bytes32 authorizedSpendsHash,
        bytes32 ucdDebtHash,
        bytes32 contractHash,
        uint256 quantumTimestamp,
        bytes calldata mintValidatorSignature
    ) external view returns (string memory);

    /// @notice Same aggregate as `PositionManager.getProtocolPauseStatus()` (implementation lives on Views to save PM bytecode).
    function getProtocolPauseStatus()
        external
        view
        returns (IPositionManager.ProtocolPauseStatus memory);

    /// @notice Extension fee cap + `ExtensionValidationHelper.calculateExtensionMetrics` (moved from PositionManager for bytecode).
    function validateExtensionMetrics(
        IPositionManagerCore.Position memory position,
        uint256 selectedTerm,
        uint256 btcPrice,
        uint256 availableBTCBalance,
        uint256 proRataRenewalFee
    )
        external
        view
        returns (
            uint256 extensionFee,
            uint256 newTotalDebt,
            uint256 newCollateralRatio,
            uint256 newTotalTerm
        );

    /// @notice Delegates to `ExtensionValidationHelper.validateExtensionTiming` (bytecode offload from PositionManager).
    function validateExtensionTimingView(
        IPositionManagerCore.Position memory position,
        uint256 selectedTerm,
        bool restrictionDisabled
    ) external view;

}

src/interfaces/ITermManager.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/**
 * @title ITermManager
 * @dev Interface for TermManager contract
 * @notice Defines functions for managing loan terms
 */
interface ITermManager is IERC165 {
    // Term management functions
    function addTerm(uint256 _termMonths, uint88 _originationFee, uint88 _extensionFee) external;
    function removeTerm(uint256 _termMonths) external;
    function updateTermFees(uint256 _termMonths, uint88 _originationFee, uint88 _extensionFee) external;
    
    // View functions
    function getTermFees(uint256 _termMonths) external view returns (uint88 originationFee, uint88 extensionFee);
    function isValidTerm(uint256 _termMonths) external view returns (bool);
    function getValidTermsWithFees() external view returns (
        uint256[] memory terms,
        uint88[] memory originationFees,
        uint88[] memory extensionFees
    );
    
    
    // Admin functions
    function updateDependencies(address newCore, address newUcdController) external;

    /// @notice Rotate the AdminModule proxy that is authorised to call admin functions via direct address check.
    /// @dev Gated internally by `msg.sender == adminModule`; only the currently-wired AdminModule can rotate to another.
    function setAdminModule(address newAdminModule) external;

    // Events
    event TermAdded(
        uint256 indexed termMonths,
        uint88 originationFee,
        uint88 extensionFee,
        address indexed admin
    );
    
    event TermRemoved(
        uint256 indexed termMonths,
        address indexed admin
    );
    
    event TermFeesUpdated(
        uint256 indexed termMonths,
        uint88 newOriginationFee,
        uint88 newExtensionFee
    );
    
    
    event DependenciesUpdated(
        address core,
        address ucdController
    );
    
    event ContractUpgraded(
        address indexed oldImplementation,
        address indexed newImplementation,
        string version,
        uint256 timestamp
    );
}

src/interfaces/IUCDController.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title IUCDController
 * @dev Interface for UCD token controller operations
 * @notice Defines functions for minting, burning, and managing UCD tokens
 */
interface IUCDController {
    // Events
    event TokensMinted(address indexed to, uint256 amount, address indexed minter);
    event TokensBurned(address indexed from, uint256 amount, address indexed burner);
    event AuthorizedMinterUpdated(address indexed minter, bool authorized);
    event AuthorizedBurnerUpdated(address indexed burner, bool authorized);
    event MaxSupplyUpdated(uint256 oldMaxSupply, uint256 newMaxSupply);
    event DailyMintLimitUpdated(uint256 oldLimit, uint256 newLimit);
    event DailyBurnLimitUpdated(uint256 oldLimit, uint256 newLimit);
    event UCDTokenUpdated(address indexed oldToken, address indexed newToken);

    // Core functions
    function mintFromLoanOps(
        address to,
        uint256 amount,
        bytes32 positionId,
        uint256 debtAfterMint
    ) external;

    function mintFromPsm(
        address to,
        uint256 amount,
        address stablecoin,
        uint256 amountIn
    ) external;

    function burnTokens(address from, uint256 amount) external;

    function burnFromPsm(address from, uint256 amount) external;

    // Admin functions
    function setAuthorizedMinter(address minter, bool authorized) external;
    function setAuthorizedBurner(address burner, bool authorized) external;
    function setMaxSupply(uint256 newMaxSupply) external;
    function setDailyMintLimit(uint256 newLimit) external;
    function setDailyBurnLimit(uint256 newLimit) external;
    function setPsmDailyBurnLimit(uint256 newLimit) external;
    function setUCDToken(address newToken) external;

    // View functions
    function getCurrentSupply() external view returns (uint256);
    function getRemainingMintCapacity() external view returns (uint256);
    function getRemainingBurnCapacity() external view returns (uint256);
    function getRemainingPsmMintCapacity() external view returns (uint256);
    function getRemainingPsmBurnCapacity() external view returns (uint256);
    function isAuthorizedMinter(address account) external view returns (bool);
    function isAuthorizedBurner(address account) external view returns (bool);
    function authorizedMinters(address account) external view returns (bool);
    function authorizedBurners(address account) external view returns (bool);
    function burnedPerAddress(address account) external view returns (uint256);
    function totalMinted() external view returns (uint256);
    function totalBurned() external view returns (uint256);
    function maxSupply() external view returns (uint256);
    function dailyMintLimit() external view returns (uint256);
    function dailyBurnLimit() external view returns (uint256);
    function lastMintReset() external view returns (uint256);
    function lastBurnReset() external view returns (uint256);
    function dailyMinted() external view returns (uint256);
    function dailyBurned() external view returns (uint256);
    function dailyPsmMinted() external view returns (uint256);
    function psmDailyMintLimit() external view returns (uint256);
    function psmDailyBurnLimit() external view returns (uint256);
    function dailyPsmBurned() external view returns (uint256);
    function circuitBreaker() external view returns (address);
    function ucdToken() external view returns (address);
}

src/interfaces/IVersioned.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @dev Interface for version checking during upgrades
 */
interface IVersioned { 
    function VERSION() external view returns (string memory); 
}

src/libraries/BitcoinAddressValidator.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title BitcoinAddressValidator
 * @dev Comprehensive Bitcoin address validation library with proper cryptographic validation
 * @notice Implements BIP-173 (Bech32) and BIP-350 (Bech32m) for SegWit addresses,
 *         and proper Base58 with double SHA256 checksum validation for legacy addresses
 */
library BitcoinAddressValidator {
    // Bitcoin address type enumeration
    enum AddressType {
        INVALID,
        P2PKH,      // Legacy addresses starting with '1'
        P2SH,       // Script hash addresses starting with '3'
        P2WPKH,     // Native SegWit addresses starting with 'bc1'
        P2WSH,      // SegWit script hash addresses starting with 'bc1'
        P2TR        // Taproot addresses starting with 'bc1p'
    }

    // Network type enumeration
    enum NetworkType {
        INVALID,
        MAINNET,
        TESTNET,
        REGTEST
    }

    // Validation result structure
    struct ValidationResult {
        bool isValid;
        AddressType addressType;
        NetworkType networkType;
        string reason;
        bool checksumValid; // True if checksum validation passed, false if bypassed
    }

    // NOTE ON ALPHABET LOOKUPS: the Base58 alphabet
    //   "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
    // and the Bech32 alphabet
    //   "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
    // are deliberately NOT stored as `bytes constant`. Solidity re-copies a
    // reference-type constant into fresh memory on EVERY `.length`/`[i]` access,
    // so a per-character linear scan of a `bytes constant` alphabet costs
    // ~700k–1.1M gas per address validation (observed on mainnet). Instead,
    // char→value mapping uses the packed uint256 tables below: each packs 8-bit
    // entries for a contiguous ASCII range, where entry i (bits [8i, 8i+8)) is
    // the alphabet index of character (rangeStart + i), or 0xFF if that
    // character is not in the alphabet. Tables are value types → pure stack
    // ops, O(1) per character.

    /// @dev Bech32 values for ASCII 0x30–0x39 ('0'–'9'); 0xFF = invalid ('1', 'b', 'i', 'o' excluded per BIP-173).
    uint256 private constant BECH32_VALUES_0x30_0x39 =
        0x0000000000000000000000000000000000000000000005071E1A1415110AFF0F;
    /// @dev Bech32 values for ASCII 0x61–0x7A ('a'–'z'); 0xFF = invalid.
    uint256 private constant BECH32_VALUES_0x61_0x7A =
        0x0000000000000204060E0C1C0B10030001FF131B1F1612FF170809190D18FF1D;
    /// @dev Base58 digit values for ASCII 0x30–0x39 ('0'–'9'); '0' itself is invalid (0xFF).
    uint256 private constant BASE58_VALUES_0x30_0x39 =
        0x00000000000000000000000000000000000000000000080706050403020100FF;
    /// @dev Base58 digit values for ASCII 0x41–0x5A ('A'–'Z'); 'I' and 'O' are invalid (0xFF).
    uint256 private constant BASE58_VALUES_0x41_0x5A =
        0x000000000000201F1E1D1C1B1A19181716FF1514131211FF100F0E0D0C0B0A09;
    /// @dev Base58 digit values for ASCII 0x61–0x7A ('a'–'z'); 'l' is invalid (0xFF).
    uint256 private constant BASE58_VALUES_0x61_0x7A =
        0x000000000000393837363534333231302F2E2D2CFF2B2A292827262524232221;

    /// @dev Sentinel for "character not in alphabet" in the packed tables.
    uint8 private constant CHAR_NOT_IN_ALPHABET = 0xFF;

    uint8 private constant ASCII_0 = 0x30;
    uint8 private constant ASCII_9 = 0x39;
    uint8 private constant ASCII_UPPER_A_CODE = 0x41;
    uint8 private constant ASCII_UPPER_Z_CODE = 0x5A;
    uint8 private constant ASCII_LOWER_A_CODE = 0x61;
    uint8 private constant ASCII_LOWER_Z_CODE = 0x7A;

    // Bech32 generator polynomial for checksum calculation (kept for reference; polymod uses full 5-element GEN table)
    uint32 constant BECH32_GENERATOR = 0x3b6a57b2;

    // Bech32m generator polynomial for checksum calculation (kept for reference)
    uint32 constant BECH32M_GENERATOR = 0x2f8b4c1e;

    // Precomputed 256-bit bitmap: bit i is set if ASCII char i is a valid Base58 character.
    // Covers: '1'-'9' (0x31-0x39), 'A'-'H' (0x41-0x48), 'J'-'N' (0x4A-0x4E),
    //         'P'-'Z' (0x50-0x5A), 'a'-'k' (0x61-0x6B), 'm'-'z' (0x6D-0x7A).
    // Excludes '0','I','O','l'. All chars above ASCII 127 are never set.
    uint256 private constant BASE58_BITMAP =
        0x0000000000000000000000000000000007FFEFFE07FF7DFE03FE000000000000;

    // --- Validation bounds & magic values (replace bare literals for static analysis clarity) ---
    uint256 private constant MIN_ADDRESS_CHARS = 26;
    uint256 private constant MAX_ADDRESS_CHARS = 62;
    uint256 private constant MAX_LEGACY_ADDRESS_CHARS = 35;
    uint256 private constant LEGACY_DECODED_MIN_BYTES = 25;
    uint256 private constant BASE58_CHECKSUM_BYTES = 4;

    uint256 private constant BECH32_MIN_ADDRESS_CHARS = 14;
    uint256 private constant BECH32_MAX_ADDRESS_CHARS = 74;
    uint256 private constant BECH32_PREFIX_LEN_SHORT = 3;
    uint256 private constant BECH32_PREFIX_LEN_REGTEST = 5;
    uint256 private constant BECH32_SEPARATOR_MIN_INDEX = 2;
    uint256 private constant BECH32_MIN_TAIL_AFTER_SEP = 7;

    uint256 private constant BECH32_DATA_MIN_CHARS = 6;
    uint256 private constant BECH32_DATA_MAX_CHARS = 90;
    uint256 private constant WITNESS_V0_DATA_MIN_CHARS = 26;
    /// @dev Upper bound for Bech32 **payload** byte length (after HRP + `1`) for v0 witnesses; must fit long P2WSH (e.g. BIP-173 examples ~59 chars).
    uint256 private constant WITNESS_V0_DATA_MAX_CHARS = 65;
    uint256 private constant WITNESS_V0_P2WSH_LENGTH_THRESHOLD = 40;
    uint256 private constant WITNESS_V1_MIN_DATA_CHARS = 38;

    uint8 private constant INVALID_WITNESS_ENCODING = type(uint8).max;

    uint256 private constant HRP_MIN_CHARS = 1;
    uint256 private constant HRP_MAX_CHARS = 83;
    uint256 private constant BASE58_BITMAP_MAX_INDEX = 128;
    uint256 private constant BASE58_RADIX = 58;

    uint8 private constant BYTE_MASK = 0xff;
    uint8 private constant BITS_PER_BYTE = 8;

    uint32 private constant BECH32_POLYMOD_SHIFT = 25;
    uint32 private constant BECH32_POLYMOD_MASK = 0x1ffffff;
    uint8 private constant BECH32_POLYMOD_GEN_COUNT = 5;
    uint32 private constant BECH32_SUM_REMAINDER = 1;
    uint32 private constant BECH32M_SUM_REMAINDER = 0x2bc830a3;

    uint32 private constant BECH32_POLY_GEN_1 = 0x26508e6d;
    uint32 private constant BECH32_POLY_GEN_2 = 0x1ea119fa;
    uint32 private constant BECH32_POLY_GEN_3 = 0x3d4233dd;
    uint32 private constant BECH32_POLY_GEN_4 = 0x2a1462b3;

    bytes1 private constant ASCII_DIGIT_1 = 0x31; // '1' Bech32 separator & P2PKH prefix
    bytes1 private constant ASCII_DIGIT_2 = 0x32;
    bytes1 private constant ASCII_DIGIT_3 = 0x33;
    bytes1 private constant ASCII_LC_M = 0x6d;
    bytes1 private constant ASCII_LC_N = 0x6e;
    bytes1 private constant ASCII_LC_B = 0x62;
    bytes1 private constant ASCII_LC_C = 0x63;
    bytes1 private constant ASCII_LC_T = 0x74;
    bytes1 private constant ASCII_LC_R = 0x72;

    bytes1 private constant ASCII_MIN_PRINTABLE = 0x21;
    bytes1 private constant ASCII_MAX_PRINTABLE = 0x7e;
    bytes1 private constant ASCII_UPPER_A = 0x41;
    bytes1 private constant ASCII_UPPER_Z = 0x5a;
    uint8 private constant ASCII_UPPER_TO_LOWER_OFFSET = 0x20;

    bytes1 private constant BECH32_EXPAND_SEPARATOR = 0x00;
    uint8 private constant BECH32_HRP_LOW_MASK = 0x1f;
    uint8 private constant BECH32_CHAR_TO_VAL_SHIFT = 5;

    // Mainnet and testnet version bytes
    bytes1 constant MAINNET_P2PKH_VERSION = 0x00; // '1'
    bytes1 constant MAINNET_P2SH_VERSION = 0x05;  // '3'
    bytes1 constant TESTNET_P2PKH_VERSION = 0x6f; // 'm' or 'n'
    bytes1 constant TESTNET_P2SH_VERSION = 0xc4;  // '2'
    bytes1 constant REGTEST_P2PKH_VERSION = 0x6f; // 'm' or 'n'
    bytes1 constant REGTEST_P2SH_VERSION = 0xc4;  // '2'

    /**
     * @dev Validates a Bitcoin address and returns detailed information
     * @param btcAddress The Bitcoin address to validate
     * @return result Validation result with type and network information
     */
    // aderyn-fp-next-line(internal-function-used-once)
    function validateBitcoinAddress(string memory btcAddress) internal pure returns (ValidationResult memory result) {
        bytes memory addrBytes = bytes(btcAddress);
        
        // Basic length check
        if (addrBytes.length < MIN_ADDRESS_CHARS || addrBytes.length > MAX_ADDRESS_CHARS) {
            result.reason = "Invalid address length";
            result.checksumValid = true; // Not applicable for invalid length
            return result;
        }

        // Check for empty address
        if (addrBytes.length == 0) {
            result.reason = "Empty address";
            result.checksumValid = true; // Not applicable for empty address
            return result;
        }

        // Determine address type based on prefix
        if (addrBytes[0] == ASCII_DIGIT_1) { // '1'
            return _validateLegacyAddress(addrBytes, true);
        } else if (addrBytes[0] == ASCII_DIGIT_3) { // '3'
            return _validateLegacyAddress(addrBytes, false);
        } else if (addrBytes[0] == ASCII_LC_M || addrBytes[0] == ASCII_LC_N) { // 'm' or 'n'
            return _validateLegacyAddress(addrBytes, true);
        } else if (addrBytes[0] == ASCII_DIGIT_2) { // '2'
            return _validateLegacyAddress(addrBytes, false);
        } else if (addrBytes.length >= BECH32_PREFIX_LEN_SHORT &&
                   addrBytes[0] == ASCII_LC_B && addrBytes[1] == ASCII_LC_C && addrBytes[2] == ASCII_DIGIT_1) { // 'bc1'
            return _validateBech32Address(addrBytes);
        } else if (addrBytes.length >= BECH32_PREFIX_LEN_SHORT &&
                   addrBytes[0] == ASCII_LC_T && addrBytes[1] == ASCII_LC_B && addrBytes[2] == ASCII_DIGIT_1) { // 'tb1'
            return _validateBech32Address(addrBytes);
        } else if (addrBytes.length >= BECH32_PREFIX_LEN_REGTEST &&
                   addrBytes[0] == ASCII_LC_B && addrBytes[1] == ASCII_LC_C &&
                   addrBytes[2] == ASCII_LC_R && addrBytes[3] == ASCII_LC_T && addrBytes[4] == ASCII_DIGIT_1) { // 'bcrt1'
            return _validateBech32Address(addrBytes);
        } else {
            result.reason = "Unknown address format";
            result.checksumValid = true; // Not applicable for unknown format
            return result;
        }
    }

    /**
     * @dev Validates legacy Bitcoin addresses (P2PKH and P2SH) with proper Base58 decoding and checksum verification
     * @param addrBytes Address bytes
     * @param isP2PKH Whether this is a P2PKH address
     * @return result Validation result
     */
    function _validateLegacyAddress(bytes memory addrBytes, bool isP2PKH) internal pure returns (ValidationResult memory result) {
        // Check length constraints
        if (addrBytes.length < MIN_ADDRESS_CHARS || addrBytes.length > MAX_LEGACY_ADDRESS_CHARS) {
            result.reason = "Invalid legacy address length";
            result.checksumValid = true; // Not applicable for invalid length
            return result;
        }

        // Validate Base58 encoding
        if (!_isValidBase58(addrBytes)) {
            result.reason = "Invalid Base58 encoding";
            result.checksumValid = true; // Not applicable for invalid encoding
            return result;
        }

        // Decode Base58 address
        bytes memory decoded = _base58Decode(addrBytes);
        if (decoded.length == 0) {
            result.reason = "Base58 decode failed";
            result.checksumValid = true; // Not applicable for decode failure
            return result;
        }

        // Check minimum length (version + hash + checksum)
        if (decoded.length < LEGACY_DECODED_MIN_BYTES) {
            result.reason = "Decoded address too short";
            result.checksumValid = true; // Not applicable for too short
            return result;
        }

        // Verify checksum using double SHA256
        bool checksumValid = _verifyChecksum(decoded);
        result.checksumValid = checksumValid;

        if (!checksumValid) {
            result.isValid = false;
            result.reason = "Invalid checksum";
            return result;
        }

        // Determine network type
        bytes1 version = decoded[0];
        if (version == MAINNET_P2PKH_VERSION || version == MAINNET_P2SH_VERSION) {
            result.networkType = NetworkType.MAINNET;
        } else if (version == TESTNET_P2PKH_VERSION || version == TESTNET_P2SH_VERSION) {
            result.networkType = NetworkType.TESTNET;
        } else {
            // For production, we'll be more lenient with version bytes
            // This allows real Bitcoin addresses to pass even if version detection fails
            if (isP2PKH) {
                result.networkType = NetworkType.MAINNET; // Default to mainnet for P2PKH
            } else {
                result.networkType = NetworkType.MAINNET; // Default to mainnet for P2SH
            }
        }

        // Set address type
        result.addressType = isP2PKH ? AddressType.P2PKH : AddressType.P2SH;
        result.isValid = true;
        // checksumValid was already set above
        return result;
    }

    /**
     * @dev Validates Bech32/Bech32m addresses (SegWit and Taproot) with proper checksum validation
     * @param addrBytes Address bytes
     * @return result Validation result
     */
    function _validateBech32Address(bytes memory addrBytes) internal pure returns (ValidationResult memory result) {
        // Check minimum length for bech32
        if (addrBytes.length < BECH32_MIN_ADDRESS_CHARS || addrBytes.length > BECH32_MAX_ADDRESS_CHARS) {
            result.reason = "Invalid bech32 address length";
            result.checksumValid = true; // Not applicable for invalid length
            return result;
        }

        // Find separator position
        uint256 separatorPos = 0;
        for (uint256 i = 0; i < addrBytes.length; i++) {
            if (addrBytes[i] == ASCII_DIGIT_1) { // '1'
                separatorPos = i;
                break;
            }
        }

        if (separatorPos == 0 || separatorPos < BECH32_SEPARATOR_MIN_INDEX || separatorPos > addrBytes.length - BECH32_MIN_TAIL_AFTER_SEP) {
            result.reason = "Invalid bech32 separator";
            result.checksumValid = true; // Not applicable for invalid separator
            return result;
        }

        // Extract human-readable part and data part
        bytes memory hrp = new bytes(separatorPos);
        for (uint256 i = 0; i < separatorPos; i++) {
            hrp[i] = addrBytes[i];
        }

        bytes memory data = new bytes(addrBytes.length - separatorPos - 1);
        for (uint256 i = 0; i < data.length; i++) {
            data[i] = addrBytes[separatorPos + 1 + i];
        }

        // Validate human-readable part
        if (!_isValidHRP(hrp)) {
            result.reason = "Invalid human-readable part";
            result.checksumValid = true; // Not applicable for invalid HRP
            return result;
        }

        // Determine network type
        if (keccak256(hrp) == keccak256("bc")) {
            result.networkType = NetworkType.MAINNET;
        } else if (keccak256(hrp) == keccak256("tb")) {
            result.networkType = NetworkType.TESTNET;
        } else if (keccak256(hrp) == keccak256("bcrt")) {
            result.networkType = NetworkType.REGTEST;
        } else {
            result.reason = "Unknown network prefix";
            result.checksumValid = true; // Not applicable for unknown network
            return result;
        }

        // Validate data part
        if (!_isValidBech32Data(data)) {
            result.reason = "Invalid bech32 data";
            result.checksumValid = true; // Not applicable for invalid data
            return result;
        }

        // Determine address type based on witness version and length
        uint8 witnessVersion = INVALID_WITNESS_ENCODING; // default: invalid, set below if data.length > 0
        if (data.length > 0) {
            witnessVersion = _getWitnessVersion(data[0]);
            if (witnessVersion == 0) {
                // For v0, check data length (excluding checksum)
                if (data.length >= WITNESS_V0_DATA_MIN_CHARS && data.length <= WITNESS_V0_DATA_MAX_CHARS) { // P2WPKH or P2WSH
                    if (data.length <= WITNESS_V0_P2WSH_LENGTH_THRESHOLD) {
                        result.addressType = AddressType.P2WPKH;
                    } else {
                        result.addressType = AddressType.P2WSH;
                    }
                } else {
                    result.reason = "Invalid witness program length for v0";
                    result.checksumValid = true; // Not applicable for invalid length
                    return result;
                }
            } else if (witnessVersion == 1) {
                // For v1 (Taproot), check data length
                if (data.length >= WITNESS_V1_MIN_DATA_CHARS) { // P2TR
                    result.addressType = AddressType.P2TR;
                } else {
                    result.reason = "Invalid witness program length for v1";
                    result.checksumValid = true; // Not applicable for invalid length
                    return result;
                }
            } else {
                result.reason = "Unsupported witness version";
                result.checksumValid = true; // Not applicable for unsupported version
                return result;
            }
        }

        // Perform bech32/bech32m checksum validation, enforcing encoding per BIP-173/BIP-350:
        // v0 (P2WPKH, P2WSH) must use Bech32 (remainder == 1)
        // v1+ (Taproot) must use Bech32m (remainder == 0x2bc830a3)
        bool checksumValid = _verifyBech32Checksum(hrp, data, witnessVersion);
        result.checksumValid = checksumValid;

        if (!checksumValid) {
            result.isValid = false;
            result.reason = "Invalid bech32 checksum";
            return result;
        }

        result.isValid = true;
        // checksumValid was already set above
        return result;
    }

    /**
     * @dev Checks if string contains only valid Base58 characters
     * @param data String to check
     * @return bool True if valid Base58
     */
    function _isValidBase58(bytes memory data) internal pure returns (bool) {
        for (uint256 i = 0; i < data.length; i++) {
            uint256 b = uint8(data[i]);
            if (b >= BASE58_BITMAP_MAX_INDEX || (BASE58_BITMAP >> b) & 1 == 0) return false;
        }
        return true;
    }

    /**
     * @dev Checks if human-readable part is valid
     * @param hrp Human-readable part
     * @return bool True if valid
     */
    function _isValidHRP(bytes memory hrp) internal pure returns (bool) {
        if (hrp.length < HRP_MIN_CHARS || hrp.length > HRP_MAX_CHARS) {
            return false;
        }

        for (uint256 i = 0; i < hrp.length; i++) {
            bytes1 b = hrp[i];
            if (b < ASCII_MIN_PRINTABLE || b > ASCII_MAX_PRINTABLE) { // ASCII printable range
                return false;
            }
        }

        return true;
    }

    /**
     * @dev Checks if bech32 data part is valid
     * @param data Data part
     * @return bool True if valid
     */
    function _isValidBech32Data(bytes memory data) internal pure returns (bool) {
        if (data.length < BECH32_DATA_MIN_CHARS || data.length > BECH32_DATA_MAX_CHARS) {
            return false;
        }

        for (uint256 i = 0; i < data.length; i++) {
            if (_getWitnessVersion(data[i]) == INVALID_WITNESS_ENCODING) {
                return false;
            }
        }

        return true;
    }

    /**
     * @dev Gets witness version from bech32 data (properly decoded). Doubles as the
     *      general char→5-bit-value Bech32 decode: returns the character's index in
     *      the Bech32 alphabet via the packed lookup tables (O(1), stack-only), or
     *      {INVALID_WITNESS_ENCODING} (0xFF) if the character is not in the alphabet.
     *      Only canonical lowercase characters are valid, matching the alphabet.
     * @param firstByte First byte of data (witness version)
     * @return uint8 Witness version
     */
    function _getWitnessVersion(bytes1 firstByte) internal pure returns (uint8) {
        uint256 code = uint8(firstByte);
        if (code >= ASCII_0 && code <= ASCII_9) {
            return uint8((BECH32_VALUES_0x30_0x39 >> ((code - ASCII_0) << 3)) & BYTE_MASK);
        }
        if (code >= ASCII_LOWER_A_CODE && code <= ASCII_LOWER_Z_CODE) {
            return uint8((BECH32_VALUES_0x61_0x7A >> ((code - ASCII_LOWER_A_CODE) << 3)) & BYTE_MASK);
        }
        return INVALID_WITNESS_ENCODING; // Invalid
    }

    /**
     * @dev Verifies Base58 checksum using double SHA256
     * @param decoded Decoded address bytes
     * @return bool True if checksum is valid
     */
    function _verifyChecksum(bytes memory decoded) internal pure returns (bool) {
        if (decoded.length < BASE58_CHECKSUM_BYTES) {
            return false;
        }

        // Extract payload and checksum
        bytes memory payload = new bytes(decoded.length - BASE58_CHECKSUM_BYTES);
        bytes memory checksum = new bytes(BASE58_CHECKSUM_BYTES);

        for (uint256 i = 0; i < payload.length; i++) {
            payload[i] = decoded[i];
        }

        for (uint256 i = 0; i < BASE58_CHECKSUM_BYTES; i++) {
            checksum[i] = decoded[decoded.length - BASE58_CHECKSUM_BYTES + i];
        }

        // Calculate double SHA256 of payload
        bytes32 hash1 = sha256(payload);
        bytes32 hash2 = sha256(abi.encodePacked(hash1));

        // Compare with checksum
        for (uint256 i = 0; i < BASE58_CHECKSUM_BYTES; i++) {
            if (checksum[i] != bytes1(hash2[i])) {
                return false;
            }
        }

        return true;
    }

    /**
     * @dev Verifies bech32/bech32m checksum using proper BIP-173/BIP-350 algorithm
     * @param hrp Human-readable part
     * @param data Data part
     * @param witnessVersion Witness version (0 for P2WPKH/P2WSH, 1 for P2TR)
     * @return bool True if checksum is valid for the correct encoding per BIP-173/BIP-350
     * @notice v0 MUST use Bech32 (remainder == 1); v1+ MUST use Bech32m (remainder == 0x2bc830a3)
     */
    function _verifyBech32Checksum(bytes memory hrp, bytes memory data, uint8 witnessVersion) internal pure returns (bool) {
        if (data.length < BECH32_DATA_MIN_CHARS) {
            return false;
        }

        // Convert HRP to lowercase for checksum calculation
        bytes memory hrpLower = new bytes(hrp.length);
        for (uint256 i = 0; i < hrp.length; i++) {
            bytes1 b = hrp[i];
            if (b >= ASCII_UPPER_A && b <= ASCII_UPPER_Z) { // A-Z
                hrpLower[i] = bytes1(uint8(b) + ASCII_UPPER_TO_LOWER_OFFSET);
            } else {
                hrpLower[i] = b;
            }
        }

        // BIP-173 HRP expansion: [c >> 5 for c in hrp] + [0] + [c & 31 for c in hrp]
        // followed by the 5-bit values of each data character (decoded from Bech32 alphabet)
        bytes memory expanded = new bytes(2 * hrpLower.length + 1 + data.length);
        uint256 pos = 0;

        // High 3 bits of each HRP character
        for (uint256 i = 0; i < hrpLower.length; i++) {
            expanded[pos++] = bytes1(uint8(hrpLower[i]) >> BECH32_CHAR_TO_VAL_SHIFT);
        }

        // Zero separator
        expanded[pos++] = BECH32_EXPAND_SEPARATOR;

        // Low 5 bits of each HRP character
        for (uint256 i = 0; i < hrpLower.length; i++) {
            expanded[pos++] = bytes1(uint8(hrpLower[i]) & BECH32_HRP_LOW_MASK);
        }

        // Map each data character to its 5-bit Bech32 value using alphabet lookup
        for (uint256 i = 0; i < data.length; i++) {
            uint8 val = _getWitnessVersion(data[i]); // reuses alphabet index lookup; returns invalid sentinel for bad char
            if (val == INVALID_WITNESS_ENCODING) return false;
            expanded[pos++] = bytes1(val);
        }

        // Calculate polynomial remainder
        uint32 remainder = _bech32Polymod(expanded);

        // Enforce encoding type per BIP-173/BIP-350:
        // v0 (P2WPKH/P2WSH) MUST use Bech32 (remainder == 1)
        // v1+ (Taproot/P2TR) MUST use Bech32m (remainder == 0x2bc830a3)
        if (witnessVersion == 0) return remainder == BECH32_SUM_REMAINDER;
        return remainder == BECH32M_SUM_REMAINDER;
    }

    /**
     * @dev Calculates Bech32 polynomial remainder
     * @param values Input values
     * @return uint32 Polynomial remainder
     */
    function _bech32Polymod(bytes memory values) internal pure returns (uint32) {
        uint32 chk = 1;
        uint32[BECH32_POLYMOD_GEN_COUNT] memory GEN = [
            BECH32_GENERATOR,
            BECH32_POLY_GEN_1,
            BECH32_POLY_GEN_2,
            BECH32_POLY_GEN_3,
            BECH32_POLY_GEN_4
        ];

        for (uint256 i = 0; i < values.length; i++) {
            uint8 b = uint8(values[i]);
            uint32 top = chk >> BECH32_POLYMOD_SHIFT;
            chk = (chk & BECH32_POLYMOD_MASK) << BECH32_CHAR_TO_VAL_SHIFT ^ b;

            for (uint8 j = 0; j < BECH32_POLYMOD_GEN_COUNT; j++) {
                if ((top >> j) & 1 == 1) {
                    chk ^= GEN[j];
                }
            }
        }

        return chk;
    }

    /**
     * @dev O(1) Base58 char→digit decode via the packed lookup tables (stack-only).
     * @param c Character to decode
     * @return uint256 The character's index in the Base58 alphabet (0–57), or
     *         {CHAR_NOT_IN_ALPHABET} (0xFF) if it is not a valid Base58 character
     *         ('0', 'I', 'O', 'l' and all non-alphanumerics are invalid).
     */
    function _base58CharValue(bytes1 c) internal pure returns (uint256) {
        uint256 code = uint8(c);
        if (code >= ASCII_0 && code <= ASCII_9) {
            return (BASE58_VALUES_0x30_0x39 >> ((code - ASCII_0) << 3)) & BYTE_MASK;
        }
        if (code >= ASCII_UPPER_A_CODE && code <= ASCII_UPPER_Z_CODE) {
            return (BASE58_VALUES_0x41_0x5A >> ((code - ASCII_UPPER_A_CODE) << 3)) & BYTE_MASK;
        }
        if (code >= ASCII_LOWER_A_CODE && code <= ASCII_LOWER_Z_CODE) {
            return (BASE58_VALUES_0x61_0x7A >> ((code - ASCII_LOWER_A_CODE) << 3)) & BYTE_MASK;
        }
        return CHAR_NOT_IN_ALPHABET;
    }

    /**
     * @dev Full Base58 decoding with proper double SHA256 checksum validation
     * @param input Base58 encoded string
     * @return bytes Decoded bytes with validated checksum
     */
    function _base58Decode(bytes memory input) internal pure returns (bytes memory) {
        if (input.length == 0) {
            return new bytes(0);
        }

        // Count leading zeros (represented by '1' in Base58)
        uint256 leadingZeros = 0;
        for (uint256 i = 0; i < input.length && input[i] == ASCII_DIGIT_1; i++) {
            leadingZeros++;
        }

        // Convert Base58 to base256
        uint256[] memory digits = new uint256[](input.length);
        for (uint256 i = 0; i < input.length; i++) {
            uint256 digit = _base58CharValue(input[i]);
            if (digit == CHAR_NOT_IN_ALPHABET) {
                return new bytes(0); // Invalid Base58 character
            }
            digits[i] = digit;
        }

        // Convert from base58 to base256
        uint256 outputLength = 0;
        for (uint256 i = 0; i < input.length; i++) {
            uint256 carry = digits[i];
            for (uint256 j = 0; j < outputLength; j++) {
                carry += uint256(digits[j]) * BASE58_RADIX;
                digits[j] = carry & BYTE_MASK;
                carry >>= BITS_PER_BYTE;
            }
            while (carry > 0) {
                if (outputLength < digits.length) {
                    digits[outputLength++] = carry & BYTE_MASK;
                }
                carry >>= BITS_PER_BYTE;
            }
        }

        // Handle leading zeros
        for (uint256 i = 0; i < leadingZeros && outputLength > 0 && digits[outputLength - 1] == 0; i++) {
            outputLength--;
        }

        // Create output array
        bytes memory output = new bytes(leadingZeros + outputLength);
        for (uint256 i = 0; i < outputLength; i++) {
            if (leadingZeros + outputLength - 1 - i < output.length) {
                output[leadingZeros + outputLength - 1 - i] = bytes1(uint8(digits[i]));
            }
        }

        return output;
    }

    /**
     * @dev Simple validation function for basic use cases
     * @param btcAddress Bitcoin address to validate
     * @return bool True if address appears valid
     */
    function isValidBitcoinAddress(string memory btcAddress) internal pure returns (bool) {
        ValidationResult memory result = validateBitcoinAddress(btcAddress);
        return result.isValid;
    }

    /**
     * @dev Get address type as string
     * @param addressType Address type enum
     * @return string String representation
     */
    function getAddressTypeString(AddressType addressType) internal pure returns (string memory) {
        if (addressType == AddressType.P2PKH) return "P2PKH";
        if (addressType == AddressType.P2SH) return "P2SH";
        if (addressType == AddressType.P2WPKH) return "P2WPKH";
        if (addressType == AddressType.P2WSH) return "P2WSH";
        if (addressType == AddressType.P2TR) return "P2TR";
        return "INVALID";
    }

    /**
     * @dev Get network type as string
     * @param networkType Network type enum
     * @return string String representation
     */
    function getNetworkTypeString(NetworkType networkType) internal pure returns (string memory) {
        if (networkType == NetworkType.MAINNET) return "MAINNET";
        if (networkType == NetworkType.TESTNET) return "TESTNET";
        if (networkType == NetworkType.REGTEST) return "REGTEST";
        return "INVALID";
    }
}

src/libraries/ExtensionValidationHelper.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

import "../interfaces/IPositionManagerCore.sol";
import "../interfaces/ILoanOperationsManager.sol";
import "./PositionManagerErrors.sol";
import {LoanStatusLib} from "./LoanStatus.sol";
import "./SafeCalculations.sol";
import "./ProtocolConstants.sol";

/**
 * @title ExtensionValidationHelper
 * @dev Helper library for loan extension validation logic
 * @notice Provides reusable functions for extension timing, balance, and metrics validation
 */
library ExtensionValidationHelper {
    /**
     * @dev Calculate extension metrics (fee, debt, collateral ratio, term)
     * @param position Current position state
     * @param selectedTerm Extension term in months
     * @param btcPrice Bitcoin price (18 decimals)
     * @param availableBTCBalance Available BTC balance (in satoshis)
     * @param proRataRenewalFee Pro-rata renewal fee computed and signed by Lit Action (18 decimals)
     * @param loanOps Loan operations manager interface for liquidation threshold
     * @return extensionFee Fee charged for extension (equals proRataRenewalFee)
     * @return newTotalDebt Total debt after extension (current debt + fee)
     * @return newCollateralRatio Collateral ratio after extension
     * @return newTotalTerm Total term after extension (current + selected)
     * @notice Validates:
     *         - Current loan is not liquidatable
     *         - Post-extension loan remains solvent
     *         - New term doesn't exceed maximum
     * @notice The extension fee is computed by the Lit Action (pro-rata credit applied off-chain)
     *         and cryptographically committed to the extension signature. It is NOT trusted blindly:
     *         the caller `PositionManagerViews.validateExtensionMetrics` bounds it on-chain to
     *         `[expectedFresh - originationFeesPaidThisTerm, expectedFresh]` (H-4) before this
     *         library runs, where `expectedFresh = ucdDebt * extensionFeeBps / 1e4`. This library
     *         therefore assumes a pre-validated `proRataRenewalFee`.
     */
    function calculateExtensionMetrics(
        IPositionManagerCore.Position memory position,
        uint256 selectedTerm,
        uint256 btcPrice,
        uint256 availableBTCBalance,
        uint256 proRataRenewalFee,
        ILoanOperationsManager loanOps
    )
        internal
        view
        returns (
            uint256 extensionFee,
            uint256 newTotalDebt,
            uint256 newCollateralRatio,
            uint256 newTotalTerm
        )
    {
        // Extension fee is the pro-rata value signed by the Lit Action, already bounded to
        // [expectedFresh - originationFeesPaidThisTerm, expectedFresh] by the caller (H-4).
        extensionFee = proRataRenewalFee;

        // Calculate new total debt safely
        newTotalDebt = SafeCalculations.safeAdd(position.ucdDebt, extensionFee);

        // audit F3 (2026-07-03): enforce the per-position debt ceiling on the renewal path.
        // The renewal fee is minted fee-only (positionId == 0), which skips the cumulative
        // `debtAfterMint > maxLoanWei` check in UCDController._enforceLoanPathPerMintCap (M-3's
        // "the borrower leg already validated newDebt" premise does not hold on extendPosition —
        // there is no borrower leg). Without this, debt compounds past `maximumLoanValueUcd` on
        // each renewal, bounded only by solvency. This is the single on-chain site where the
        // renewal's newTotalDebt is known before any state write.
        uint256 maxLoanWei = loanOps.maximumLoanValueUcd() * ProtocolConstants.UCD_DECIMALS;
        if (newTotalDebt > maxLoanWei) {
            revert PositionManagerErrors.ExceedsMaxLoan();
        }

        // Use signed availableBTCBalance from Lit Action
        // This value is cryptographically bound to the extension authorization
        // It has been validated to match on-chain calculation in extendPosition()
        SafeCalculations.validateBounds(
            availableBTCBalance,
            btcPrice,
            newTotalDebt
        );
        uint256 collateralValue = SafeCalculations.safeCollateralValue(
            availableBTCBalance,
            btcPrice
        );

        // Get liquidation threshold from LoanOperationsManager
        uint256 liquidationThresholdValue = loanOps.liquidationThreshold();

        // Check current loan is not liquidatable
        if (
            SafeCalculations.isLiquidatable(
                collateralValue,
                position.ucdDebt,
                liquidationThresholdValue
            )
        ) {
            revert PositionManagerErrors.PositionLiquidatable();
        }

        // Check post-renewal loan remains solvent
        if (
            SafeCalculations.isLiquidatable(
                collateralValue,
                newTotalDebt,
                liquidationThresholdValue
            )
        ) {
            revert PositionManagerErrors.PositionWouldBecomeLiquidatable();
        }

        // Calculate new collateral ratio safely
        newCollateralRatio = SafeCalculations.safeCollateralRatio(
            collateralValue,
            newTotalDebt
        );

        // Calculate new total term
        newTotalTerm = uint256(position.selectedTerm) + selectedTerm;
        if (newTotalTerm > type(uint16).max)
            revert PositionManagerErrors.TermExceedsMaximum();
    }

    /**
     * @dev Validate extension timing constraints
     * @param position Current position state
     * @param selectedTerm Extension term in months
     * @param restrictionDisabled Whether the just-in-time renewal restriction is disabled for this
     *        chain. Defaults to false (restriction ENFORCED) on every chain; only a non-mainnet
     *        deployment can opt out — see PositionManager.setRenewalRestriction.
     * @notice Validates:
     *         - Active loans can only extend before expiry
     *         - H-5: Active loans (unless the restriction is disabled) can only renew once at
     *           least `currentTermDuration - 30 days` has elapsed since the last renewal. The
     *           window is measured from `lastRenewedAt`, not from `expiryAt`, so a borrower
     *           cannot chain multiple extensions inside a single renewal window.
     *         - Extensions can't exceed double term of remaining time (prevent stockpiling)
     *         - Expired loans must extend into the future
     */
    function validateExtensionTiming(
        IPositionManagerCore.Position memory position,
        uint256 selectedTerm,
        bool restrictionDisabled
    ) internal view {
        // Check if loan is not expired (for ACTIVE loans)
        if (position.status == LoanStatusLib.LoanStatus.ACTIVE) {
            if (block.timestamp > position.expiryAt) {
                revert PositionManagerErrors.ExtensionNotAllowed();
            }

            // H-5: just-in-time renewal window. Enforced by default; only a non-mainnet
            // deployment can disable it. Measured from the most recent renewal so that
            // chaining extensions across blocks/quanta cannot stockpile forward expiry.
            // EXPIRED loans intentionally skip this — they must be allowed to renew to
            // become current again (the 2*term runway check below still bounds them).
            if (!restrictionDisabled) {
                // lastRenewedAt is 0 for positions created before the H-5 upgrade; fall
                // back to createdAt (always non-zero) so legacy positions remain bound.
                uint256 effectiveLastRenewed = position.lastRenewedAt == 0
                    ? position.createdAt
                    : position.lastRenewedAt;

                uint256 currentTermDuration = position.selectedTerm == 12
                    ? 365 days
                    : uint256(position.selectedTerm) *
                        ProtocolConstants.SECONDS_PER_MONTH;

                // Renewal is only permitted in the final 30 days of the current term.
                // Terms of 30 days or less are intentionally unrestricted (window == 0).
                uint256 renewalWindow = currentTermDuration > 30 days
                    ? currentTermDuration - 30 days
                    : 0;

                if (block.timestamp - effectiveLastRenewed < renewalWindow) {
                    revert PositionManagerErrors.ExtensionNotAllowed();
                }
            }
        }

        // Extension adds to current expiry, but can't exceed double term period of runway
        uint256 currentTimestamp = block.timestamp;

        // Calculate term duration
        uint256 term = selectedTerm == 12
            ? 365 days
            : selectedTerm * ProtocolConstants.SECONDS_PER_MONTH;

        // Extension adds to CURRENT EXPIRY (not current timestamp)
        uint256 potentialExpiryDate = position.expiryAt + term;

        // Must extend into the future. This check is required before the subtraction below
        // to prevent an arithmetic underflow panic for deeply-expired loans where
        // expiryAt + term < block.timestamp (i.e. the term doesn't bring expiry past now).
        if (potentialExpiryDate <= currentTimestamp) {
            revert PositionManagerErrors.InvalidRequestedExpiryDate();
        }

        // Calculate remaining time if we extend
        uint256 potentialDifference = potentialExpiryDate - currentTimestamp;

        // Maximum allowed runway: double the term
        uint256 doubleTerm = term * 2;

        // Prevent stockpiling: can't have more than double term of remaining time
        if (potentialDifference > doubleTerm) {
            revert PositionManagerErrors.InvalidRequestedExpiryDate();
        }
    }
}

src/libraries/LoanStatus.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title LoanStatus
 * @dev Canonical loan lifecycle states for positions
 */
library LoanStatusLib {
    enum LoanStatus {
        PENDING_DEPOSIT,    // Loan created, awaiting BTC deposit
        PENDING_MINT,       // BTC deposited, awaiting UCD minting
        ACTIVE,             // UCD minted, loan is active
        EXPIRED,            // Loan passed expiry, in grace period
        LIQUIDATABLE,       // Under-collateralized, eligible for liquidation
        LIQUIDATED,         // Position has been liquidated
        REPAID,             // UCD debt repaid, awaiting BTC withdrawal
        CLOSED              // Position permanently closed
    }

    function toString(LoanStatus status) internal pure returns (string memory) {
        if (status == LoanStatus.PENDING_DEPOSIT) return "PENDING_DEPOSIT";
        if (status == LoanStatus.PENDING_MINT) return "PENDING_MINT";
        if (status == LoanStatus.ACTIVE) return "ACTIVE";
        if (status == LoanStatus.EXPIRED) return "EXPIRED";
        if (status == LoanStatus.LIQUIDATABLE) return "LIQUIDATABLE";
        if (status == LoanStatus.LIQUIDATED) return "LIQUIDATED";
        if (status == LoanStatus.REPAID) return "REPAID";
        if (status == LoanStatus.CLOSED) return "CLOSED";
        return "UNKNOWN";
    }
}


src/libraries/PositionManagerErrors.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title PositionManagerErrors
 * @dev Custom errors for PositionManager contract to reduce bytecode size
 * @notice Replaces string-based error messages with custom errors for gas efficiency
 */
library PositionManagerErrors {
    // General validation errors
    error InvalidPositionId();
    error InvalidPKPId();
    error InvalidAmount();
    error InvalidTerm();
    error InvalidAddress();

    // Position state errors
    error PositionNotFound();
    error PositionNotActive();
    error PositionAlreadyExists();
    error PositionNotEligibleForOperation();
    error PositionStatusInvalid();

    // Authorization errors
    error NotAuthorized();
    error NotBorrower();
    error NotLiquidator();
    /// @dev LIQUIDATED-position BTC release: caller has LIQUIDATOR_ROLE but is not registered PKP owner for the position
    error NotLiquidationPkpOwner();
    /// @dev Caller is not the registered AdminModule proxy on a module that gates admin functions with msg.sender == adminModule.
    error NotAdminModule();
    error InsufficientBalance();
    /// @dev OpenZeppelin `_grantRole` returned false (e.g. role already held) when a fresh grant was required.
    error UnexpectedRoleGrantFailure();

    // Business logic errors
    error CollateralRatioTooLow();
    error LoanAmountTooLow();
    error LoanAmountTooHigh();
    error ExtensionNotAllowed();
    error DebtNotZero();

    // System errors
    error InvalidBTCPrice();
    error CircuitBreakerTriggered();
    error ModuleCallFailed();
    error ValidationFailed();
    error IntegrityCheckFailed();

    // Extension specific errors
    error ExtensionFeeMintingFailed();
    error TermExceedsMaximum();
    error PositionLiquidatable();
    error PositionWouldBecomeLiquidatable();
    error InvalidRequestedExpiryDate();

    // Partial payment specific errors
    error PaymentAmountZero();
    error PaymentAmountTooLarge();

    // Balance confirmation specific errors
    error InvalidCollateralAmount();

    // Dynamic collateral specific errors
    error InsufficientCollateralForAmount();
    error CollateralRatioTooLargeForStorage();

    // Flash-loan / same-block interaction protection
    error SameBlockInteraction();

    /// @dev PositionManager granular liquidation pause (Option A) or dependent checks.
    error LiquidationsPaused();

    // Authorization registry errors
    error NoRegistry();
    error InvalidValidatorSignature();
    /// @dev setAuthorizationRegistry: passed address returns false on IS_PRODUCTION_REGISTRY() — likely a test bypass.
    error NotProductionRegistry();
    /// @dev setBTCSpendAuthorizer: passed address returns false on IS_PRODUCTION_AUTHORIZER() — likely a test bypass.
    error NotProductionAuthorizer();

    // Cross-contract reentrancy / operation lock errors
    error OperationInProgress();

    // Contract validation errors
    error NotContract(); // address has no deployed code

    // Network / mode errors
    error InvalidNetworkMode(); // BTC network string not "mainnet" or "regtest"
    error InvalidNetwork(); // wrong chainId for operation

    // PKP / vault address errors
    error PKPAlreadyUsed(); // PKP ID already registered
    error InvalidVaultAddress(); // Bitcoin vault address missing/malformed
    error InvalidPkpPublicKey(); // PKP public key missing or does not match pkpId-derived address

    // Term-start / timestamp errors
    error InvalidTermStartTime(); // term start too far in the past

    // Signature length error
    error InvalidSignatureLength(); // signature < 64 bytes or not 65 bytes

    // Circuit-breaker limit errors
    error ExceedsMaxLoan(); // UCD amount exceeds single-loan cap
    error AlreadyActive(); // circuit breaker already active
    error CircuitBreakerNotActive(); // circuit breaker not currently active
    error AlreadySigned(); // address already signed this proposal

    // Term-management errors
    error TermAlreadyExists(); // term months already registered
    error TermNotFound(); // term months not registered
    error FeeTooHigh(uint256 fee, uint256 max); // fee exceeds protocol cap
    error FeeTooLow(uint256 fee, uint256 min); // fee below independently-bounded floor
    error CannotRemoveLastTerm(); // must keep at least one term

    // Upgrade-validation errors
    error CannotUpgradeToSelf(); // new impl == current proxy address
    error SameImplementation(); // new impl == current implementation
    error MissingVersion(); // module does not expose VERSION()

    // H-2 fix: directional debt update verification errors
    error MintVerificationFailed(); // debt increase without corresponding UCD supply increase
    error MintVerificationMismatch(
        uint256 expectedSupply,
        uint256 currentSupply
    ); // mint supply mismatch diagnostics
    error BurnVerificationFailed(); // debt decrease without PositionManager holding sufficient UCD
}

src/libraries/ProtocolConstants.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title ProtocolConstants
 * @dev Centralized protocol-wide constants to improve code readability and maintainability
 * @notice This library defines commonly used magic numbers as named constants
 */
library ProtocolConstants {
    // =============================================================================
    // TIME CONSTANTS
    // =============================================================================

    /**
     * @dev Number of seconds in a month (standardized to 30 days for loan term calculations)
     * Used for converting month-based loan terms to seconds
     */
    uint256 internal constant SECONDS_PER_MONTH = 30 days;

    /**
     * @dev Seconds in one day
     */
    uint256 internal constant SECONDS_PER_DAY = 1 days;

    /**
     * @dev Seconds in one hour
     */
    uint256 internal constant SECONDS_PER_HOUR = 1 hours;

    // =============================================================================
    // DECIMAL CONSTANTS
    // =============================================================================

    /**
     * @dev UCD token decimals (18 decimals like standard ERC20)
     * Used for converting between whole UCD units and wei units
     */
    uint256 internal constant UCD_DECIMALS = 10**18;

    /**
     * @dev Bitcoin decimals (8 decimals = satoshis)
     * Used for BTC amount calculations and conversions
     */
    uint256 internal constant BTC_DECIMALS = 10**8;

    /**
     * @dev USD price feed decimals (8 decimals for Chainlink price feeds)
     */
    uint256 internal constant USD_PRICE_DECIMALS = 10**8;

    // =============================================================================
    // PERCENTAGE CONSTANTS
    // =============================================================================

    /**
     * @dev Basis points denominator (10000 = 100%)
     * Used for all percentage calculations in the protocol
     */
    uint256 internal constant BASIS_POINTS_DENOMINATOR = 1e4;

    /**
     * @dev Full percentage in basis points (100%)
     */
    uint256 internal constant FULL_PERCENTAGE_BPS = 1e4;

    // =============================================================================
    // VALIDATION CONSTANTS
    // =============================================================================

    /**
     * @dev Maximum total BTC supply (21 million BTC)
     * Used for sanity checks on BTC amounts
     */
    uint256 internal constant MAX_BTC_TOTAL_SUPPLY = 21e6 * BTC_DECIMALS;

    /**
     * @dev Extended maximum for protocol needs (25 million BTC)
     * Provides safety margin for validation
     */
    uint256 internal constant MAX_BTC_PROTOCOL_LIMIT = 25e6 * BTC_DECIMALS;

    // =============================================================================
    // BTC PRICE BOUNDS (8-decimal / Chainlink format)
    // =============================================================================

    /// @dev Absolute minimum BTC/USD price: $1,000 with 8 decimals. Single source of truth used
    ///      by InputValidation, SafeCalculations, and LoanOperationsManager.
    uint256 internal constant ABSOLUTE_MIN_BTC_PRICE_8DEC = 1_000 * USD_PRICE_DECIMALS;

    /// @dev Absolute maximum BTC/USD price: $100,000,000 with 8 decimals. Single source of truth
    ///      used by InputValidation, SafeCalculations, and LoanOperationsManager.
    uint256 internal constant ABSOLUTE_MAX_BTC_PRICE_8DEC = 1e8 * USD_PRICE_DECIMALS;

    // =============================================================================
    // HELPER FUNCTIONS
    // =============================================================================

    /**
     * @dev Convert months to seconds using standard 30-day months
     * @param months Number of months
     * @return uint256 Equivalent time in seconds
     */
    function monthsToSeconds(uint256 months) internal pure returns (uint256) {
        return months * SECONDS_PER_MONTH;
    }

    /**
     * @dev Calculate expiry timestamp from term start and selected term
     * @param termStartTimestamp When the term started
     * @param selectedTermMonths Loan term in months
     * @return uint256 Expiry timestamp
     * @notice For 12-month terms, uses 1 year (365 days) instead of 360 days
     */
    function calculateExpiryTimestamp(
        uint256 termStartTimestamp,
        uint256 selectedTermMonths
    ) internal pure returns (uint256) {
        // Special case: 12 months = 1 year (365 days)
        if (selectedTermMonths == 12) {
            return termStartTimestamp + 365 days;
        }
        // For other terms, use standard 30-day months
        return termStartTimestamp + (selectedTermMonths * SECONDS_PER_MONTH);
    }

    /**
     * @dev Convert whole UCD units to wei (18 decimal) units
     * @param ucdAmount Amount in whole UCD units
     * @return uint256 Amount in wei units
     */
    function ucdToWei(uint256 ucdAmount) internal pure returns (uint256) {
        return ucdAmount * UCD_DECIMALS;
    }

    /**
     * @dev Convert BTC units to satoshis
     * @param btcAmount Amount in whole BTC units
     * @return uint256 Amount in satoshis
     */
    function btcToSatoshis(uint256 btcAmount) internal pure returns (uint256) {
        return btcAmount * BTC_DECIMALS;
    }

    /**
     * @dev Convert wei (18 decimal) to whole UCD units
     * @param weiAmount Amount in wei units
     * @return uint256 Amount in whole UCD units
     */
    function weiToUcd(uint256 weiAmount) internal pure returns (uint256) {
        return weiAmount / UCD_DECIMALS;
    }

    /**
     * @dev Convert satoshis to whole BTC units
     * @param satoshis Amount in satoshis
     * @return uint256 Amount in whole BTC units
     */
    function satoshisToBtc(uint256 satoshis) internal pure returns (uint256) {
        return satoshis / BTC_DECIMALS;
    }
}

src/libraries/SafeCalculations.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

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

/**
 * @title SafeCalculations
 * @dev Library for overflow-safe mathematical operations in Diamond Hands Protocol
 * @notice Provides protection against integer overflow attacks in collateral and fee calculations
 */
library SafeCalculations {
    // Protocol constants
    uint256 public constant BASIS_POINTS = 1e4; // 100%

    // High-precision multiplier for intermediate calculations (18 decimal places).
    // Used to preserve sub-basis-point accuracy in ratio and fee calculations before
    // performing integer division, reducing truncation error.
    uint256 public constant PRECISION_MULTIPLIER = 1e18;

    /// @dev Converts satoshi × USD price (both 1e8 scaled) to 1e18 UCD: multiply by 1e10/1e8 (= 100).
    uint256 public constant COLLATERAL_VALUE_SCALE = 100;

    // Maximum safe values to prevent overflow attacks
    uint256 public constant MAX_BTC_AMOUNT = 21e6 * 1e8; // 21M BTC in satoshis
    /// @dev Aligned with ProtocolConstants.ABSOLUTE_MAX_BTC_PRICE_8DEC — single source of truth.
    uint256 public constant MAX_BTC_PRICE = ProtocolConstants.ABSOLUTE_MAX_BTC_PRICE_8DEC;
    uint256 public constant MAX_UCD_AMOUNT = 1e12 * 1e18; // $1T max UCD
    uint256 public constant MAX_FEE_RATE = 1e4; // 100% max fee rate

    // Pre-computed overflow-check bounds (avoids inline division on every call)
    /// @dev ceiling-division addend: BASIS_POINTS - 1, used in safeFeeRoundUp
    uint256 public constant CEILING_ADJUSTMENT = BASIS_POINTS - 1; // = 9999
    /// @dev max safe collateralValue before collateralValue * BASIS_POINTS overflows
    uint256 public constant MAX_RATIO_INPUT = type(uint256).max / BASIS_POINTS;
    /// @dev max safe collateralValue before collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER overflows
    uint256 public constant MAX_HEALTH_INPUT = type(uint256).max / BASIS_POINTS / PRECISION_MULTIPLIER;

    // Custom errors for gas efficiency
    error CollateralOverflow();
    error RatioOverflow();
    error FeeOverflow();
    error MultiplicationOverflow();
    error AdditionOverflow();
    error BtcAmountTooLarge();
    error BtcPriceTooHigh();
    error UcdAmountTooLarge();
    error FeeRateTooHigh();
    error DivisionByZero();
    /// @dev Emitted when a calculated result falls outside expected protocol bounds.
    error CalculationOutOfBounds(uint256 result, uint256 minExpected, uint256 maxExpected);

    /**
     * @dev Safely calculate collateral value from BTC amount and price
     * @param btcAmount BTC amount in satoshis
     * @param btcPrice BTC price in 1e8 format (USD) - e.g., 9112100000000 = $91,121
     * @return uint256 Collateral value in USD (1e18 format)
     */
    function safeCollateralValue(
        uint256 btcAmount,
        uint256 btcPrice
    ) internal pure returns (uint256) {
        // Input validation
        if (btcAmount > MAX_BTC_AMOUNT) revert BtcAmountTooLarge();
        if (btcPrice > MAX_BTC_PRICE) revert BtcPriceTooHigh();

        // Check for multiplication overflow before performing operation
        // Need to check: btcAmount * btcPrice * COLLATERAL_VALUE_SCALE
        if (
            btcAmount != 0 &&
            btcPrice > type(uint256).max / btcAmount / COLLATERAL_VALUE_SCALE
        ) {
            revert CollateralOverflow();
        }

        // Safe calculation: convert satoshis to BTC (1e8), multiply by price (1e8), scale to 1e18
        // Formula: (sats * price_e8 * 1e10) / 1e8 = (sats * price_e8 * COLLATERAL_VALUE_SCALE)
        // Example: (29500000 * 9112100000000 * COLLATERAL_VALUE_SCALE) = 26880445000000000000000 ≈ $26,880.45 (1e18)
        return (btcAmount * btcPrice * COLLATERAL_VALUE_SCALE);
    }

    /**
     * @dev Safely calculate collateral ratio
     * @param collateralValue USD value of collateral (1e18 format)
     * @param debtAmount Current debt amount (1e18 format)
     * @return uint256 Collateral ratio in basis points
     */
    function safeCollateralRatio(
        uint256 collateralValue,
        uint256 debtAmount
    ) internal pure returns (uint256) {
        if (debtAmount == 0) revert DivisionByZero();
        if (collateralValue > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();

        // Check for multiplication overflow: collateralValue * BASIS_POINTS
        if (collateralValue > MAX_RATIO_INPUT) {
            revert RatioOverflow();
        }

        return (collateralValue * BASIS_POINTS) / debtAmount;
    }

    /**
     * @dev Safely calculate loan amount from collateral and ratio
     * @param collateralValue USD value of collateral (1e18 format)
     * @param collateralRatio Desired collateral ratio in basis points
     * @return uint256 Maximum loan amount
     */
    function safeLoanAmount(
        uint256 collateralValue,
        uint256 collateralRatio
    ) internal pure returns (uint256) {
        if (collateralRatio == 0) revert DivisionByZero();
        if (collateralValue > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();

        // Check for multiplication overflow: collateralValue * BASIS_POINTS
        if (collateralValue > MAX_RATIO_INPUT) {
            revert RatioOverflow();
        }

        return (collateralValue * BASIS_POINTS) / collateralRatio;
    }

    /**
     * @dev Safely calculate origination fee
     * @param principal Loan principal amount
     * @param originationFeeRate Fee rate in basis points
     * @return uint256 Origination fee amount
     */
    function safeOriginationFee(
        uint256 principal,
        uint256 originationFeeRate
    ) internal pure returns (uint256) {
        if (principal > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();
        if (originationFeeRate > MAX_FEE_RATE) revert FeeRateTooHigh();

        // Check for multiplication overflow
        if (
            principal != 0 && originationFeeRate > type(uint256).max / principal
        ) {
            revert FeeOverflow();
        }

        return (principal * originationFeeRate) / BASIS_POINTS;
    }

    /**
     * @dev Safely calculate extension fee for loan renewals
     * @param principal Current loan principal
     * @param extensionFeeRate Extension fee rate in basis points
     * @return uint256 Extension fee amount
     */
    function safeExtensionFee(
        uint256 principal,
        uint256 extensionFeeRate
    ) internal pure returns (uint256) {
        if (principal > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();
        if (extensionFeeRate > MAX_FEE_RATE) revert FeeRateTooHigh();

        // Check for multiplication overflow
        if (
            principal != 0 && extensionFeeRate > type(uint256).max / principal
        ) {
            revert FeeOverflow();
        }

        return (principal * extensionFeeRate) / BASIS_POINTS;
    }

    /**
     * @dev Safely add two numbers with overflow protection
     * @param a First number
     * @param b Second number
     * @return uint256 Sum of a and b
     */
    function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            uint256 result = a + b;
            if (result < a) revert AdditionOverflow(); // Overflow check
            return result;
        }
    }

    /**
     * @dev Safely multiply two numbers with overflow protection
     * @param a First number
     * @param b Second number
     * @return uint256 Product of a and b
     */
    function safeMultiply(
        uint256 a,
        uint256 b
    ) internal pure returns (uint256) {
        if (a == 0) return 0;
        if (b > type(uint256).max / a) revert MultiplicationOverflow();
        return a * b;
    }

    /**
     * @dev Safely divide two numbers with zero protection
     * @param a Dividend
     * @param b Divisor
     * @return uint256 Quotient of a / b
     */
    function safeDivide(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) revert DivisionByZero();
        return a / b;
    }

    /**
     * @dev Validate that calculation inputs are within safe bounds
     * @param btcAmount BTC amount to validate
     * @param btcPrice BTC price to validate
     * @param ucdAmount UCD amount to validate
     */
    function validateBounds(
        uint256 btcAmount,
        uint256 btcPrice,
        uint256 ucdAmount
    ) internal pure {
        if (btcAmount > MAX_BTC_AMOUNT) revert BtcAmountTooLarge();
        if (btcPrice > MAX_BTC_PRICE) revert BtcPriceTooHigh();
        if (ucdAmount > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();
    }

    /**
     * @dev Calculate health factor safely for liquidation checks
     * @param collateralValue USD value of collateral
     * @param debtAmount Current debt amount
     * @param liquidationThreshold Liquidation threshold in basis points
     * @return uint256 Health factor (1e18 = 1.0, <1e18 = unhealthy)
     */
    function safeHealthFactor(
        uint256 collateralValue,
        uint256 debtAmount,
        uint256 liquidationThreshold
    ) internal pure returns (uint256) {
        if (debtAmount == 0) return type(uint256).max; // No debt = infinite health
        if (liquidationThreshold == 0) revert DivisionByZero();

        // Prevent overflow in: collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER
        if (collateralValue > MAX_HEALTH_INPUT) {
            revert RatioOverflow();
        }

        // Precision fix: compute the full numerator before dividing.
        // Old approach (precision loss):
        //   liquidationValue = (collateralValue * BASIS_POINTS) / liquidationThreshold   ← truncates here
        //   return (liquidationValue * PRECISION_MULTIPLIER) / debtAmount
        //
        // New approach (no intermediate truncation):
        //   numerator = collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER
        //   denominator = liquidationThreshold * debtAmount
        //   health = numerator / denominator
        //
        // This preserves 18 decimal places of precision in the final result.
        uint256 numerator = collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER;
        if (liquidationThreshold > type(uint256).max / debtAmount) revert RatioOverflow();
        uint256 denominator = liquidationThreshold * debtAmount;
        return numerator / denominator;
    }

    /**
     * @dev Safely check if position is liquidatable
     * @param collateralValue USD value of collateral
     * @param debtAmount Current debt amount
     * @param liquidationThreshold Liquidation threshold in basis points
     * @return bool True if position can be liquidated
     */
    function isLiquidatable(
        uint256 collateralValue,
        uint256 debtAmount,
        uint256 liquidationThreshold
    ) internal pure returns (bool) {
        if (debtAmount == 0) return false; // No debt = not liquidatable

        // Same bounds as safeCollateralRatio; compare via cross-product to avoid an extra
        // internal call (floor(collateral*BPS/debt) < T  iff  collateral*BPS < T*debt).
        if (collateralValue > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();
        if (collateralValue > MAX_RATIO_INPUT) revert RatioOverflow();
        if (liquidationThreshold > type(uint256).max / debtAmount) revert RatioOverflow();

        return (collateralValue * BASIS_POINTS) <
            (liquidationThreshold * debtAmount);
    }

    /**
     * @dev Calculate collateral ratio scaled by PRECISION_MULTIPLIER to preserve sub-basis-point accuracy.
     * @param collateralValue USD value of collateral (1e18 format)
     * @param debtAmount Current debt amount (1e18 format)
     * @return uint256 Ratio = (collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER) / debtAmount.
     *                 Divide by PRECISION_MULTIPLIER to recover the standard basis-point ratio.
     * @notice Use this instead of safeCollateralRatio when the result feeds into a comparison that
     *         could be affected by rounding (e.g., checking proximity to a liquidation threshold).
     */
    function safePrecisionCollateralRatio(
        uint256 collateralValue,
        uint256 debtAmount
    ) internal pure returns (uint256) {
        if (debtAmount == 0) revert DivisionByZero();
        if (collateralValue > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();

        // Overflow check: collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER
        if (collateralValue > MAX_HEALTH_INPUT) {
            revert RatioOverflow();
        }

        return (collateralValue * BASIS_POINTS * PRECISION_MULTIPLIER) / debtAmount;
    }

    /**
     * @dev Calculate a fee using ceiling (round-up) division.
     * @param principal Loan principal amount
     * @param feeRate Fee rate in basis points
     * @return uint256 Fee amount rounded up to the nearest wei.
     * @notice Prevents systematic under-collection caused by truncating floor division.
     *         Use this for protocol-side fee collection; safeOriginationFee/safeExtensionFee
     *         round down (favour borrower) which may be intentional for UX reasons.
     */
    function safeFeeRoundUp(
        uint256 principal,
        uint256 feeRate
    ) internal pure returns (uint256) {
        if (principal > MAX_UCD_AMOUNT) revert UcdAmountTooLarge();
        if (feeRate > MAX_FEE_RATE) revert FeeRateTooHigh();
        if (principal == 0 || feeRate == 0) return 0;

        if (feeRate > type(uint256).max / principal) revert FeeOverflow();

        uint256 numerator = principal * feeRate;
        // Ceiling division: (a + d - 1) / d  where d = BASIS_POINTS
        return (numerator + CEILING_ADJUSTMENT) / BASIS_POINTS;
    }

    /**
     * @dev Assert that a calculation result lies within expected protocol bounds.
     * @param result The calculated value to validate
     * @param minExpected Minimum acceptable value (inclusive)
     * @param maxExpected Maximum acceptable value (inclusive)
     * @notice Reverts with CalculationOutOfBounds if the result is out of range.
     *         Use this as a post-condition check for critical financial calculations.
     */
    function verifyCalculationBounds(
        uint256 result,
        uint256 minExpected,
        uint256 maxExpected
    ) internal pure {
        if (result < minExpected || result > maxExpected) {
            revert CalculationOutOfBounds(result, minExpected, maxExpected);
        }
    }

    /**
     * @dev Calculate maximum borrowable amount based on collateral and borrow cap ratio.
     * @param collateralValue USD value of Bitcoin collateral
     * @param maxBorrowRatioBps Maximum borrow ratio in basis points (debt/collateral value)
     * @return uint256 Maximum UCD that can be borrowed
     */
    function safeMaxBorrow(
        uint256 collateralValue,
        uint256 maxBorrowRatioBps
    ) internal pure returns (uint256) {
        if (maxBorrowRatioBps == 0) return 0;
        if (maxBorrowRatioBps > BASIS_POINTS) revert FeeRateTooHigh();

        // Check for overflow before multiplication
        if (collateralValue > type(uint256).max / maxBorrowRatioBps) {
            revert MultiplicationOverflow();
        }

        return (collateralValue * maxBorrowRatioBps) / BASIS_POINTS;
    }
}

src/roles/Roles.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;

/**
 * @title Roles
 * @dev Centralized role definitions for Diamond Hands Protocol
 * @notice Single source of truth for all access control roles across the protocol
 * @custom:security-note This library prevents role drift between contracts
 *
 * Removed roles (pre-mainnet cleanup, 2026-05-26):
 *   - UPGRADER_ROLE         — never used; upgrades flow through AdminModule's onlyAdminModule gate.
 *   - EMERGENCY_ROLE        — declared PSM-specific but never wired in SimplePSMV2.
 *   - CONTROLLER_ROLE       — never used.
 *   - PROOF_VALIDATOR_ROLE  — BTCProofValidator was removed from the protocol.
 *   - LIT_PROTOCOL_ROLE     — removed in LITActionValidator v2.3.0 (M-03).
 *   - TIMELOCK_ADMIN_ROLE   — protocol uses AdminModule's own timelock, not OZ TimelockController.
 *   - PROPOSER_ROLE         — same: AdminModule has its own propose/sign/execute machinery.
 *   - EXECUTOR_ROLE         — same.
 *   - CANCELLER_ROLE        — same.
 *
 * The string names are still referenced in `scripts/shared/snapshot-access-control-roles.ts`
 * and `scripts/shared/rotate-default-admin-role.ts` to discover any legacy holders during
 * audit sweeps. Keep those scripts pointed at the strings, not at these constants.
 */
library Roles {
    // =============================================================================
    // CORE ADMINISTRATIVE ROLES
    // =============================================================================

    /// @dev OpenZeppelin default admin role (super admin)
    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /// @dev Standard admin role for contract management
    bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");

    /// @dev Emergency pause role for critical security events
    bytes32 public constant EMERGENCY_PAUSE_ROLE = keccak256("EMERGENCY_PAUSE_ROLE");

    // =============================================================================
    // TOKEN & MINTING ROLES
    // =============================================================================

    /// @dev Role for minting UCD tokens
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");

    /// @dev Role for burning UCD tokens
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");

    // =============================================================================
    // POSITION & LIQUIDATION ROLES
    // =============================================================================

    /// @dev Role for liquidating undercollateralized positions
    bytes32 public constant LIQUIDATOR_ROLE = keccak256("LIQUIDATOR_ROLE");

    // =============================================================================
    // PROOF & VALIDATION ROLES
    // =============================================================================

    /// @dev Role for upgrade validation operations
    bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE");

    // =============================================================================
    // LIT PROTOCOL & PKP ROLES
    // =============================================================================

    /// @dev Role for PKP registry management
    bytes32 public constant PKP_REGISTRY_ROLE = keccak256("PKP_REGISTRY_ROLE");

    // =============================================================================
    // SYSTEM INTEGRATION ROLES
    // =============================================================================

    /// @dev Role for authorized contract interactions
    bytes32 public constant AUTHORIZED_CONTRACT_ROLE = keccak256("AUTHORIZED_CONTRACT_ROLE");

    /// @dev Registrar role. Grants are per-contract, and blast radii differ by consumer:
    ///      - ContractVersionRegistry: legacy — retained on the ABI, but `register` is
    ///        `onlyAdminModule` since v1.4.0 (H-3), so the role controls nothing there.
    ///      - The agent/delegate registries (AgentDelegateRegistryBase and its concrete
    ///        registries, PositionDelegateRegistry): see each contract's NatSpec. Hold it on a
    ///        dedicated ops Safe (mainnet threshold >= 2), never an EOA.
    ///      (CarryAgentRegistry, a former consumer, was retired 2026-09-26.)
    bytes32 public constant REGISTRAR_ROLE = keccak256("REGISTRAR_ROLE");

    // =============================================================================
    // TIMELOCK & GOVERNANCE ROLES
    // =============================================================================

    /// @dev Role held by AdminModule for timelocked limit changes on CircuitBreaker/TermManager
    bytes32 public constant ADMIN_MODULE_ROLE = keccak256("ADMIN_MODULE_ROLE");
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "none"
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "london"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.