{"sources":{"src/core/MonetrixVault.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"../tokens/USDM.sol\";\nimport \"../tokens/sUSDM.sol\";\nimport \"./MonetrixConfig.sol\";\nimport \"./InsuranceFund.sol\";\nimport \"../interfaces/IHyperCore.sol\";\nimport \"../interfaces/HyperCoreConstants.sol\";\nimport \"../interfaces/IMonetrixAccountant.sol\";\nimport \"../interfaces/IRedeemEscrow.sol\";\nimport \"../interfaces/IYieldEscrow.sol\";\nimport \"./ActionEncoder.sol\";\nimport \"./PrecompileReader.sol\";\nimport \"./TokenMath.sol\";\nimport \"./MonetrixAccountant.sol\";\nimport {MonetrixGovernedUpgradeable} from \"../governance/MonetrixGovernedUpgradeable.sol\";\n\n/// @title MonetrixVault - Core vault managing USDC deposits, USDM minting, redemption queue, and L1 hedge execution\n/// @dev Role mapping (via shared MonetrixAccessController):\n///      - GUARDIAN: pause / unpause / pauseOperator / unpauseOperator (delay=0)\n///      - OPERATOR: bridge / hedge / HLP / yield-distribution (delay=0)\n///      - GOVERNOR: set* / emergency* (24h timelock)\n///      - UPGRADER: _authorizeUpgrade (48h timelock, inherited from base)\n/// @dev Two-dimensional pause:\n///      - `paused` (OZ Pausable): user fund I/O — deposit, redeem claim, outflow paths.\n///      - `operatorPaused` (custom):    all operator-driven mutations (hedge/HLP/BLP/bridges/yield).\n///      Outflow functions (`keeperBridge`, `settle`, `distributeYield`) are gated by BOTH.\ncontract MonetrixVault is PausableUpgradeable, ReentrancyGuard, MonetrixGovernedUpgradeable {\n    using SafeERC20 for IERC20;\n\n    enum BridgeTarget { Vault, Multisig }\n\n    // ═══════════════════════════════════════════════════════════\n    //                      STATE\n    // ═══════════════════════════════════════════════════════════\n\n    // ─── Core references ────────────────────────────────────\n    IERC20 public usdc;\n    USDM public usdm;\n    sUSDM public susdm;\n    MonetrixConfig public config;\n    address public coreDepositWallet;\n    address public accountant;\n    address public multisigVault;\n    address public redeemEscrow;\n    address public yieldEscrow;\n\n    // ─── Operational state ──────────────────────────────────\n    bool public hlpDepositEnabled;\n    bool public multisigVaultEnabled;\n    uint256 public lastBridgeTimestamp;\n\n    // ─── L1 principal tracking ───────────────────────────────\n    uint256 public outstandingL1Principal;\n    uint256 public bridgeRetentionAmount;\n\n    // ─── Redeem queue ───────────────────────────────────────\n    /// @dev 2-slot layout without exotic bit widths. `owner` (160 bits) +\n    ///      `cooldownEnd` (64 bits) packs into slot 0 (224/256 used); amount\n    ///      takes the full uint256 slot 1 — same storage cost as the former\n    ///      uint152/uint104 packing, but no truncation risk on usdmAmount.\n    struct RedeemRequest {\n        address owner;        // slot 0 ┐\n        uint64  cooldownEnd;  // slot 0 ┘\n        uint256 usdmAmount;   // slot 1\n    }\n\n    uint256 public nextRedeemId;\n    mapping(uint256 => RedeemRequest) public redeemRequests;\n    mapping(address => uint256[]) private _userRedeemIds;\n\n    /// @notice PM activation flag for Vault's L1 account; when true, `_sendL1Bridge` counts 0x811 supplied.\n    bool public pmEnabled;\n\n    /// @notice Operator-side pause (independent of `paused`). When true, blocks every operator-driven\n    ///         mutation (hedge/HLP/BLP/bridges/yield/escrow routing). User-facing functions keep\n    ///         their own `whenNotPaused` gate and are unaffected.\n    bool public operatorPaused;\n\n    uint256[50] private __gap;\n\n    // ─── Events ─────────────────────────────────────────────\n    event Deposited(address indexed user, uint256 amount);\n    event RedeemRequested(uint256 indexed requestId, address indexed owner, uint256 usdmAmount, uint256 cooldownEnd);\n    event RedeemClaimed(uint256 indexed requestId, address indexed owner, address indexed recipient, uint256 usdmAmount);\n    event BridgedToL1(uint256 amount);\n    event PrincipalBridgedFromL1(uint256 amount);\n    event YieldBridgedFromL1(uint256 amount);\n    event YieldCollected(uint256 amount);\n    event YieldDistributed(uint256 totalYield, uint256 userShare, uint256 insuranceShare, uint256 foundationShare);\n    event HedgeExecuted(uint256 indexed batchId, uint32 spotAsset, uint32 perpAsset, uint64 size);\n    event HedgeClosed(uint256 indexed positionId, uint32 spotAsset, uint64 size);\n    event HedgeRepaired(uint256 indexed positionId, uint16 residualBps);\n    event HlpDeposited(uint64 usdAmount);\n    event HlpWithdrawn(uint64 usdAmount);\n    event HlpDepositEnabledUpdated(bool enabled);\n    event RedemptionsFunded(uint256 amount);\n    event RedeemEscrowReclaimed(uint256 amount);\n    event EmergencyActionSent(address indexed sender, bytes32 dataHash);\n    event AccountantUpdated(address newAccountant);\n    event MultisigVaultUpdated(address newMultisigVault);\n    event RedeemEscrowUpdated(address redeemEscrow);\n    event YieldEscrowUpdated(address yieldEscrow);\n    event BridgeRetentionAmountUpdated(uint256 amount);\n    event PmEnabledUpdated(bool enabled);\n    event BlpSupplied(uint64 indexed token, uint64 l1Amount);\n    event BlpWithdrawn(uint64 indexed token, uint64 l1Amount);\n    event OperatorPaused(address indexed by);\n    event OperatorUnpaused(address indexed by);\n\n\n\n    // ═══════════════════════════════════════════════════════════\n    //                    INITIALIZER\n    // ═══════════════════════════════════════════════════════════\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(\n        address _usdc,\n        address _usdm,\n        address _susdm,\n        address _config,\n        address _coreDepositWallet,\n        address _acl\n    ) external initializer {\n        require(_usdc != address(0) && _usdm != address(0) && _susdm != address(0), \"zero token\");\n        require(_config != address(0) && _coreDepositWallet != address(0), \"zero dep\");\n\n        __Pausable_init();\n        __Governed_init(_acl);\n\n        usdc = IERC20(_usdc);\n        usdm = USDM(_usdm);\n        susdm = sUSDM(_susdm);\n        config = MonetrixConfig(_config);\n        coreDepositWallet = _coreDepositWallet;\n        hlpDepositEnabled = true;\n    }\n\n    \n    // ═══════════════════════════════════════════════════════════\n    //                      MODIFIER\n    // ═══════════════════════════════════════════════════════════\n\n    modifier requireWired() {\n        require(accountant != address(0) && redeemEscrow != address(0) && yieldEscrow != address(0), \"not wired\");\n        _;\n    }\n\n    modifier whenOperatorNotPaused() {\n        require(!operatorPaused, \"operator paused\");\n        _;\n    }\n\n    // ═══════════════════════════════════════════════════════════\n    //                   USER OPERATIONS\n    // ═══════════════════════════════════════════════════════════\n\n    function deposit(uint256 amount) external nonReentrant whenNotPaused {\n        require(\n            amount >= config.minDepositAmount() && amount <= config.maxDepositAmount(),\n            \"deposit out of range\"\n        );\n        uint256 maxTVL = config.maxTVL();\n        if (maxTVL > 0) {\n            require(usdm.totalSupply() + amount <= maxTVL, \"TVL cap exceeded\");\n        }\n        usdc.safeTransferFrom(msg.sender, address(this), amount);\n        usdm.mint(msg.sender, amount);\n        emit Deposited(msg.sender, amount);\n    }\n\n    function requestRedeem(uint256 usdmAmount) external nonReentrant whenNotPaused requireWired returns (uint256 requestId) {\n        require(usdmAmount > 0, \"zero amount\");\n        IERC20(address(usdm)).safeTransferFrom(msg.sender, address(this), usdmAmount);\n        IRedeemEscrow(redeemEscrow).addObligation(usdmAmount);\n\n        requestId = nextRedeemId++;\n        redeemRequests[requestId] = RedeemRequest({\n            owner: msg.sender,\n            cooldownEnd: SafeCast.toUint64(block.timestamp + config.redeemCooldown()),\n            usdmAmount: usdmAmount\n        });\n        _userRedeemIds[msg.sender].push(requestId);\n        emit RedeemRequested(requestId, msg.sender, usdmAmount, block.timestamp + config.redeemCooldown());\n    }\n\n    function claimRedeem(uint256 requestId) external nonReentrant whenNotPaused requireWired {\n        _claimRedeemTo(requestId, msg.sender);\n    }\n\n    /// @notice Claim a matured redeem, paying out to `recipient` instead of `msg.sender`.\n    /// @dev Escape hatch for an owner whose own address can no longer receive USDC\n    ///      (e.g. Circle blacklist). Still owner-gated; only redirects the payout target.\n    function claimRedeemTo(uint256 requestId, address recipient) external nonReentrant whenNotPaused requireWired {\n        _claimRedeemTo(requestId, recipient);\n    }\n\n    function _claimRedeemTo(uint256 requestId, address recipient) internal {\n        require(recipient != address(0), \"zero recipient\");\n        RedeemRequest memory req = redeemRequests[requestId];\n        require(\n            req.usdmAmount > 0\n                && msg.sender == req.owner\n                && block.timestamp >= req.cooldownEnd,\n            \"invalid claim\"\n        );\n        uint256 amount = req.usdmAmount;\n        delete redeemRequests[requestId];\n        _removeUserRedeemId(req.owner, requestId);\n\n        usdm.burn(amount);\n        IRedeemEscrow(redeemEscrow).payOut(recipient, amount);\n        emit RedeemClaimed(requestId, req.owner, recipient, amount);\n    }\n\n    // ═══════════════════════════════════════════════════════════\n    //                 OPERATOR OPERATIONS\n    // ═══════════════════════════════════════════════════════════\n\n    // ─── Bridge (EVM ↔ L1) ──────────────────────────────────\n    // NOTE: Once the vault contract account supports Portfolio Margin,\n    // all positions will be held by the vault directly and multisigVault\n    // will be disabled.\n    function keeperBridge(BridgeTarget target) external onlyOperator requireWired whenNotPaused whenOperatorNotPaused {\n        require(block.timestamp >= lastBridgeTimestamp + config.bridgeInterval(), \"too early\");\n        uint256 amount = netBridgeable();\n        require(amount > 0, \"nothing to bridge\");\n        address recipient = (target == BridgeTarget.Multisig && multisigVaultEnabled && multisigVault != address(0))\n            ? multisigVault\n            : address(this);\n        outstandingL1Principal += amount;\n        lastBridgeTimestamp = block.timestamp;\n        usdc.forceApprove(coreDepositWallet, amount);\n        ICoreDepositWallet(coreDepositWallet).depositFor(recipient, amount, HyperCoreConstants.SPOT_DEX);\n        emit BridgedToL1(amount);\n    }\n\n    function bridgePrincipalFromL1(uint256 amount) external onlyOperator requireWired whenOperatorNotPaused {\n        require(\n            amount > 0 && amount <= redemptionShortfall() && amount <= outstandingL1Principal,\n            \"invalid bridge amount\"\n        );\n        outstandingL1Principal -= amount;\n        _sendL1Bridge(amount);\n        emit PrincipalBridgedFromL1(amount);\n    }\n\n    function bridgeYieldFromL1(uint256 amount) external onlyOperator requireWired whenOperatorNotPaused {\n        require(amount > 0, \"zero amount\");\n        require(amount <= yieldShortfall(), \"yield shortfall\");\n        _sendL1Bridge(amount);\n        emit YieldBridgedFromL1(amount);\n    }\n\n    // ─── Hedge execution ────────────────────────────────────\n\n    function executeHedge(uint256 batchId, ActionEncoder.HedgeParams calldata params)\n        external\n        onlyOperator\n        whenOperatorNotPaused\n    {\n        require(params.size > 0, \"zero size\");\n        _requireHedgePair(params.perpAsset, params.spotAsset);\n\n        ActionEncoder.sendBuySpot(params);\n        ActionEncoder.sendShortPerp(params);\n\n        // Under PM, Vault's new spot balance auto-supplies into 0x811 → register\n        // so Accountant's strict supplied reads don't revert. Notify with HL token_index\n        // (from Config), NOT `params.spotAsset` (which is pair_asset_id).\n        if (pmEnabled && accountant != address(0)) {\n            uint64 spotToken = uint64(config.perpToSpot(params.perpAsset));\n            MonetrixAccountant(accountant).notifyVaultSupply(spotToken, params.perpAsset);\n        }\n\n        emit HedgeExecuted(batchId, params.spotAsset, params.perpAsset, params.size);\n    }\n\n    function closeHedge(ActionEncoder.CloseParams calldata params) external onlyOperator whenOperatorNotPaused {\n        _requireHedgePair(params.perpAsset, params.spotAsset);\n\n        ActionEncoder.sendSellSpot(params);\n        ActionEncoder.sendClosePerp(params);\n\n        emit HedgeClosed(params.positionId, params.spotAsset, params.size);\n    }\n\n    function repairHedge(uint256 positionId, ActionEncoder.RepairParams calldata params)\n        external\n        onlyOperator\n        whenOperatorNotPaused\n    {\n        _requireRepairAsset(params.asset, params.isPerp);\n\n        ActionEncoder.sendRepairAction(params);\n\n        emit HedgeRepaired(positionId, params.residualBps);\n    }\n\n    // ─── HLP strategy ───────────────────────────────────────\n\n    function depositToHLP(uint64 usdAmount) external onlyOperator whenOperatorNotPaused {\n        require(usdAmount > 0, \"zero amount\");\n        require(hlpDepositEnabled, \"HLP deposit frozen\");\n\n        ActionEncoder.sendVaultDeposit(HyperCoreConstants.HLP_VAULT, usdAmount);\n        emit HlpDeposited(usdAmount);\n    }\n\n    function setHlpDepositEnabled(bool enabled) external onlyOperator whenOperatorNotPaused {\n        hlpDepositEnabled = enabled;\n        emit HlpDepositEnabledUpdated(enabled);\n    }\n\n    function withdrawFromHLP(uint64 usdAmount) external onlyOperator whenOperatorNotPaused {\n        require(usdAmount > 0, \"zero amount\");\n\n        PrecompileReader.VaultEquity memory eq =\n            PrecompileReader.vaultEquity(address(this), HyperCoreConstants.HLP_VAULT);\n        require(uint256(usdAmount) <= uint256(eq.equity), \"exceeds hlp equity\");\n        // `lockedUntil` is ms-epoch; L1 silently drops withdraws during lock.\n        require(\n            block.timestamp * 1000 >= uint256(eq.lockedUntil),\n            \"HLP still locked\"\n        );\n\n        ActionEncoder.sendVaultWithdraw(HyperCoreConstants.HLP_VAULT, usdAmount);\n        emit HlpWithdrawn(usdAmount);\n    }\n\n    // ─── BLP (Borrow/Lend Pool) ─────────────────────────────\n\n    /// @notice Supply `l1Amount` of `token` into HL's BLP (action 15 op=0). L1 8-dp wei.\n    function supplyToBlp(uint64 token, uint64 l1Amount) external onlyOperator whenOperatorNotPaused {\n        require(l1Amount > 0, \"zero amount\");\n        ActionEncoder.sendSupply(token, l1Amount);\n        if (accountant != address(0)) {\n            uint32 perpIndex = 0;\n            if (token != uint64(HyperCoreConstants.USDC_TOKEN_INDEX)) {\n                // Whitelist map is authoritative — BTC-PERP is index 0.\n                require(config.isSpotWhitelisted(uint32(token)), \"spot not whitelisted\");\n                perpIndex = config.spotToPerp(uint32(token));\n            }\n            MonetrixAccountant(accountant).notifyVaultSupply(token, perpIndex);\n        }\n        emit BlpSupplied(token, l1Amount);\n    }\n\n    /// @notice Withdraw from BLP back to spot (action 15 op=1). `l1Amount=0` means max.\n    function withdrawFromBlp(uint64 token, uint64 l1Amount) external onlyOperator whenOperatorNotPaused {\n        ActionEncoder.sendWithdrawSupply(token, l1Amount);\n        emit BlpWithdrawn(token, l1Amount);\n    }\n\n    // ─── Settlement + Yield ─────────────────────────────────\n\n    /// @notice Atomic all-or-nothing settle. Keeper submits `proposedYield`\n    ///         (phantom-excluded off-chain); Accountant enforces 4 gates\n    ///         (initialized / interval / distributable / annualized) and Vault\n    ///         enforces EVM USDC sufficiency. On success the full\n    ///         `proposedYield` moves to YieldEscrow; otherwise tx reverts.\n    /// @dev Only `shortfall` is reserved here. `bridgeRetentionAmount` is a\n    ///      bridge-to-L1 working balance (see `netBridgeable`); it is NOT a\n    ///      solvency invariant and must not block yield routing.\n    function settle(uint256 proposedYield) external onlyOperator requireWired nonReentrant whenNotPaused whenOperatorNotPaused {\n        require(proposedYield > 0, \"zero yield\");\n\n        uint256 vaultBal = usdc.balanceOf(address(this));\n        uint256 shortfall_ = IRedeemEscrow(redeemEscrow).shortfall();\n        uint256 available = vaultBal > shortfall_ ? vaultBal - shortfall_ : 0;\n        require(available >= proposedYield, \"insufficient EVM USDC\");\n\n        IMonetrixAccountant(accountant).settleDailyPnL(proposedYield);\n        usdc.safeTransfer(yieldEscrow, proposedYield);\n        emit YieldCollected(proposedYield);\n    }\n\n    function distributeYield() external nonReentrant onlyOperator requireWired whenNotPaused whenOperatorNotPaused {\n        uint256 totalYield = IYieldEscrow(yieldEscrow).balance();\n        require(totalYield > 0, \"no yield\");\n\n        uint256 balBefore = usdc.balanceOf(address(this));\n        IYieldEscrow(yieldEscrow).pullForDistribution(totalYield);\n        require(usdc.balanceOf(address(this)) >= balBefore + totalYield, \"pull\");\n\n        uint256 userShare = (totalYield * config.userYieldBps()) / 10000;\n        uint256 insuranceShare = (totalYield * config.insuranceYieldBps()) / 10000;\n\n        // Empty-vault yield would be captured by next depositor (L1-H1); reroute to foundation.\n        if (userShare > 0 && susdm.totalSupply() == 0) {\n            userShare = 0;\n        }\n\n        uint256 foundationShare = totalYield - userShare - insuranceShare;\n\n        if (userShare > 0) {\n            usdm.mint(address(this), userShare);\n            IERC20(address(usdm)).forceApprove(address(susdm), userShare);\n            susdm.injectYield(userShare);\n        }\n\n        if (insuranceShare > 0) {\n            address insuranceFundAddr = config.insuranceFund();\n            require(insuranceFundAddr != address(0), \"zero if\");\n            InsuranceFund _insuranceFund = InsuranceFund(insuranceFundAddr);\n            usdc.forceApprove(address(_insuranceFund), insuranceShare);\n            _insuranceFund.deposit(insuranceShare);\n        }\n        if (foundationShare > 0) {\n            address foundationAddr = config.foundation();\n            require(foundationAddr != address(0), \"zero fdn\");\n            usdc.safeTransfer(foundationAddr, foundationShare);\n        }\n\n        emit YieldDistributed(totalYield, userShare, insuranceShare, foundationShare);\n    }\n\n    // ─── Fund routing (Vault ↔ RedeemEscrow) ────────────────\n\n    function fundRedemptions(uint256 amount) external onlyOperator requireWired whenOperatorNotPaused {\n        uint256 sf = IRedeemEscrow(redeemEscrow).shortfall();\n        if (sf == 0) return;\n        uint256 toFund = amount == 0 ? sf : amount;\n        require(toFund <= sf, \"exceeds shortfall\");\n        uint256 vaultBal = usdc.balanceOf(address(this));\n        uint256 toTransfer = toFund < vaultBal ? toFund : vaultBal;\n        require(toTransfer > 0, \"nothing to fund\");\n        usdc.safeTransfer(redeemEscrow, toTransfer);\n        emit RedemptionsFunded(toTransfer);\n    }\n\n    function reclaimFromRedeemEscrow(uint256 amount) external onlyOperator requireWired whenOperatorNotPaused {\n        require(amount > 0, \"zero amount\");\n        IRedeemEscrow(redeemEscrow).reclaimTo(address(this), amount);\n        emit RedeemEscrowReclaimed(amount);\n    }\n\n    // ═══════════════════════════════════════════════════════════\n    //                  GUARDIAN OPERATIONS\n    // ═══════════════════════════════════════════════════════════\n\n    function pause() external onlyGuardian {\n        _pause();\n    }\n\n    function unpause() external onlyGuardian {\n        _unpause();\n    }\n\n    /// @notice Halt every operator-driven mutation (hedge/HLP/BLP/bridges/yield/escrow).\n    ///         User fund I/O stays on the independent `paused` flag.\n    function pauseOperator() external onlyGuardian {\n        operatorPaused = true;\n        emit OperatorPaused(msg.sender);\n    }\n\n    function unpauseOperator() external onlyGuardian {\n        operatorPaused = false;\n        emit OperatorUnpaused(msg.sender);\n    }\n\n    // ═══════════════════════════════════════════════════════════\n    //                  GOVERNOR OPERATIONS\n    // ═══════════════════════════════════════════════════════════\n\n    /// @dev Emergency escape hatches DO NOT check either pause flag. They exist precisely\n    ///      to recover from states where the operator pipeline is suspect / halted —\n    ///      gating them by pause would defeat their purpose. Governor 24h timelock is\n    ///      the guard.\n    function emergencyRawAction(bytes calldata data) external onlyGovernor {\n        ICoreWriter(HyperCoreConstants.CORE_WRITER).sendRawAction(data);\n        emit EmergencyActionSent(msg.sender, keccak256(data));\n    }\n\n    function emergencyBridgePrincipalFromL1(uint256 amount) external onlyGovernor {\n        require(amount > 0 && amount <= outstandingL1Principal, \"invalid bridge amount\");\n        outstandingL1Principal -= amount;\n        _sendL1Bridge(amount);\n        emit PrincipalBridgedFromL1(amount);\n    }\n\n    function setAccountant(address _accountant) external onlyGovernor {\n        require(_accountant != address(0), \"zero acc\");\n        accountant = _accountant;\n        emit AccountantUpdated(_accountant);\n    }\n\n    function setMultisigVault(address _multisig) external onlyGovernor {\n        if (_multisig == address(0)) {\n            require(!multisigVaultEnabled, \"multi on\");\n        }\n        multisigVault = _multisig;\n        emit MultisigVaultUpdated(_multisig);\n    }\n\n    function setMultisigVaultEnabled(bool _enabled) external onlyGovernor {\n        if (_enabled) {\n            require(multisigVault != address(0), \"no multi\");\n        }\n        multisigVaultEnabled = _enabled;\n    }\n\n    function setRedeemEscrow(address _escrow) external onlyGovernor {\n        require(_escrow != address(0), \"zero address\");\n        redeemEscrow = _escrow;\n        emit RedeemEscrowUpdated(_escrow);\n    }\n\n    function setYieldEscrow(address _escrow) external onlyGovernor {\n        require(_escrow != address(0), \"zero address\");\n        yieldEscrow = _escrow;\n        emit YieldEscrowUpdated(_escrow);\n    }\n\n    function setBridgeRetentionAmount(uint256 amount) external onlyGuardian {\n        bridgeRetentionAmount = amount;\n        emit BridgeRetentionAmountUpdated(amount);\n    }\n\n    /// @notice Flip after PM is activated on Vault's L1 account; gates the 0x811 read in `_sendL1Bridge`.\n    function setPmEnabled(bool enabled) external onlyGovernor {\n        pmEnabled = enabled;\n        emit PmEnabledUpdated(enabled);\n    }\n\n    // ═══════════════════════════════════════════════════════════\n    //                      INTERNAL\n    // ═══════════════════════════════════════════════════════════\n\n    /// @dev Checks L1 USDC (spot + supplied when PM on) covers `amount` before SEND_ASSET; avoids silent L1 drop when hedge is still locked.\n    function _sendL1Bridge(uint256 amount) internal {\n        uint64 usdcToken = uint64(HyperCoreConstants.USDC_TOKEN_INDEX);\n        uint256 l1Available = uint256(PrecompileReader.spotBalance(address(this), usdcToken).total);\n        if (pmEnabled) {\n            l1Available += uint256(PrecompileReader.suppliedBalance(address(this), usdcToken));\n        }\n        require(\n            l1Available >= TokenMath.usdcEvmToL1Wei(amount),\n            \"L1 USDC insufficient (unwind hedge or wait for settlement)\"\n        );\n        ActionEncoder.sendBridgeToL1(amount);\n    }\n\n    /// @dev `spotAsset` is the HL limit-order asset for the spot leg (= 10000 + pair_index),\n    ///      NOT the token_index. See `MonetrixConfig.TradeableAsset` for the distinction.\n    function _requireHedgePair(uint32 perpAsset, uint32 spotAsset) internal view {\n        require(config.isPerpWhitelisted(perpAsset), \"perp not whitelisted\");\n        require(config.perpToSpotPairAssetId(perpAsset) == spotAsset, \"spot/perp mismatch\");\n    }\n\n    /// @dev For `isPerp=false`, `asset` is the HL pair_asset_id (= 10000 + pair_index).\n    function _requireRepairAsset(uint32 asset, bool isPerp) internal view {\n        if (isPerp) {\n            require(config.isPerpWhitelisted(asset), \"perp not whitelisted\");\n        } else {\n            require(config.isSpotPairAssetIdWhitelisted(asset), \"spot pair not wl\");\n        }\n    }\n\n    function _removeUserRedeemId(address user, uint256 requestId) private {\n        uint256[] storage ids = _userRedeemIds[user];\n        uint256 len = ids.length;\n        for (uint256 i = 0; i < len; i++) {\n            if (ids[i] == requestId) {\n                ids[i] = ids[len - 1];\n                ids.pop();\n                return;\n            }\n        }\n    }\n\n    // ═══════════════════════════════════════════════════════════\n    //                       VIEW\n    // ═══════════════════════════════════════════════════════════\n\n    function netBridgeable() public view returns (uint256) {\n        uint256 bal = usdc.balanceOf(address(this));\n        uint256 sf = IRedeemEscrow(redeemEscrow).shortfall();\n        uint256 reserved = sf + bridgeRetentionAmount;\n        return bal > reserved ? bal - reserved : 0;\n    }\n\n    function redemptionShortfall() public view returns (uint256) {\n        if (redeemEscrow == address(0)) return 0;\n        return IRedeemEscrow(redeemEscrow).shortfall();\n    }\n\n    function yieldShortfall() public view returns (uint256) {\n        if (accountant == address(0)) return 0;\n        int256 s = IMonetrixAccountant(accountant).surplus();\n        if (s <= 0) return 0;\n        uint256 yield = uint256(s);\n        uint256 vaultBal = usdc.balanceOf(address(this));\n        uint256 res = IRedeemEscrow(redeemEscrow).shortfall() + bridgeRetentionAmount;\n        uint256 available = vaultBal > res ? vaultBal - res : 0;\n        return yield > available ? yield - available : 0;\n    }\n\n\n\n    function canKeeperBridge() external view returns (bool) {\n        if (redeemEscrow == address(0)) return false;\n        return block.timestamp >= lastBridgeTimestamp + config.bridgeInterval()\n            && netBridgeable() > 0;\n    }\n\n    struct RedeemRequestDetail {\n        uint256 requestId;\n        uint256 usdmAmount;\n        uint256 cooldownEnd;\n    }\n\n    function getUserRedeemIds(address user) external view returns (uint256[] memory) {\n        return _userRedeemIds[user];\n    }\n\n    function getUserRedeemRequests(address user) external view returns (RedeemRequestDetail[] memory) {\n        uint256[] memory ids = _userRedeemIds[user];\n        RedeemRequestDetail[] memory details = new RedeemRequestDetail[](ids.length);\n        for (uint256 i = 0; i < ids.length; i++) {\n            RedeemRequest memory req = redeemRequests[ids[i]];\n            details[i] =\n                RedeemRequestDetail({requestId: ids[i], usdmAmount: req.usdmAmount, cooldownEnd: req.cooldownEnd});\n        }\n        return details;\n    }\n\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable\n    struct PausableStorage {\n        bool _paused;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Pausable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;\n\n    function _getPausableStorage() private pure returns (PausableStorage storage $) {\n        assembly {\n            $.slot := PausableStorageLocation\n        }\n    }\n\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    /**\n     * @dev The operation failed because the contract is paused.\n     */\n    error EnforcedPause();\n\n    /**\n     * @dev The operation failed because the contract is not paused.\n     */\n    error ExpectedPause();\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    function __Pausable_init() internal onlyInitializing {\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        PausableStorage storage $ = _getPausableStorage();\n        return $._paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        if (paused()) {\n            revert EnforcedPause();\n        }\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        if (!paused()) {\n            revert ExpectedPause();\n        }\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n        emit Unpaused(_msgSender());\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/ReentrancyGuard.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\n\nimport {StorageSlot} from \"./StorageSlot.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n *\n * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced\n * by the {ReentrancyGuardTransient} variant in v6.0.\n *\n * @custom:stateless\n */\nabstract contract ReentrancyGuard {\n    using StorageSlot for bytes32;\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant REENTRANCY_GUARD_STORAGE =\n        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    constructor() {\n        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    /**\n     * @dev A `view` only version of {nonReentrant}. Use to block view functions\n     * from being called, preventing reading from inconsistent contract state.\n     *\n     * CAUTION: This is a \"view\" modifier and does not change the reentrancy\n     * status. Use it only on view functions. For payable or non-payable functions,\n     * use the standard {nonReentrant} modifier instead.\n     */\n    modifier nonReentrantView() {\n        _nonReentrantBeforeView();\n        _;\n    }\n\n    function _nonReentrantBeforeView() private view {\n        if (_reentrancyGuardEntered()) {\n            revert ReentrancyGuardReentrantCall();\n        }\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        _nonReentrantBeforeView();\n\n        // Any calls to nonReentrant after this point will fail\n        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _reentrancyGuardStorageSlot().getUint256Slot().value = NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;\n    }\n\n    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {\n        return REENTRANCY_GUARD_STORAGE;\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev An uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        if (!_safeTransfer(token, to, value, true)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        if (!_safeTransferFrom(token, from, to, value, true)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {\n        return _safeTransfer(token, to, value, false);\n    }\n\n    /**\n     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {\n        return _safeTransferFrom(token, from, to, value, false);\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     *\n     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        if (!_safeApprove(token, spender, value, false)) {\n            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));\n            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the\n     * return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param to The recipient of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {\n        bytes4 selector = IERC20.transfer.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(to, shr(96, not(0))))\n            mstore(0x24, value)\n            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return\n     * value: the return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param from The sender of the tokens\n     * @param to The recipient of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value,\n        bool bubble\n    ) private returns (bool success) {\n        bytes4 selector = IERC20.transferFrom.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(from, shr(96, not(0))))\n            mstore(0x24, and(to, shr(96, not(0))))\n            mstore(0x44, value)\n            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n            mstore(0x60, 0)\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:\n     * the return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param spender The spender of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {\n        bytes4 selector = IERC20.approve.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(spender, shr(96, not(0))))\n            mstore(0x24, value)\n            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n        }\n    }\n}\n"},"src/tokens/USDM.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\n\nimport {MonetrixGovernedUpgradeable} from \"../governance/MonetrixGovernedUpgradeable.sol\";\n\n/// @title USDM - Monetrix Delta-Neutral Stablecoin\n/// @notice 1:1 USDC-backed stablecoin, 6 decimals. Pure token, no business logic.\n/// @dev `mint` / `burn` restricted to `vault` (bound once via `setVault`).\n///      `pause` / `unpause` are held by GUARDIAN.\ncontract USDM is ERC20Upgradeable, PausableUpgradeable, MonetrixGovernedUpgradeable {\n    address public vault;\n\n    event VaultSet(address indexed vault);\n\n    error VaultAlreadySet();\n    error NotVault();\n    error ZeroVault();\n\n    modifier onlyVault() {\n        if (msg.sender != vault) revert NotVault();\n        _;\n    }\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(address _acl) external initializer {\n        __ERC20_init(\"Monetrix USD\", \"USDM\");\n        __Pausable_init();\n        __Governed_init(_acl);\n    }\n\n    /// @notice One-time binding of the Vault address. Irreversible.\n    function setVault(address _vault) external onlyGovernor {\n        if (_vault == address(0)) revert ZeroVault();\n        if (vault != address(0)) revert VaultAlreadySet();\n        vault = _vault;\n        emit VaultSet(_vault);\n    }\n\n    function mint(address to, uint256 amount) external onlyVault {\n        _mint(to, amount);\n    }\n\n    /// @notice Burn USDM from the caller's own balance.\n    /// @dev Vault.claimRedeem holds the USDM to be burned in its own balance\n    ///      (transferred in during requestRedeem), so self-burn is sufficient.\n    function burn(uint256 amount) external onlyVault {\n        _burn(msg.sender, amount);\n    }\n\n    function pause() external onlyGuardian {\n        _pause();\n    }\n\n    function unpause() external onlyGuardian {\n        _unpause();\n    }\n\n    function decimals() public pure override returns (uint8) {\n        return 6;\n    }\n\n    function _update(address from, address to, uint256 value) internal override whenNotPaused {\n        super._update(from, to, value);\n    }\n\n    uint256[49] private __gap;\n}\n"},"src/tokens/sUSDM.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC4626Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/ReentrancyGuard.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"../core/MonetrixConfig.sol\";\nimport {MonetrixGovernedUpgradeable} from \"../governance/MonetrixGovernedUpgradeable.sol\";\nimport {sUSDMEscrow} from \"./sUSDMEscrow.sol\";\n\n/// @title sUSDM - Staked USDM (Yield-bearing ERC-4626 vault token)\n/// @notice wstETH-style appreciation model. Exchange rate rises as yield is\n///         injected. Unstake cooldown physically isolates USDM into\n///         `sUSDMEscrow` at burn time — all queue logic stays here.\n/// @dev `injectYield` gated on `vault` (bound once via `setVault`).\n///      `pause` / `unpause` are `onlyGuardian`.\n///      `setConfig` / `setEscrow` / `setVault` are `onlyGovernor` (24h timelock).\ncontract sUSDM is\n    ERC4626Upgradeable,\n    PausableUpgradeable,\n    ReentrancyGuard,\n    MonetrixGovernedUpgradeable\n{\n    using SafeERC20 for IERC20;\n\n    struct UnstakeRequest {\n        address owner;\n        uint256 sharesAmount;\n        uint256 usdmAmount;\n        uint256 exchangeRate;\n        uint256 cooldownEnd;\n    }\n\n    uint256 public nextRequestId;\n    uint256 public totalPendingClaims;\n    mapping(uint256 => UnstakeRequest) public unstakeRequests;\n\n    MonetrixConfig public config;\n\n    // Yield tracking\n    uint256 public totalYieldInjected;\n    uint256 public lastCumulativeYield;\n\n    // ─── User Unstake Request Tracking ───\n    mapping(address => uint256[]) private _userUnstakeIds;\n\n    // ─── Physical isolation escrow ───\n    sUSDMEscrow public escrow;\n\n    address public vault;\n\n    event UnstakeRequested(\n        uint256 indexed requestId,\n        address indexed owner,\n        uint256 shares,\n        uint256 usdmAmount,\n        uint256 exchangeRate,\n        uint256 cooldownEnd\n    );\n    event UnstakeClaimed(uint256 indexed requestId, address indexed owner, uint256 usdmAmount);\n    event YieldInjected(uint256 amount, uint256 totalAssets, uint256 totalSupply);\n    event EscrowSet(address indexed escrow);\n    event VaultSet(address indexed vault);\n\n    error CooldownNotExpired(uint256 requestId, uint256 cooldownEnd);\n    error NotRequestOwner(uint256 requestId, address caller, address owner);\n    error AlreadyClaimed(uint256 requestId);\n    error UseCooldownFunctions();\n    error EscrowNotSet();\n    error EscrowAlreadySet();\n    error EscrowMismatch();\n    error VaultAlreadySet();\n    error NotVault();\n    error ZeroVault();\n\n    modifier onlyVault() {\n        if (msg.sender != vault) revert NotVault();\n        _;\n    }\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(address _usdm, address _config, address _acl) external initializer {\n        require(_usdm != address(0), \"sUSDM: zero usdm\");\n        require(_config != address(0), \"sUSDM: zero config\");\n        __ERC4626_init(IERC20(_usdm));\n        __ERC20_init(\"Staked USDM\", \"sUSDM\");\n        __Pausable_init();\n        __Governed_init(_acl);\n        config = MonetrixConfig(_config);\n    }\n\n\n    // --- ERC-4626 Overrides ---\n\n    function totalAssets() public view override returns (uint256) {\n        return IERC20(asset()).balanceOf(address(this));\n    }\n\n    function _decimalsOffset() internal pure override returns (uint8) {\n        return 6;\n    }\n\n    function withdraw(uint256, address, address) public pure override returns (uint256) {\n        revert UseCooldownFunctions();\n    }\n\n    function redeem(uint256, address, address) public pure override returns (uint256) {\n        revert UseCooldownFunctions();\n    }\n\n    function deposit(uint256 assets, address receiver) public override nonReentrant whenNotPaused returns (uint256) {\n        return super.deposit(assets, receiver);\n    }\n\n    function mint(uint256 shares, address receiver) public override nonReentrant whenNotPaused returns (uint256) {\n        return super.mint(shares, receiver);\n    }\n\n    // --- ERC-4626 max* overrides ---\n    //\n    // The default OZ implementations return `type(uint256).max` (for deposit/mint)\n    // or user-balance-derived values (for withdraw/redeem), which would mislead\n    // integrators because our `deposit`/`mint` revert under pause, and our\n    // `withdraw`/`redeem` always revert (unstake is async via the cooldown flow).\n    // Per EIP-4626: \"max* MUST return ... [a value that would] not cause a revert.\"\n\n    /// @notice 0 when paused (deposits revert), else uncapped.\n    function maxDeposit(address) public view override returns (uint256) {\n        return paused() ? 0 : type(uint256).max;\n    }\n\n    /// @notice 0 when paused (mints revert), else uncapped.\n    function maxMint(address) public view override returns (uint256) {\n        return paused() ? 0 : type(uint256).max;\n    }\n\n    /// @notice Always 0 — `withdraw` always reverts. Use `cooldownAssets` + `claimUnstake`.\n    function maxWithdraw(address) public pure override returns (uint256) {\n        return 0;\n    }\n\n    /// @notice Always 0 — `redeem` always reverts. Use `cooldownShares` + `claimUnstake`.\n    function maxRedeem(address) public pure override returns (uint256) {\n        return 0;\n    }\n\n    // --- Unstake Cooldown ---\n\n    function cooldownShares(uint256 shares) external nonReentrant whenNotPaused returns (uint256 requestId) {\n        require(shares > 0, \"sUSDM: zero shares\");\n        require(balanceOf(msg.sender) >= shares, \"sUSDM: insufficient balance\");\n        if (address(escrow) == address(0)) revert EscrowNotSet();\n\n        uint256 supply = totalSupply();\n        uint256 currentRate = supply > 0 ? (totalAssets() * 1e18) / supply : 1e18;\n        uint256 assets = convertToAssets(shares);\n        require(assets > 0, \"sUSDM: zero assets\");\n\n        _burn(msg.sender, shares);\n        totalPendingClaims += assets;\n        escrow.deposit(assets);\n\n        requestId = nextRequestId++;\n        unstakeRequests[requestId] = UnstakeRequest({\n            owner: msg.sender,\n            sharesAmount: shares,\n            usdmAmount: assets,\n            exchangeRate: currentRate,\n            cooldownEnd: block.timestamp + config.unstakeCooldown()\n        });\n        _userUnstakeIds[msg.sender].push(requestId);\n        emit UnstakeRequested(\n            requestId, msg.sender, shares, assets, currentRate, block.timestamp + config.unstakeCooldown()\n        );\n    }\n\n    /// @notice Unstake by exact USDM amount (ERC-4626 `withdraw` semantics:\n    ///         shares rounded up in vault's favor). For \"unstake all\" use\n    ///         `cooldownShares` to avoid 1-wei-per-request rounding drag.\n    function cooldownAssets(uint256 assets) external nonReentrant whenNotPaused returns (uint256 requestId) {\n        require(assets > 0, \"sUSDM: zero assets\");\n        uint256 shares = previewWithdraw(assets);\n        require(shares > 0, \"sUSDM: zero shares\");\n        require(balanceOf(msg.sender) >= shares, \"sUSDM: insufficient balance\");\n        if (address(escrow) == address(0)) revert EscrowNotSet();\n\n        uint256 supply = totalSupply();\n        uint256 currentRate = supply > 0 ? (totalAssets() * 1e18) / supply : 1e18;\n\n        _burn(msg.sender, shares);\n        totalPendingClaims += assets;\n        escrow.deposit(assets);\n\n        requestId = nextRequestId++;\n        unstakeRequests[requestId] = UnstakeRequest({\n            owner: msg.sender,\n            sharesAmount: shares,\n            usdmAmount: assets,\n            exchangeRate: currentRate,\n            cooldownEnd: block.timestamp + config.unstakeCooldown()\n        });\n        _userUnstakeIds[msg.sender].push(requestId);\n        emit UnstakeRequested(\n            requestId, msg.sender, shares, assets, currentRate, block.timestamp + config.unstakeCooldown()\n        );\n    }\n\n    function claimUnstake(uint256 requestId) external nonReentrant whenNotPaused {\n        UnstakeRequest memory req = unstakeRequests[requestId];\n        if (req.usdmAmount == 0) revert AlreadyClaimed(requestId);\n        if (msg.sender != req.owner) revert NotRequestOwner(requestId, msg.sender, req.owner);\n        if (block.timestamp < req.cooldownEnd) revert CooldownNotExpired(requestId, req.cooldownEnd);\n\n        delete unstakeRequests[requestId];\n        _removeUserUnstakeId(req.owner, requestId);\n        totalPendingClaims -= req.usdmAmount;\n        escrow.release(msg.sender, req.usdmAmount);\n        emit UnstakeClaimed(requestId, msg.sender, req.usdmAmount);\n    }\n\n    // --- Yield Injection ---\n\n    function injectYield(uint256 usdmAmount) external onlyVault nonReentrant {\n        require(usdmAmount > 0, \"sUSDM: zero yield\");\n        require(usdmAmount <= config.maxYieldPerInjection(), \"sUSDM: yield exceeds max\");\n        // Empty-vault yield would be captured by next depositor (L1-H1).\n        require(totalSupply() > 0, \"sUSDM: no stakers\");\n\n        IERC20(asset()).safeTransferFrom(msg.sender, address(this), usdmAmount);\n\n        totalYieldInjected += usdmAmount;\n        lastCumulativeYield = (totalAssets() * 1e18) / totalSupply();\n\n        emit YieldInjected(usdmAmount, totalAssets(), totalSupply());\n    }\n\n    // --- Admin ---\n\n    function setConfig(address _config) external onlyGovernor {\n        require(_config != address(0), \"sUSDM: zero config\");\n        config = MonetrixConfig(_config);\n    }\n\n    /// @notice One-time wiring of the physically-isolated escrow.\n    ///         Grants infinite USDM allowance so `escrow.deposit()` can pull.\n    function setEscrow(address _escrow) external onlyGovernor {\n        require(_escrow != address(0), \"sUSDM: zero escrow\");\n        if (address(escrow) != address(0)) revert EscrowAlreadySet();\n        if (sUSDMEscrow(_escrow).sUSDM() != address(this)) revert EscrowMismatch();\n        if (address(sUSDMEscrow(_escrow).usdm()) != asset()) revert EscrowMismatch();\n        escrow = sUSDMEscrow(_escrow);\n        IERC20(asset()).forceApprove(_escrow, type(uint256).max);\n        emit EscrowSet(_escrow);\n    }\n\n    /// @notice One-time binding of the Vault address. Irreversible.\n    function setVault(address _vault) external onlyGovernor {\n        if (_vault == address(0)) revert ZeroVault();\n        if (vault != address(0)) revert VaultAlreadySet();\n        vault = _vault;\n        emit VaultSet(_vault);\n    }\n\n    function pause() external onlyGuardian {\n        _pause();\n    }\n\n    function unpause() external onlyGuardian {\n        _unpause();\n    }\n\n    function _update(address from, address to, uint256 value) internal override whenNotPaused {\n        super._update(from, to, value);\n    }\n\n    // --- User Unstake Query ---\n\n    struct UnstakeRequestDetail {\n        uint256 requestId;\n        uint256 sharesAmount;\n        uint256 usdmAmount;\n        uint256 exchangeRate;\n        uint256 cooldownEnd;\n    }\n\n    function getUserUnstakeIds(address user) external view returns (uint256[] memory) {\n        return _userUnstakeIds[user];\n    }\n\n    function getUserUnstakeRequests(address user) external view returns (UnstakeRequestDetail[] memory) {\n        uint256[] memory ids = _userUnstakeIds[user];\n        UnstakeRequestDetail[] memory details = new UnstakeRequestDetail[](ids.length);\n        for (uint256 i = 0; i < ids.length; i++) {\n            UnstakeRequest memory req = unstakeRequests[ids[i]];\n            details[i] = UnstakeRequestDetail({\n                requestId: ids[i],\n                sharesAmount: req.sharesAmount,\n                usdmAmount: req.usdmAmount,\n                exchangeRate: req.exchangeRate,\n                cooldownEnd: req.cooldownEnd\n            });\n        }\n        return details;\n    }\n\n    function _removeUserUnstakeId(address user, uint256 requestId) private {\n        uint256[] storage ids = _userUnstakeIds[user];\n        uint256 len = ids.length;\n        for (uint256 i = 0; i < len; i++) {\n            if (ids[i] == requestId) {\n                ids[i] = ids[len - 1];\n                ids.pop();\n                return;\n            }\n        }\n    }\n\n    uint256[45] private __gap;\n}\n"},"src/core/MonetrixConfig.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport {MonetrixGovernedUpgradeable} from \"../governance/MonetrixGovernedUpgradeable.sol\";\n\n/// @title MonetrixConfig - Centralized protocol parameter registry\n/// @notice Holds operational parameters: yield split ratios, deposit/TVL\n///         limits, cooldowns, and the recipient addresses (insurance fund,\n///         foundation) that the yield split targets.\n/// @dev All parameter mutations are gated by the 24h timelock via\n///      `onlyGovernor`. Upgrades are gated by the 48h timelock via the\n///      inherited `_authorizeUpgrade` hook.\ncontract MonetrixConfig is MonetrixGovernedUpgradeable {\n    uint256 public userYieldBps;\n    uint256 public insuranceYieldBps;\n    uint256 public minDepositAmount;\n    uint256 public maxDepositAmount;\n    uint256 public maxTVL;\n    uint256 public bridgeInterval;\n    address public insuranceFund;\n    address public foundation;\n    uint256 public redeemCooldown;\n    uint256 public unstakeCooldown;\n\n    // ─── Tradeable asset whitelist ──────────────────────────\n    /// @dev HL has three independent index spaces. This struct binds them into one tuple:\n    ///        - `perpIndex`       — HL perp identifier (oracle key, info key, limit-order asset for perp leg)\n    ///        - `spotIndex`       — HL token index (0x801/0x811 balance key, action-15 BLP token)\n    ///        - `spotPairAssetId` — HL limit-order asset for the spot leg (= 10000 + HL spot pair_index)\n    ///      `spotIndex` and `spotPairAssetId` are NOT the same number — one token can back many\n    ///      pairs, so the pair must be chosen explicitly per whitelisted asset.\n    struct TradeableAsset {\n        uint32 perpIndex;\n        uint32 spotIndex;\n        uint32 spotPairAssetId;\n    }\n\n    TradeableAsset[] public tradeableAssets;\n    mapping(uint32 => uint32) public perpToSpot;\n    mapping(uint32 => uint32) public spotToPerp;\n    mapping(uint32 => uint32) public perpToSpotPairAssetId;\n    mapping(uint32 => bool) public isPerpWhitelisted;\n    mapping(uint32 => bool) public isSpotWhitelisted;           // keyed by HL token_index\n    mapping(uint32 => bool) public isSpotPairAssetIdWhitelisted; // keyed by HL pair_asset_id (= 10000 + pair_index)\n\n    /// @notice Per-injection cap on sUSDM.injectYield. Governor-tunable defense-in-depth\n    ///         against off-chain yield input errors (yield is derived on-chain from\n    ///         backing − supply, but the cap bounds a single injection amount).\n    uint256 public maxYieldPerInjection;\n\n    /// @notice Annualized cap (bps of USDM supply) for a single settle proposal.\n    ///         Enforced by Accountant: `proposedYield ≤ supply × bps × Δt / (10000 × 1y)`.\n    /// @dev Hard upper-bound at `MAX_ANNUAL_YIELD_BPS_CAP` (currently 50% APR).\n    uint256 public maxAnnualYieldBps;\n\n    uint256 public constant MAX_ANNUAL_YIELD_BPS_CAP = 5000;\n\n    event YieldBpsUpdated(uint256 userBps, uint256 insuranceBps, uint256 foundationBps);\n    event DepositLimitsUpdated(uint256 minAmount, uint256 maxAmount);\n    event MaxTVLUpdated(uint256 newCap);\n    event BridgeIntervalUpdated(uint256 interval);\n    event CooldownsUpdated(uint256 redeemCooldown, uint256 unstakeCooldown);\n    event AddressUpdated(string name, address addr);\n    event TradeableAssetsUpdated(uint256 count);\n    event MaxYieldPerInjectionUpdated(uint256 amount);\n    event MaxAnnualYieldBpsUpdated(uint256 bps);\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(address _insuranceFund, address _foundation, address _acl) external initializer {\n        require(_insuranceFund != address(0), \"Config: zero insuranceFund\");\n        require(_foundation != address(0), \"Config: zero foundation\");\n        __Governed_init(_acl);\n        insuranceFund = _insuranceFund;\n        foundation = _foundation;\n        userYieldBps = 7000;\n        insuranceYieldBps = 1000;\n        minDepositAmount = 100e6;\n        maxDepositAmount = 1_000_000e6;\n        maxTVL = 10_000_000e6;\n        bridgeInterval = 6 hours;\n        redeemCooldown = 3 days;\n        unstakeCooldown = 3 days;\n        maxYieldPerInjection = 1_000_000e6;\n        maxAnnualYieldBps = 1200;\n    }\n\n    /// @notice Foundation share = 10000 - userYieldBps - insuranceYieldBps.\n    function foundationYieldBps() external view returns (uint256) {\n        return 10000 - userYieldBps - insuranceYieldBps;\n    }\n\n    function setYieldBps(uint256 _userBps, uint256 _insuranceBps) external onlyGovernor {\n        require(_userBps + _insuranceBps <= 10000, \"Config: bps exceed 10000\");\n        userYieldBps = _userBps;\n        insuranceYieldBps = _insuranceBps;\n        emit YieldBpsUpdated(_userBps, _insuranceBps, 10000 - _userBps - _insuranceBps);\n    }\n\n    function setDepositLimits(uint256 _min, uint256 _max) external onlyGovernor {\n        require(_min > 0, \"Config: zero min\");\n        require(_min < _max, \"Config: min >= max\");\n        minDepositAmount = _min;\n        maxDepositAmount = _max;\n        emit DepositLimitsUpdated(_min, _max);\n    }\n\n    function setMaxTVL(uint256 _maxTVL) external onlyGovernor {\n        maxTVL = _maxTVL;\n        emit MaxTVLUpdated(_maxTVL);\n    }\n\n    function setBridgeInterval(uint256 _interval) external onlyGuardian {\n        require(_interval > 0, \"Config: zero interval\");\n        require(_interval <= 1 days, \"Config: interval too long\");\n        bridgeInterval = _interval;\n        emit BridgeIntervalUpdated(_interval);\n    }\n\n    function setCooldowns(uint256 _redeemCooldown, uint256 _unstakeCooldown) external onlyGovernor {\n        require(_redeemCooldown >= 1 minutes, \"Config: redeem cooldown too short\");\n        require(_unstakeCooldown >= 1 minutes, \"Config: unstake cooldown too short\");\n        require(_redeemCooldown <= 30 days, \"Config: redeem cooldown too long\");\n        require(_unstakeCooldown <= 30 days, \"Config: unstake cooldown too long\");\n        redeemCooldown = _redeemCooldown;\n        unstakeCooldown = _unstakeCooldown;\n        emit CooldownsUpdated(_redeemCooldown, _unstakeCooldown);\n    }\n\n    function setInsuranceFund(address _addr) external onlyGovernor {\n        require(_addr != address(0), \"Config: zero address\");\n        insuranceFund = _addr;\n        emit AddressUpdated(\"insuranceFund\", _addr);\n    }\n\n    function setFoundation(address _addr) external onlyGovernor {\n        require(_addr != address(0), \"Config: zero address\");\n        foundation = _addr;\n        emit AddressUpdated(\"foundation\", _addr);\n    }\n\n    function setMaxYieldPerInjection(uint256 _amount) external onlyGovernor {\n        require(_amount > 0, \"Config: zero max\");\n        maxYieldPerInjection = _amount;\n        emit MaxYieldPerInjectionUpdated(_amount);\n    }\n\n    function setMaxAnnualYieldBps(uint256 _bps) external onlyGovernor {\n        require(_bps > 0, \"Config: zero bps\");\n        require(_bps <= MAX_ANNUAL_YIELD_BPS_CAP, \"Config: exceeds hard cap\");\n        maxAnnualYieldBps = _bps;\n        emit MaxAnnualYieldBpsUpdated(_bps);\n    }\n\n    // ─── Tradeable asset whitelist management ──────────────\n\n    function addTradeableAsset(TradeableAsset calldata asset) external onlyGovernor {\n        _addAsset(asset);\n        emit TradeableAssetsUpdated(tradeableAssets.length);\n    }\n\n    function addTradeableAssets(TradeableAsset[] calldata assets) external onlyGovernor {\n        for (uint256 i = 0; i < assets.length; i++) {\n            _addAsset(assets[i]);\n        }\n        emit TradeableAssetsUpdated(tradeableAssets.length);\n    }\n\n    function _addAsset(TradeableAsset calldata asset) internal {\n        // spotIndex 0 = USDC (base currency, never a hedge). perpIndex 0 allowed (BTC-PERP).\n        require(asset.spotIndex != 0, \"Config: zero spotIndex\");\n        require(asset.spotPairAssetId >= 10000, \"Config: pair asset_id must be >= 10000\");\n        require(!isPerpWhitelisted[asset.perpIndex], \"Config: perp already listed\");\n        require(!isSpotWhitelisted[asset.spotIndex], \"Config: spot already listed\");\n        require(!isSpotPairAssetIdWhitelisted[asset.spotPairAssetId], \"Config: pair already listed\");\n        tradeableAssets.push(asset);\n        perpToSpot[asset.perpIndex] = asset.spotIndex;\n        spotToPerp[asset.spotIndex] = asset.perpIndex;\n        perpToSpotPairAssetId[asset.perpIndex] = asset.spotPairAssetId;\n        isPerpWhitelisted[asset.perpIndex] = true;\n        isSpotWhitelisted[asset.spotIndex] = true;\n        isSpotPairAssetIdWhitelisted[asset.spotPairAssetId] = true;\n    }\n\n    function removeTradeableAsset(uint32 perpIndex) external onlyGovernor {\n        require(isPerpWhitelisted[perpIndex], \"Config: perp not listed\");\n        uint32 spotIdx = perpToSpot[perpIndex];\n        uint32 pairAssetId = perpToSpotPairAssetId[perpIndex];\n\n        // Swap-and-pop from the array\n        uint256 len = tradeableAssets.length;\n        for (uint256 i = 0; i < len; i++) {\n            if (tradeableAssets[i].perpIndex == perpIndex) {\n                tradeableAssets[i] = tradeableAssets[len - 1];\n                tradeableAssets.pop();\n                break;\n            }\n        }\n\n        delete perpToSpot[perpIndex];\n        delete spotToPerp[spotIdx];\n        delete perpToSpotPairAssetId[perpIndex];\n        delete isPerpWhitelisted[perpIndex];\n        delete isSpotWhitelisted[spotIdx];\n        delete isSpotPairAssetIdWhitelisted[pairAssetId];\n        emit TradeableAssetsUpdated(tradeableAssets.length);\n    }\n\n    function tradeableAssetsLength() external view returns (uint256) {\n        return tradeableAssets.length;\n    }\n\n    /// @dev Reduced from 50 → 49 (V2 `maxYieldPerInjection`) → 48 (V3 `maxAnnualYieldBps`)\n    ///      → 46 (V4 `perpToSpotPairAssetId` + `isSpotPairAssetIdWhitelisted`).\n    uint256[46] private __gap;\n}\n"},"src/core/InsuranceFund.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {MonetrixGovernedUpgradeable} from \"../governance/MonetrixGovernedUpgradeable.sol\";\n\n/// @title InsuranceFund - Monetrix protocol insurance reserve\n/// @notice Accumulates USDC from yield splits. Anyone can deposit, withdrawals\n///         require the 24h timelock (GOVERNOR).\ncontract InsuranceFund is MonetrixGovernedUpgradeable {\n    using SafeERC20 for IERC20;\n\n    IERC20 public usdc;\n    uint256 public totalDeposited;\n    uint256 public totalWithdrawn;\n\n    event Deposited(address indexed from, uint256 amount);\n    event Withdrawn(address indexed to, uint256 amount, string reason);\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(address _usdc, address _acl) external initializer {\n        require(_usdc != address(0), \"IF: zero usdc\");\n        __Governed_init(_acl);\n        usdc = IERC20(_usdc);\n    }\n\n\n    function balance() external view returns (uint256) {\n        return usdc.balanceOf(address(this));\n    }\n\n    function deposit(uint256 amount) external {\n        require(amount > 0, \"IF: zero amount\");\n        usdc.safeTransferFrom(msg.sender, address(this), amount);\n        totalDeposited += amount;\n        emit Deposited(msg.sender, amount);\n    }\n\n    function withdraw(address to, uint256 amount, string calldata reason) external onlyGovernor {\n        require(amount > 0, \"IF: zero amount\");\n        require(to != address(0), \"IF: zero address\");\n        require(amount <= usdc.balanceOf(address(this)), \"IF: insufficient balance\");\n        totalWithdrawn += amount;\n        usdc.safeTransfer(to, amount);\n        emit Withdrawn(to, amount, reason);\n    }\n\n    uint256[50] private __gap;\n}\n"},"src/interfaces/IHyperCore.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\ninterface ICoreWriter {\n    function sendRawAction(bytes calldata data) external;\n}\n\ninterface ICoreDepositWallet {\n    function deposit(uint256 amount, uint32 destination) external;\n    /// @notice Deposit USDC on behalf of `recipient` — credits recipient's L1 account\n    function depositFor(address recipient, uint256 amount, uint32 destination) external;\n}\n\ninterface IHyperCoreRead {\n    struct SpotBalance {\n        uint64 total;\n        uint64 hold;\n    }\n\n    struct PerpPosition {\n        int64 szi;\n        uint32 leverage;\n        uint64 entryNtl;\n    }\n\n    function readSpotBalance(address user, uint32 token) external view returns (SpotBalance memory);\n    function readPerpPosition(address user, uint32 perp) external view returns (PerpPosition memory);\n}\n"},"src/interfaces/HyperCoreConstants.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\n/// @title HyperCoreConstants - Asset IDs, addresses, and protocol-level constants.\n/// @notice Pure constants only. Precision / unit conversions live in `TokenMath`.\nlibrary HyperCoreConstants {\n    address constant CORE_WRITER = 0x3333333333333333333333333333333333333333;\n    address constant CORE_READ = 0x0000000000000000000000000000000000000800;\n    address constant CORE_DEPOSIT_WALLET_MAINNET = 0x6B9E773128f453f5c2C60935Ee2DE2CBc5390A24;\n    address constant CORE_DEPOSIT_WALLET_TESTNET = 0x0B80659a4076E9E93C7DbE0f10675A16a3e5C206;\n    uint32 constant USDC_TOKEN_INDEX = 0;\n    uint32 constant SPOT_DEX = type(uint32).max;\n\n    // Action encoding constants\n    uint8 constant ACTION_VERSION = 1;\n    uint24 constant ACTION_LIMIT_ORDER = 1;\n    uint24 constant ACTION_VAULT_TRANSFER = 2;\n    uint24 constant ACTION_SPOT_SEND = 6;\n    uint24 constant ACTION_SEND_ASSET = 13;\n    uint24 constant ACTION_BORROW_LEND = 15;\n    address constant USDC_SYSTEM_ADDRESS = 0x2000000000000000000000000000000000000000;\n    uint256 constant EVM_TO_L1_PRECISION = 100;\n\n    // Precompile addresses\n    address constant PRECOMPILE_POSITION = 0x0000000000000000000000000000000000000800;\n    address constant PRECOMPILE_SPOT_BALANCE = 0x0000000000000000000000000000000000000801;\n    address constant PRECOMPILE_VAULT_EQUITY = 0x0000000000000000000000000000000000000802;\n    address constant PRECOMPILE_ORACLE_PX = 0x0000000000000000000000000000000000000807;\n    address constant PRECOMPILE_SPOT_PX = 0x0000000000000000000000000000000000000808;\n    address constant PRECOMPILE_PERP_ASSET_INFO = 0x000000000000000000000000000000000000080a;\n    address constant PRECOMPILE_TOKEN_INFO = 0x000000000000000000000000000000000000080C;\n    address constant PRECOMPILE_ACCOUNT_MARGIN_SUMMARY = 0x000000000000000000000000000000000000080F;\n    address constant PRECOMPILE_SUPPLIED_BALANCE = 0x0000000000000000000000000000000000000811;\n\n    // HLP vault address (change per network before deployment)\n    address constant HLP_VAULT = 0xdfc24b077bc1425AD1DEA75bCB6f8158E10Df303;\n}\n"},"src/interfaces/IMonetrixAccountant.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\n/// @title IMonetrixAccountant\n/// @notice Minimal interface for peg reads + yield declaration gating. The\n///         accountant holds no tokens; `settleDailyPnL` is the single yield\n///         authority. Bounds: initialized + interval + distributable + annualized.\ninterface IMonetrixAccountant {\n    function settleDailyPnL(uint256 proposedYield) external returns (uint256 distributable);\n    function surplus() external view returns (int256);\n    function distributableSurplus() external view returns (int256);\n}\n"},"src/interfaces/IRedeemEscrow.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\n/// @title IRedeemEscrow\n/// @notice Holds USDC reserved for pending redemptions. Tracks its own\n/// obligations (totalOwed) so it knows what it owes vs what it has.\ninterface IRedeemEscrow {\n    function addObligation(uint256 amount) external;\n    function payOut(address recipient, uint256 amount) external;\n    function reclaimTo(address to, uint256 amount) external;\n    function totalOwed() external view returns (uint256);\n    function shortfall() external view returns (uint256);\n    function balance() external view returns (uint256);\n}\n"},"src/interfaces/IYieldEscrow.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\n/// @title IYieldEscrow\n/// @notice Minimal interface for the yield escrow contract.\n/// Holds USDC for yield distribution. Only the Vault can move funds\n/// in (via direct safeTransfer) or out (via pullForDistribution).\ninterface IYieldEscrow {\n    function pullForDistribution(uint256 amount) external;\n    function balance() external view returns (uint256);\n}\n"},"src/core/ActionEncoder.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"../interfaces/HyperCoreConstants.sol\";\nimport \"../interfaces/IHyperCore.sol\";\nimport \"./TokenMath.sol\";\n\n/// @title ActionEncoder — single encode+send path for every L1 CoreWriter action\n/// @notice All write-side HyperCore interactions go through this library. Each\n///         `sendX` function builds the action payload AND calls\n///         `ICoreWriter.sendRawAction` in one step, so there is no\n///         \"half-encoded, bytes floating around\" intermediate state.\n/// @dev Library `internal` functions inline into the caller's bytecode, which\n///      means `CoreWriter.sendRawAction`'s `msg.sender` is the Vault, not this\n///      library. This preserves Vault's identity as the sole L1 account on\n///      HyperCore — the very reason an earlier Gateway-as-contract design had\n///      to be reverted (funds followed Gateway, not Vault).\nlibrary ActionEncoder {\n    /// @dev HL LIMIT_ORDER TIF encoding: 1=ALO (post-only), 2=GTC, 3=IOC.\n    ///      Caller passes raw uint8 in struct; see `lib/hyper-evm-lib/src/common/HLConstants.sol`.\n\n    struct HedgeParams {\n        uint32 spotAsset;\n        uint32 perpAsset;\n        uint64 size;             // 10^8 * human readable\n        uint64 spotPrice;        // 10^8 * human readable\n        uint64 perpPrice;        // 10^8 * human readable\n        uint128 cloid;           // 0 = no cloid\n        uint8 tif;               // 1=ALO, 2=GTC, 3=IOC — applies to both open legs\n        bool spotReduceOnly;     // typically false for opens; keeper-controlled for edge cases\n        bool perpReduceOnly;     // typically false for opens; keeper-controlled for edge cases\n    }\n\n    struct CloseParams {\n        uint256 positionId;\n        uint32 spotAsset;\n        uint32 perpAsset;\n        uint64 size;\n        uint64 spotPrice;\n        uint64 perpPrice;\n        uint128 cloid;\n        uint8 tif;               // 1=ALO, 2=GTC, 3=IOC — applies to both close legs\n        bool spotReduceOnly;     // HL spot silently drops reduceOnly=true on some paths — keeper may need false\n        bool perpReduceOnly;     // perp reduceOnly=true is safe (prevents flip-through)\n    }\n\n    struct RepairParams {\n        uint32 asset;\n        bool isPerp;       // true = repairing perp leg, false = repairing spot leg\n        bool isBuy;\n        bool reduceOnly;   // true = close (undo failed hedge), false = open (complete failed hedge)\n        uint64 size;\n        uint64 price;\n        uint16 residualBps;\n        uint128 cloid;\n        uint8 tif;         // 1=ALO, 2=GTC, 3=IOC\n    }\n\n    // ─── Hedge ─────────────────────────────────────────────────\n\n    /// @notice Place spot buy limit order — long leg of a hedge.\n    /// @dev `p.spotReduceOnly` is forwarded; opens typically pass `false`.\n    function sendBuySpot(HedgeParams memory p) internal {\n        _sendLimitOrder(p.spotAsset, true, p.spotPrice, p.size, p.spotReduceOnly, p.tif, p.cloid);\n    }\n\n    /// @notice Place perp short limit order — short leg of a hedge.\n    /// @dev `p.perpReduceOnly` is forwarded; opens typically pass `false`.\n    function sendShortPerp(HedgeParams memory p) internal {\n        _sendLimitOrder(p.perpAsset, false, p.perpPrice, p.size, p.perpReduceOnly, p.tif, p.cloid);\n    }\n\n    /// @notice Close spot leg — sell the long.\n    /// @dev `p.spotReduceOnly` is forwarded as-is. Keeper should typically pass `false`\n    ///      for spot (HL has been observed to silently drop spot+reduceOnly=true on some\n    ///      paths — tx 0xe20964…/0x3bde5f on 2026-04-22 confirmed the asymmetry).\n    function sendSellSpot(CloseParams memory p) internal {\n        _sendLimitOrder(p.spotAsset, false, p.spotPrice, p.size, p.spotReduceOnly, p.tif, p.cloid);\n    }\n\n    /// @notice Close perp leg — buy back the short.\n    /// @dev `p.perpReduceOnly` typically `true` to prevent accidental flip.\n    function sendClosePerp(CloseParams memory p) internal {\n        _sendLimitOrder(p.perpAsset, true, p.perpPrice, p.size, p.perpReduceOnly, p.tif, p.cloid);\n    }\n\n    /// @notice Residual repair order — single-leg limit order that either\n    ///         completes or undoes a partially-filled hedge.\n    function sendRepairAction(RepairParams memory p) internal {\n        _sendLimitOrder(p.asset, p.isBuy, p.price, p.size, p.reduceOnly, p.tif, p.cloid);\n    }\n\n    /// @dev Shared LIMIT_ORDER encode+dispatch. Consolidates what was 5 copies\n    ///      inlined into the Vault; compiler emits one JUMPDEST body shared by all\n    ///      callers, cutting ~hundreds of bytes off Vault's runtime bytecode.\n    function _sendLimitOrder(\n        uint32 asset,\n        bool isBuy,\n        uint64 price,\n        uint64 size,\n        bool reduceOnly,\n        uint8 tif,\n        uint128 cloid\n    ) private {\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_LIMIT_ORDER,\n            abi.encode(asset, isBuy, price, size, reduceOnly, tif, cloid)\n        );\n        _sendRaw(action);\n    }\n\n    // ─── HLP Vault Transfer ────────────────────────────────────\n\n    /// @notice Deposit USD into a HyperCore vault (e.g. HLP).\n    /// @dev `usdAmount` is in 6-decimal perp units (NOT 8-decimal L1 wei).\n    function sendVaultDeposit(address vault, uint64 usdAmount) internal {\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_VAULT_TRANSFER,\n            abi.encode(vault, true, usdAmount)\n        );\n        _sendRaw(action);\n    }\n\n    /// @notice Withdraw USD from a HyperCore vault. Subject to vault lock.\n    function sendVaultWithdraw(address vault, uint64 usdAmount) internal {\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_VAULT_TRANSFER,\n            abi.encode(vault, false, usdAmount)\n        );\n        _sendRaw(action);\n    }\n\n    // ─── BLP (Borrow/Lend Pool, action 15) ─────────────────────\n\n    /// @notice Supply `l1Amount` of `token` into HL's Borrow/Lend Pool (op=0).\n    /// @dev `l1Amount` is L1 8-dp wei. Target token must be BLP-enabled (has `ltv`).\n    function sendSupply(uint64 token, uint64 l1Amount) internal {\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_BORROW_LEND,\n            abi.encode(uint8(0), token, l1Amount)\n        );\n        _sendRaw(action);\n    }\n\n    /// @notice Withdraw `l1Amount` of `token` from BLP back to spot (op=1). `l1Amount=0` means max.\n    function sendWithdrawSupply(uint64 token, uint64 l1Amount) internal {\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_BORROW_LEND,\n            abi.encode(uint8(1), token, l1Amount)\n        );\n        _sendRaw(action);\n    }\n\n    // ─── Spot Transfer ─────────────────────────────────────────\n\n    /// @notice Send spot tokens on L1 to `destination`.\n    /// @dev `amount` is EVM-scale uint64 USDC; converted to L1 8-dp wei via\n    ///      `TokenMath.usdcEvmToL1Wei` (SafeCast, reverts on overflow).\n    function sendSpotSend(address destination, uint64 token, uint64 amount) internal {\n        uint64 l1Amount = TokenMath.usdcEvmToL1Wei(uint256(amount));\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_SPOT_SEND,\n            abi.encode(destination, token, l1Amount)\n        );\n        _sendRaw(action);\n    }\n\n    /// @notice Bridge USDC from EVM back to L1 via ACTION_SEND_ASSET.\n    /// @dev Routes cross-dex spot→spot self-transfer; caller's L1 spot USDC\n    ///      decrements by `usdcEvmToL1Wei(evmAmount)`. Amount is in 6-dp EVM USDC.\n    function sendBridgeToL1(uint256 evmAmount) internal {\n        uint64 l1Amount = TokenMath.usdcEvmToL1Wei(evmAmount);\n        bytes memory action = abi.encodePacked(\n            HyperCoreConstants.ACTION_VERSION,\n            HyperCoreConstants.ACTION_SEND_ASSET,\n            abi.encode(\n                HyperCoreConstants.USDC_SYSTEM_ADDRESS,\n                address(0),\n                HyperCoreConstants.SPOT_DEX,\n                HyperCoreConstants.SPOT_DEX,\n                uint64(HyperCoreConstants.USDC_TOKEN_INDEX),\n                l1Amount\n            )\n        );\n        _sendRaw(action);\n    }\n\n    // ─── Internal ──────────────────────────────────────────────\n\n    function _sendRaw(bytes memory action) private {\n        ICoreWriter(HyperCoreConstants.CORE_WRITER).sendRawAction(action);\n    }\n}\n"},"src/core/PrecompileReader.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"../interfaces/HyperCoreConstants.sol\";\nimport \"./TokenMath.sol\";\n\n/// @title PrecompileReader — typed wrappers over HyperCore read precompiles\n/// @notice Single read path for L1 state. Reverts on precompile failure so a\n///         transient glitch can't be silently booked as a zero balance.\n///         Also owns the read-side EVM↔L1 unit boundary (via `TokenMath`);\n///         `ActionEncoder` owns the write side.\nlibrary PrecompileReader {\n    struct SpotBalance {\n        uint64 total;\n        uint64 hold;\n        uint64 entryNtl;\n    }\n\n    struct VaultEquity {\n        uint64 equity;\n        uint64 lockedUntil;\n    }\n\n    /// @dev L1 wire format — order-sensitive for abi.decode.\n    struct PerpAssetInfo {\n        string coin;\n        uint32 marginTableId;\n        uint8 szDecimals;\n        uint8 maxLeverage;\n        bool onlyIsolated;\n    }\n\n    /// @dev L1 wire format — order-sensitive for abi.decode.\n    struct TokenInfo {\n        string name;\n        uint64[] spots;\n        uint64 deployerTradingFeeShare;\n        address deployer;\n        address evmContract;\n        uint8 szDecimals;\n        uint8 weiDecimals;\n        int8 evmExtraWeiDecimals;\n    }\n\n    /// @notice Spot token balance (0x801).\n    function spotBalance(address account, uint64 token) internal view returns (SpotBalance memory) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_SPOT_BALANCE.staticcall(\n            abi.encode(account, token)\n        );\n        require(ok && res.length >= 96, \"PrecompileReader: spot balance read failed\");\n        (uint64 total, uint64 hold, uint64 entryNtl) = abi.decode(res, (uint64, uint64, uint64));\n        return SpotBalance(total, hold, entryNtl);\n    }\n\n    /// @notice HLP / core-vault equity (0x802).\n    function vaultEquity(address account, address vaultAddr) internal view returns (VaultEquity memory) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_VAULT_EQUITY.staticcall(\n            abi.encode(account, vaultAddr)\n        );\n        require(ok && res.length >= 64, \"PrecompileReader: vault equity read failed\");\n        (uint64 equity, uint64 lockedUntil) = abi.decode(res, (uint64, uint64));\n        return VaultEquity(equity, lockedUntil);\n    }\n\n    /// @notice Perp/spot oracle price (0x807). Reverts on zero (outage signal).\n    function oraclePx(uint32 assetIndex) internal view returns (uint64 price) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_ORACLE_PX.staticcall(\n            abi.encode(assetIndex)\n        );\n        require(ok && res.length >= 32, \"PrecompileReader: oracle px read failed\");\n        price = abi.decode(res, (uint64));\n        require(price > 0, \"PrecompileReader: oracle px zero\");\n    }\n\n    /// @notice Perp account value (signed, 6-dp) from 0x80F.\n    function accountValueSigned(address user) internal view returns (int64 accountValue) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_ACCOUNT_MARGIN_SUMMARY.staticcall(\n            abi.encode(uint32(0), user)\n        );\n        require(ok && res.length >= 128, \"PrecompileReader: perp account read failed\");\n        (accountValue,,,) = abi.decode(res, (int64, uint64, uint64, int64));\n    }\n\n    /// @notice PM \"supplied\" balance (0x811). Returned in L1 8-dp wei.\n    function suppliedBalance(address account, uint64 token) internal view returns (uint64 supplied) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_SUPPLIED_BALANCE.staticcall(\n            abi.encode(account, token)\n        );\n        require(ok && res.length >= 128, \"PrecompileReader: supplied balance read failed\");\n        (,,, supplied) = abi.decode(res, (uint64, uint64, uint64, uint64));\n    }\n\n    /// @notice Spot oracle price (0x808) for an HL spot pair.\n    /// @param spotAssetId HL spot asset id = 10000 + spot_pair_index (NOT token_index).\n    ///                    See `MonetrixConfig.TradeableAsset.spotPairAssetId`.\n    /// @dev Returned value is scaled by `10^(8 - baseSzDecimals)`.\n    function spotPx(uint64 spotAssetId) internal view returns (uint64 price) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_SPOT_PX.staticcall(\n            abi.encode(spotAssetId)\n        );\n        require(ok && res.length >= 32, \"PrecompileReader: spot px read failed\");\n        price = abi.decode(res, (uint64));\n        require(price > 0, \"PrecompileReader: spot px zero\");\n    }\n\n    /// @notice Perp asset metadata (0x80A).\n    function perpAssetInfo(uint32 perpIndex) internal view returns (PerpAssetInfo memory info) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_PERP_ASSET_INFO.staticcall(\n            abi.encode(perpIndex)\n        );\n        require(ok && res.length >= 160, \"PrecompileReader: perp asset info read failed\");\n        info = abi.decode(res, (PerpAssetInfo));\n    }\n\n    /// @notice HIP-1 token metadata (0x80C).\n    function tokenInfo(uint32 tokenIndex) internal view returns (TokenInfo memory info) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_TOKEN_INFO.staticcall(\n            abi.encode(tokenIndex)\n        );\n        require(ok && res.length >= 256, \"PrecompileReader: token info read failed\");\n        info = abi.decode(res, (TokenInfo));\n    }\n\n    // ─── Read-side boundary helpers (read + unit conversion) ─────\n\n    /// @notice L1 spot USDC balance in 6-dp EVM USDC.\n    function spotUsdcEvm(address account) internal view returns (uint256) {\n        SpotBalance memory bal = spotBalance(account, uint64(HyperCoreConstants.USDC_TOKEN_INDEX));\n        return TokenMath.usdcL1WeiToEvm(bal.total);\n    }\n\n    /// @notice PM-supplied USDC balance in 6-dp EVM USDC.\n    function suppliedUsdcEvm(address account) internal view returns (uint256) {\n        uint64 supplied = suppliedBalance(account, uint64(HyperCoreConstants.USDC_TOKEN_INDEX));\n        return TokenMath.usdcL1WeiToEvm(supplied);\n    }\n\n    /// @notice PM USDC net of borrow (supplyValue − borrowValue) in 6-dp EVM USDC.\n    /// @dev Signed: negative when the account borrows more USDC than it supplies (the\n    ///      delta-neutral case). Nets the PM borrow liability so backing isn't overstated.\n    ///      0x811 wire order is (borrowBasis, borrowValue, supplyBasis, supplyValue).\n    function netSuppliedUsdcEvm(address account) internal view returns (int256) {\n        (bool ok, bytes memory res) = HyperCoreConstants.PRECOMPILE_SUPPLIED_BALANCE.staticcall(\n            abi.encode(account, uint64(HyperCoreConstants.USDC_TOKEN_INDEX))\n        );\n        require(ok && res.length >= 128, \"PrecompileReader: supplied balance read failed\");\n        (, uint64 borrowValue,, uint64 supplyValue) = abi.decode(res, (uint64, uint64, uint64, uint64));\n        return int256(TokenMath.usdcL1WeiToEvm(supplyValue)) - int256(TokenMath.usdcL1WeiToEvm(borrowValue));\n    }\n\n    /// @notice Spot hedge balance valued in 6-dp USDC via perp oracle + live HIP-1 decimals.\n    function spotNotionalUsdcFromPerp(\n        uint32 spotTokenIndex,\n        uint32 perpIndex,\n        address account\n    ) internal view returns (uint256) {\n        SpotBalance memory bal = spotBalance(account, uint64(spotTokenIndex));\n        if (bal.total == 0) return 0;\n        uint64 price = oraclePx(perpIndex);\n        (uint8 weiDec, uint8 szDec) = _assetDecimals(spotTokenIndex, perpIndex);\n        return TokenMath.spotNotionalUsdcFromPerpPx(bal.total, price, weiDec, szDec);\n    }\n\n    /// @notice PM-supplied hedge balance valued in 6-dp USDC.\n    function suppliedNotionalUsdcFromPerp(\n        uint32 spotTokenIndex,\n        uint32 perpIndex,\n        address account\n    ) internal view returns (uint256) {\n        uint64 supplied = suppliedBalance(account, uint64(spotTokenIndex));\n        if (supplied == 0) return 0;\n        uint64 price = oraclePx(perpIndex);\n        (uint8 weiDec, uint8 szDec) = _assetDecimals(spotTokenIndex, perpIndex);\n        return TokenMath.spotNotionalUsdcFromPerpPx(supplied, price, weiDec, szDec);\n    }\n\n    function _assetDecimals(uint32 spotTokenIndex, uint32 perpIndex)\n        private view returns (uint8 weiDec, uint8 perpSzDec)\n    {\n        TokenInfo memory ti = tokenInfo(spotTokenIndex);\n        PerpAssetInfo memory pi = perpAssetInfo(perpIndex);\n        weiDec = ti.weiDecimals;\n        perpSzDec = pi.szDecimals;\n    }\n}\n"},"src/core/TokenMath.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport {SafeCast} from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\n/// @title TokenMath — EVM↔L1 unit conversions + L1 notional math for HyperCore\n/// @notice All magic numbers (`/100`, oracle scalings, ...) live here. Every division\n///         floor-rounds — backing/surplus math relies on this being the conservative\n///         direction. Full derivations in `docs/invariants/precision-invariants.md`.\nlibrary TokenMath {\n    using SafeCast for uint256;\n\n    /// @dev USDC `evmExtraWeiDecimals = -2` (L1 8-dp, EVM 6-dp) → EVM→L1 × 100.\n    uint256 internal constant USDC_EVM_TO_L1_FACTOR = 100;\n\n    // ─── EVM ↔ L1 conversion ───────────────────────────────────\n\n    /// @notice EVM 6-dp USDC → L1 spot 8-dp wei. Reverts on overflow.\n    function usdcEvmToL1Wei(uint256 evm6dp) internal pure returns (uint64) {\n        return SafeCast.toUint64(evm6dp * USDC_EVM_TO_L1_FACTOR);\n    }\n\n    /// @notice L1 spot 8-dp USDC wei → EVM 6-dp USDC. Floor rounding.\n    function usdcL1WeiToEvm(uint64 l1_8dp) internal pure returns (uint256) {\n        return uint256(l1_8dp) / USDC_EVM_TO_L1_FACTOR;\n    }\n\n    /// @notice Generic EVM → L1 conversion for any HIP-1 token.\n    /// @dev `evmExtraWeiDecimals = L1 weiDecimals − EVM decimals`. Negative → multiply,\n    ///      positive → divide (floor), zero → identity. Matches hyper-evm-lib convention.\n    function evmToL1Wei(uint256 evmAmount, int8 evmExtraWeiDecimals) internal pure returns (uint64) {\n        if (evmExtraWeiDecimals == 0) {\n            return SafeCast.toUint64(evmAmount);\n        } else if (evmExtraWeiDecimals < 0) {\n            uint256 scaled = evmAmount * (10 ** uint8(-evmExtraWeiDecimals));\n            return SafeCast.toUint64(scaled);\n        } else {\n            uint256 scaled = evmAmount / (10 ** uint8(evmExtraWeiDecimals));\n            return SafeCast.toUint64(scaled);\n        }\n    }\n\n    /// @notice Generic L1 → EVM conversion (inverse of `evmToL1Wei`).\n    function l1WeiToEvm(uint64 l1Amount, int8 evmExtraWeiDecimals) internal pure returns (uint256) {\n        if (evmExtraWeiDecimals == 0) {\n            return uint256(l1Amount);\n        } else if (evmExtraWeiDecimals < 0) {\n            return uint256(l1Amount) / (10 ** uint8(-evmExtraWeiDecimals));\n        } else {\n            return uint256(l1Amount) * (10 ** uint8(evmExtraWeiDecimals));\n        }\n    }\n\n    // ─── Asset notional → 6-dp USDC ────────────────────────────\n\n    /// @notice Spot balance × perp oracle (0x807) → 6-dp USDC notional.\n    /// @dev Formula: `balWei × rawPx / 10^(weiDecimals − perpSzDecimals)`.\n    ///      0x807 format = `actualPrice × 10^(6 − szDecimals)`.\n    function spotNotionalUsdcFromPerpPx(\n        uint64 balWei,\n        uint64 rawPerpOraclePx,\n        uint8 weiDecimals,\n        uint8 perpSzDecimals\n    ) internal pure returns (uint256) {\n        if (balWei == 0 || rawPerpOraclePx == 0) return 0;\n        require(weiDecimals >= perpSzDecimals, \"TokenMath: invalid decimals\");\n        uint256 divisor = 10 ** uint256(weiDecimals - perpSzDecimals);\n        return (uint256(balWei) * uint256(rawPerpOraclePx)) / divisor;\n    }\n\n    /// @notice Spot balance × spot oracle (0x808) → 6-dp USDC notional.\n    /// @dev 0x808 is 2dp more precise than 0x807 (`× 10^(8 − szDecimals)`), so the\n    ///      divisor gains +2: `balWei × rawPx / 10^(weiDecimals + 2 − spotSzDecimals)`.\n    function spotNotionalUsdcFromSpotPx(\n        uint64 balWei,\n        uint64 rawSpotPx,\n        uint8 weiDecimals,\n        uint8 spotSzDecimals\n    ) internal pure returns (uint256) {\n        if (balWei == 0 || rawSpotPx == 0) return 0;\n        uint256 exp = uint256(weiDecimals) + 2;\n        require(exp >= spotSzDecimals, \"TokenMath: invalid decimals\");\n        uint256 divisor = 10 ** (exp - uint256(spotSzDecimals));\n        return (uint256(balWei) * uint256(rawSpotPx)) / divisor;\n    }\n\n    // ─── L1 spot ↔ perp USDC rescale ───────────────────────────\n\n    /// @notice L1 spot USDC (8-dp) → L1 perp accountValue (6-dp).\n    function usdcSpotWeiToPerp(uint64 spotWei) internal pure returns (uint64) {\n        return spotWei / 100;\n    }\n\n    /// @notice L1 perp USDC (6-dp) → L1 spot USDC (8-dp).\n    function usdcPerpToSpotWei(uint64 perp6dp) internal pure returns (uint64) {\n        return SafeCast.toUint64(uint256(perp6dp) * 100);\n    }\n}\n"},"src/core/MonetrixAccountant.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\nimport \"../tokens/USDM.sol\";\nimport \"../interfaces/HyperCoreConstants.sol\";\nimport \"../interfaces/IMonetrixAccountant.sol\";\nimport \"../interfaces/IRedeemEscrow.sol\";\nimport \"./PrecompileReader.sol\";\nimport {MonetrixGovernedUpgradeable} from \"../governance/MonetrixGovernedUpgradeable.sol\";\n\n/// @notice Minimal reader interfaces to avoid circular imports.\ninterface IMonetrixVaultReader {\n    function multisigVault() external view returns (address);\n    function redeemEscrow() external view returns (address);\n}\n\ninterface IMonetrixConfigReader {\n    function tradeableAssets(uint256 index)\n        external view returns (uint32 perpIndex, uint32 spotIndex, uint32 spotPairAssetId);\n    function tradeableAssetsLength() external view returns (uint256);\n    function maxAnnualYieldBps() external view returns (uint256);\n    function spotToPerp(uint32 spotIndex) external view returns (uint32);\n    function isSpotWhitelisted(uint32 spotIndex) external view returns (bool);\n}\n\n/// @title MonetrixAccountant — Peg guardian & yield gate for Monetrix V1\n/// @notice Peg defense + yield declaration authority. Holds no tokens; state is\n///         strictly accounting metadata (interval, totals, timestamps).\n/// @dev `settleDailyPnL` is the single yield declaration entry, gated on\n///      `onlyVault`. Governance (24h timelock) owns parameter tuning.\n///\n///      Safety invariants enforced in `settleDailyPnL`:\n///        1. Initialization gate — `lastSettlementTime > 0` (set via `initializeSettlement`)\n///        2. Interval gate       — `block.timestamp ≥ lastSettlementTime + minSettlementInterval`\n///        3. Distributable gate  — `proposedYield ≤ distributableSurplus()` (F1: redemption window)\n///        4. Annualized gate     — `proposedYield ≤ supply × bps × Δt / (10000 × 1y)` (F8: typo + phantom rate limit)\ncontract MonetrixAccountant is IMonetrixAccountant, MonetrixGovernedUpgradeable {\n\n    error NotVault();\n    error SpotNotWhitelisted(uint64 spotToken);\n    error SuppliedIndexOutOfBounds(uint256 index, uint256 length);\n    error ConfigNotSet();\n\n    modifier onlyVault() {\n        if (msg.sender != vault) revert NotVault();\n        _;\n    }\n\n    address public vault;\n    IERC20 public usdc;\n    USDM public usdm;\n    address public config;\n\n    /// @custom:deprecated Unused from V3 onward; retained for storage layout stability.\n    int256 public lastSurplusSnapshot;\n    uint256 public lastSettlementTime;\n    uint256 public minSettlementInterval;\n\n    // V3 additions\n    uint256 public totalSettledYield;\n\n    // ─── Supply-slot registries (HL 0x811 activation tracking) ──\n \n    struct SuppliedAsset {\n        uint64 spotToken;\n        uint32 perpIndex; // ignored when spotToken == USDC_TOKEN_INDEX\n    }\n    SuppliedAsset[] public vaultSupplied;\n    SuppliedAsset[] public multisigSupplied;\n    mapping(uint64 => bool) internal _vaultSupplyKnown;\n    mapping(uint64 => bool) internal _multisigSupplyKnown;\n\n    // ─── Events ──────────────────────────────────────────────\n\n    event YieldSettled(\n        uint256 indexed day,\n        uint256 proposedYield,\n        uint256 distributable,\n        uint256 cumulative\n    );\n    event MinSettlementIntervalUpdated(uint256 interval);\n    event ConfigUpdated(address config);\n    event SettlementInitialized(uint256 timestamp);\n    event VaultSuppliedRegistered(uint64 indexed spotToken, uint32 perpIndex);\n    event MultisigSuppliedRegistered(uint64 indexed spotToken, uint32 perpIndex);\n    event VaultSuppliedRemoved(uint64 indexed spotToken);\n    event MultisigSuppliedRemoved(uint64 indexed spotToken);\n\n    uint256[46] private __gap;\n\n    /// @custom:oz-upgrades-unsafe-allow constructor\n    constructor() {\n        _disableInitializers();\n    }\n\n    function initialize(address _vault, address _usdc, address _usdm, address _acl) external initializer {\n        require(_vault != address(0), \"Accountant: zero vault\");\n        require(_usdc != address(0), \"Accountant: zero usdc\");\n        require(_usdm != address(0), \"Accountant: zero usdm\");\n\n        __Governed_init(_acl);\n\n        vault = _vault;\n        usdc = IERC20(_usdc);\n        usdm = USDM(_usdm);\n        minSettlementInterval = 20 hours;\n    }\n\n\n    // ─── View: backing + surplus ─────────────────────────────\n\n    /// @notice Signed per-USDM backing. YieldEscrow (in-transit yield) and\n    ///         InsuranceFund (ring-fenced reserve) are excluded by design.\n    /// @dev Mark-to-market; signed so a liquidated perp account reduces backing.\n    function totalBackingSigned() public view returns (int256 total) {\n        // EVM USDC — Vault + RedeemEscrow (not YieldEscrow: undistributed yield is not backing)\n        total = int256(usdc.balanceOf(vault));\n        address re = IMonetrixVaultReader(vault).redeemEscrow();\n        if (re != address(0)) {\n            total += int256(usdc.balanceOf(re));\n        }\n\n        // L1 state — vault reads the Vault-side registry; multisigVault reads\n        // its own registry. Strict 0x811 on every entry: if an entry is listed\n        // but the slot was never actually activated on HL, backing reverts —\n        // forcing a keeper/operator registration fix rather than silently\n        // under-counting.\n        total += _readL1Backing(vault, vaultSupplied);\n        address _multisigVault = IMonetrixVaultReader(vault).multisigVault();\n        if (_multisigVault != address(0)) {\n            total += _readL1Backing(_multisigVault, multisigSupplied);\n        }\n    }\n\n    /// @dev Sum perp + spot USDC + spot hedge tokens + supplied (registered) + HLP for a single L1 account.\n    function _readL1Backing(address account, SuppliedAsset[] storage suppliedList)\n        internal view returns (int256 total)\n    {\n        total = _readPerpAccountValueSigned(account);\n\n        // L1 spot USDC (idle cash not yet deployed to perp/hedge)\n        total += int256(_readSpotUsdcBalance(account));\n\n        // Supplied (0x811) — iterate only registered slots; strict reads.\n        uint256 slen = suppliedList.length;\n        for (uint256 i = 0; i < slen; i++) {\n            SuppliedAsset storage a = suppliedList[i];\n            if (a.spotToken == uint64(HyperCoreConstants.USDC_TOKEN_INDEX)) {\n                // Net the PM USDC borrow liability (supply − borrow); signed, can be negative.\n                total += PrecompileReader.netSuppliedUsdcEvm(account);\n            } else {\n                total += int256(\n                    PrecompileReader.suppliedNotionalUsdcFromPerp(uint32(a.spotToken), a.perpIndex, account)\n                );\n            }\n        }\n\n        // Spot hedge tokens (0x801) — unchanged; 0x801 returns 0 for unheld tokens rather than reverting.\n        if (config != address(0)) {\n            IMonetrixConfigReader cfg = IMonetrixConfigReader(config);\n            uint256 len = cfg.tradeableAssetsLength();\n            for (uint256 i = 0; i < len; i++) {\n                (uint32 perpIndex, uint32 spotIndex, ) = cfg.tradeableAssets(i);\n                total += int256(_readSpotAssetUsdc(spotIndex, perpIndex, account));\n            }\n        }\n\n        // HLP equity counted at full mark value (no principal cap).\n        // multisigVault-held HLP is recognized on the same basis as Vault-held HLP.\n        total += int256(_readHlpEquity(account));\n    }\n\n    /// @notice Unsigned view, clamped at 0. Internal math must use `totalBackingSigned()`.\n    function totalBacking() public view returns (uint256) {\n        int256 signed = totalBackingSigned();\n        return signed > 0 ? uint256(signed) : 0;\n    }\n\n    function surplus() public view returns (int256) {\n        return totalBackingSigned() - int256(usdm.totalSupply());\n    }\n\n    /// @notice Yield-declarable surplus. Subtracts pending redemption shortfall\n    ///         from `surplus()` so `usdm.burn` at request time cannot inflate a\n    ///         phantom-yield window before `claimRedeem` drains the USDC.\n    function distributableSurplus() public view returns (int256) {\n        int256 s = surplus();\n        address re = IMonetrixVaultReader(vault).redeemEscrow();\n        uint256 sf = re == address(0) ? 0 : IRedeemEscrow(re).shortfall();\n        return s - int256(sf);\n    }\n\n    // ─── Daily settlement ────────────────────────────────────\n\n    /// @notice Keeper-asserted daily yield declaration. On-chain bounds keep the\n    ///         keeper's off-chain claim within safe distributable + annualized caps.\n    /// @param proposedYield keeper-computed period yield (phantom-excluded off-chain)\n    /// @return distributable the gate-2 bound at the time of call (audit only)\n    function settleDailyPnL(uint256 proposedYield)\n        external\n        onlyVault\n        returns (uint256 distributable)\n    {\n        // Gate 1 — Initialization\n        require(lastSettlementTime > 0, \"Accountant: not initialized\");\n        // Gate 2 — Interval\n        require(\n            block.timestamp >= lastSettlementTime + minSettlementInterval,\n            \"Accountant: settlement too early\"\n        );\n        // Gate 3 — Distributable surplus bound (F1 fix: redeem-window safe)\n        int256 ds = distributableSurplus();\n        require(ds > 0, \"Accountant: no distributable surplus\");\n        distributable = uint256(ds);\n        require(proposedYield <= distributable, \"Accountant: exceeds distributable\");\n        // Gate 4 — Annualized APR bound (F8 fix: typo + phantom rate limit).\n        // When no USDM is outstanding, the APR denominator is vacuous; Gate 3\n        // remains the binding bound on distributable surplus.\n        uint256 supply_ = usdm.totalSupply();\n        if (supply_ > 0) {\n            uint256 elapsed = block.timestamp - lastSettlementTime;\n            uint256 cap = (supply_ * IMonetrixConfigReader(config).maxAnnualYieldBps() * elapsed)\n                / (10_000 * 365 days);\n            require(proposedYield <= cap, \"Accountant: exceeds annualized cap\");\n        }\n\n        lastSettlementTime = block.timestamp;\n        totalSettledYield += proposedYield;\n\n        emit YieldSettled(_currentDay(), proposedYield, distributable, totalSettledYield);\n    }\n\n    // ─── Admin: config ───────────────────────────────────────\n\n    function setConfig(address _config) external onlyGovernor {\n        require(_config != address(0), \"Accountant: zero config\");\n        config = _config;\n        emit ConfigUpdated(_config);\n    }\n\n    function setMinSettlementInterval(uint256 interval) external onlyGovernor {\n        require(interval >= 1 hours, \"Accountant: interval too short\");\n        require(interval <= 2 days, \"Accountant: interval too long\");\n        minSettlementInterval = interval;\n        emit MinSettlementIntervalUpdated(interval);\n    }\n\n    // ─── Supply registrations (0x811 activation tracking) ────\n\n    /// @notice Register a Vault-side supplied slot. Called automatically by\n    ///         the Vault in paths that activate 0x811 (`supplyToBlp`, and\n    ///         `executeHedge` when `pmEnabled` is true). Idempotent — a\n    ///         second call with the same `spotToken` is a no-op.\n    function notifyVaultSupply(uint64 spotToken, uint32 perpIndex) external onlyVault {\n        if (!_vaultSupplyKnown[spotToken]) {\n            _vaultSupplyKnown[spotToken] = true;\n            vaultSupplied.push(SuppliedAsset({spotToken: spotToken, perpIndex: perpIndex}));\n            emit VaultSuppliedRegistered(spotToken, perpIndex);\n        }\n    }\n\n    /// @notice Register a multisigVault-side supplied slot; perp derived from `config.spotToPerp`.\n    function addMultisigSupplyToken(uint64 spotToken) external onlyOperator {\n        if (_multisigSupplyKnown[spotToken]) return;\n        uint32 perpIndex = _resolvePerp(spotToken);\n        _multisigSupplyKnown[spotToken] = true;\n        multisigSupplied.push(SuppliedAsset({spotToken: spotToken, perpIndex: perpIndex}));\n        emit MultisigSuppliedRegistered(spotToken, perpIndex);\n    }\n\n    /// @notice Operator removal of a supplied-registry entry; swap-and-pop, re-add via the normal path.\n    /// @dev Operator-gated to match `addMultisigSupplyToken`. Removing an entry can only reduce\n    ///      measured backing (never inflate it), so worst case is a more conservative settle —\n    ///      no drain vector, doesn't warrant the 24h governor timelock.\n    function removeSuppliedEntry(bool isMultisig, uint256 index) external onlyOperator {\n        SuppliedAsset[] storage list = isMultisig ? multisigSupplied : vaultSupplied;\n        mapping(uint64 => bool) storage known = isMultisig ? _multisigSupplyKnown : _vaultSupplyKnown;\n\n        uint256 len = list.length;\n        if (index >= len) revert SuppliedIndexOutOfBounds(index, len);\n\n        uint64 removedToken = list[index].spotToken;\n        uint256 last = len - 1;\n        if (index != last) list[index] = list[last];\n        list.pop();\n        known[removedToken] = false;\n\n        if (isMultisig) emit MultisigSuppliedRemoved(removedToken);\n        else            emit VaultSuppliedRemoved(removedToken);\n    }\n\n    function _resolvePerp(uint64 spotToken) internal view returns (uint32) {\n        if (spotToken == uint64(HyperCoreConstants.USDC_TOKEN_INDEX)) return 0;\n        if (config == address(0)) revert ConfigNotSet();\n        IMonetrixConfigReader cfg = IMonetrixConfigReader(config);\n        // Registration check via map, not `spotToPerp != 0` — BTC-PERP is index 0.\n        if (!cfg.isSpotWhitelisted(uint32(spotToken))) revert SpotNotWhitelisted(spotToken);\n        return cfg.spotToPerp(uint32(spotToken));\n    }\n\n    /// @notice Length of the Vault supplied-asset registry (for off-chain UIs).\n    function vaultSuppliedLength() external view returns (uint256) {\n        return vaultSupplied.length;\n    }\n\n    /// @notice Length of the multisig supplied-asset registry (for off-chain UIs).\n    function multisigSuppliedLength() external view returns (uint256) {\n        return multisigSupplied.length;\n    }\n\n    // ─── Admin: lifecycle ────────────────────────────────────\n\n    /// @notice Opens the settlement gate. Must run once; subsequent settles are\n    ///         enforced against `lastSettlementTime`. Idempotency: cannot re-run.\n    function initializeSettlement() external onlyGovernor {\n        require(lastSettlementTime == 0, \"Accountant: already initialized\");\n        require(config != address(0), \"Accountant: config unset\");\n        lastSettlementTime = block.timestamp;\n        emit SettlementInitialized(block.timestamp);\n    }\n\n    // ─── Internal precompile readers ─────────────────────────\n    // All reads go through PrecompileReader (fail-closed: reverts on precompile\n    // glitch so a transient outage can't be silently booked as a loss). The\n    // EVM↔L1 unit conversions are owned by PrecompileReader itself — this\n    // contract is pure aggregation logic.\n\n    function _readPerpAccountValueSigned(address user) internal view returns (int256) {\n        return int256(PrecompileReader.accountValueSigned(user));\n    }\n\n    function _readSpotAssetUsdc(uint32 spotTokenIndex, uint32 perpIndex, address account)\n        internal view returns (uint256)\n    {\n        return PrecompileReader.spotNotionalUsdcFromPerp(spotTokenIndex, perpIndex, account);\n    }\n\n    function _readSpotUsdcBalance(address account) internal view returns (uint256) {\n        return PrecompileReader.spotUsdcEvm(account);\n    }\n\n    function _readHlpEquity(address account) internal view returns (uint256) {\n        return uint256(PrecompileReader.vaultEquity(account, HyperCoreConstants.HLP_VAULT).equity);\n    }\n\n    function _currentDay() internal view returns (uint256) {\n        return block.timestamp / 1 days;\n    }\n}\n"},"src/governance/MonetrixGovernedUpgradeable.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol\";\n\nimport {IMonetrixAccessController} from \"./IMonetrixAccessController.sol\";\n\n/// @title MonetrixGovernedUpgradeable\n/// @notice Abstract base class for every upgradeable Monetrix contract.\n///         Replaces AccessControlUpgradeable usage across the protocol —\n///         instead of each contract maintaining its own role registry, every\n///         check defers to the shared MonetrixAccessController (\"ACL\").\n/// @dev Inheritors must:\n///         1. Call `__Governed_init(acl)` from their own `initialize()`.\n///         2. Use the `onlyGuardian / onlyGovernor / onlyUpgrader /\n///            onlyOperator` modifiers in place of `onlyRole(...)`.\n///         3. NOT override `_authorizeUpgrade` — it is already wired to\n///            `onlyUpgrader` (the 48h timelock path).\nabstract contract MonetrixGovernedUpgradeable is Initializable, UUPSUpgradeable {\n    IMonetrixAccessController public acl;\n\n    error NotAuthorized(bytes32 role, address caller);\n    error ZeroAccessController();\n\n    // ─── Modifiers ─────────────────────────────────────────────\n    modifier onlyGuardian() {\n        _check(acl.GUARDIAN(), msg.sender);\n        _;\n    }\n\n    modifier onlyGovernor() {\n        _check(acl.GOVERNOR(), msg.sender);\n        _;\n    }\n\n    modifier onlyUpgrader() {\n        _check(acl.UPGRADER(), msg.sender);\n        _;\n    }\n\n    modifier onlyOperator() {\n        _check(acl.OPERATOR(), msg.sender);\n        _;\n    }\n\n    // ─── Init ──────────────────────────────────────────────────\n    /// @dev Idempotent wrt reinitializer: child contracts may call this from\n    ///      either `initialize()` (fresh deployment) or a `reinitialize(n)`\n    ///      during migration of an existing proxy.\n    function __Governed_init(address _acl) internal onlyInitializing {\n        if (_acl == address(0)) revert ZeroAccessController();\n        acl = IMonetrixAccessController(_acl);\n    }\n\n    // ─── Upgrade authorization ────────────────────────────────\n    /// @dev Gated by the UPGRADER role — in production this is the 48h\n    ///      TimelockController, so every implementation swap inherits the\n    ///      48h delay automatically.\n    function _authorizeUpgrade(address) internal view override {\n        _check(acl.UPGRADER(), msg.sender);\n    }\n\n    // ─── Internal ──────────────────────────────────────────────\n    function _check(bytes32 role, address caller) private view {\n        if (!acl.hasRole(role, caller)) revert NotAuthorized(role, caller);\n    }\n\n    uint256[49] private __gap;\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reinitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.\n     *\n     * NOTE: Consider following the ERC-7201 formula to derive storage locations.\n     */\n    function _initializableStorageSlot() internal pure virtual returns (bytes32) {\n        return INITIALIZABLE_STORAGE;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        bytes32 slot = _initializableStorageSlot();\n        assembly {\n            $.slot := slot\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {IERC20Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20\n    struct ERC20Storage {\n        mapping(address account => uint256) _balances;\n\n        mapping(address account => mapping(address spender => uint256)) _allowances;\n\n        uint256 _totalSupply;\n\n        string _name;\n        string _symbol;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC20\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;\n\n    function _getERC20Storage() private pure returns (ERC20Storage storage $) {\n        assembly {\n            $.slot := ERC20StorageLocation\n        }\n    }\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * Both values are immutable: they can only be set once during construction.\n     */\n    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC20_init_unchained(name_, symbol_);\n    }\n\n    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        ERC20Storage storage $ = _getERC20Storage();\n        $._name = name_;\n        $._symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /// @inheritdoc IERC20\n    function totalSupply() public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._totalSupply;\n    }\n\n    /// @inheritdoc IERC20\n    function balanceOf(address account) public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        ERC20Storage storage $ = _getERC20Storage();\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            $._totalSupply += value;\n        } else {\n            uint256 fromBalance = $._balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                $._balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                $._totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                $._balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        ERC20Storage storage $ = _getERC20Storage();\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        $._allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance < type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/extensions/ERC4626.sol)\n\npragma solidity ^0.8.24;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {ERC20Upgradeable} from \"../ERC20Upgradeable.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC4626} from \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport {LowLevelCall} from \"@openzeppelin/contracts/utils/LowLevelCall.sol\";\nimport {Memory} from \"@openzeppelin/contracts/utils/Memory.sol\";\nimport {Math} from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the ERC-4626 \"Tokenized Vault Standard\" as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n *\n * This extension allows the minting and burning of \"shares\" (represented using the ERC-20 inheritance) in exchange for\n * underlying \"assets\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\n * the ERC-20 standard. Any additional extensions included along it would affect the \"shares\" token represented by this\n * contract and not the \"assets\" token which is an independent contract.\n *\n * [CAUTION]\n * ====\n * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning\n * with a \"donation\" to the vault that inflates the price of a share. This is variously known as a donation or inflation\n * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial\n * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may\n * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by\n * verifying the amount received is as expected, using a wrapper that performs these checks such as\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\n *\n * Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.\n * The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals\n * and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which\n * itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default\n * offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result\n * of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.\n * With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the\n * underlying math can be found xref:ROOT:erc4626.adoc#inflation-attack[here].\n *\n * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued\n * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets\n * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience\n * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the\n * `_convertToShares` and `_convertToAssets` functions.\n *\n * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].\n * ====\n *\n * [NOTE]\n * ====\n * When overriding this contract, some elements must be considered:\n *\n * * When overriding the behavior of the deposit or withdraw mechanisms, it is recommended to override the internal\n * functions. Overriding {_deposit} automatically affects both {deposit} and {mint}. Similarly, overriding {_withdraw}\n * automatically affects both {withdraw} and {redeem}. Overall it is not recommended to override the public facing\n * functions since that could lead to inconsistent behaviors between the {deposit} and {mint} or between {withdraw} and\n * {redeem}, which is documented to have lead to loss of funds.\n *\n * * Overrides to the deposit or withdraw mechanism must be reflected in the preview functions as well.\n *\n * * {maxWithdraw} depends on {maxRedeem}. Therefore, overriding {maxRedeem} only is enough. On the other hand,\n * overriding {maxWithdraw} only would have no effect on {maxRedeem}, and could create an inconsistency between the two\n * functions.\n *\n * * If {previewRedeem} is overridden to revert, {maxWithdraw} must be overridden as necessary to ensure it\n * always return successfully.\n * ====\n */\nabstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626 {\n    using Math for uint256;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC4626\n    struct ERC4626Storage {\n        IERC20 _asset;\n        uint8 _underlyingDecimals;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC4626\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC4626StorageLocation = 0x0773e532dfede91f04b12a73d3d2acd361424f41f76b4fb79f090161e36b4e00;\n\n    function _getERC4626Storage() private pure returns (ERC4626Storage storage $) {\n        assembly {\n            $.slot := ERC4626StorageLocation\n        }\n    }\n\n    /**\n     * @dev Attempted to deposit more assets than the max amount for `receiver`.\n     */\n    error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);\n\n    /**\n     * @dev Attempted to mint more shares than the max amount for `receiver`.\n     */\n    error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);\n\n    /**\n     * @dev Attempted to withdraw more assets than the max amount for `receiver`.\n     */\n    error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);\n\n    /**\n     * @dev Attempted to redeem more shares than the max amount for `receiver`.\n     */\n    error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);\n\n    /**\n     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).\n     */\n    function __ERC4626_init(IERC20 asset_) internal onlyInitializing {\n        __ERC4626_init_unchained(asset_);\n    }\n\n    function __ERC4626_init_unchained(IERC20 asset_) internal onlyInitializing {\n        ERC4626Storage storage $ = _getERC4626Storage();\n        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\n        $._underlyingDecimals = success ? assetDecimals : 18;\n        $._asset = asset_;\n    }\n\n    /**\n     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\n     */\n    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {\n        Memory.Pointer ptr = Memory.getFreeMemoryPointer();\n        (bool success, bytes32 returnedDecimals, ) = LowLevelCall.staticcallReturn64Bytes(\n            address(asset_),\n            abi.encodeCall(IERC20Metadata.decimals, ())\n        );\n        Memory.setFreeMemoryPointer(ptr);\n\n        return\n            (success && LowLevelCall.returnDataSize() >= 32 && uint256(returnedDecimals) <= type(uint8).max)\n                ? (true, uint8(uint256(returnedDecimals)))\n                : (false, 0);\n    }\n\n    /**\n     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This\n     * \"original\" value is cached during construction of the vault contract. If this read operation fails (e.g., the\n     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.\n     *\n     * See {IERC20Metadata-decimals}.\n     */\n    function decimals() public view virtual override(IERC20Metadata, ERC20Upgradeable) returns (uint8) {\n        ERC4626Storage storage $ = _getERC4626Storage();\n        return $._underlyingDecimals + _decimalsOffset();\n    }\n\n    /// @inheritdoc IERC4626\n    function asset() public view virtual returns (address) {\n        ERC4626Storage storage $ = _getERC4626Storage();\n        return address($._asset);\n    }\n\n    /// @inheritdoc IERC4626\n    function totalAssets() public view virtual returns (uint256) {\n        return IERC20(asset()).balanceOf(address(this));\n    }\n\n    /// @inheritdoc IERC4626\n    function convertToShares(uint256 assets) public view virtual returns (uint256) {\n        return _convertToShares(assets, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n        return _convertToAssets(shares, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function maxDeposit(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /// @inheritdoc IERC4626\n    function maxMint(address) public view virtual returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /// @inheritdoc IERC4626\n    function maxWithdraw(address owner) public view virtual returns (uint256) {\n        return previewRedeem(maxRedeem(owner));\n    }\n\n    /// @inheritdoc IERC4626\n    function maxRedeem(address owner) public view virtual returns (uint256) {\n        return balanceOf(owner);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n        return _convertToShares(assets, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewMint(uint256 shares) public view virtual returns (uint256) {\n        return _convertToAssets(shares, Math.Rounding.Ceil);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n        return _convertToShares(assets, Math.Rounding.Ceil);\n    }\n\n    /// @inheritdoc IERC4626\n    function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n        return _convertToAssets(shares, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IERC4626\n    function deposit(uint256 assets, address receiver) public virtual returns (uint256) {\n        uint256 maxAssets = maxDeposit(receiver);\n        if (assets > maxAssets) {\n            revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);\n        }\n\n        uint256 shares = previewDeposit(assets);\n        _deposit(_msgSender(), receiver, assets, shares);\n\n        return shares;\n    }\n\n    /// @inheritdoc IERC4626\n    function mint(uint256 shares, address receiver) public virtual returns (uint256) {\n        uint256 maxShares = maxMint(receiver);\n        if (shares > maxShares) {\n            revert ERC4626ExceededMaxMint(receiver, shares, maxShares);\n        }\n\n        uint256 assets = previewMint(shares);\n        _deposit(_msgSender(), receiver, assets, shares);\n\n        return assets;\n    }\n\n    /// @inheritdoc IERC4626\n    function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {\n        uint256 maxAssets = maxWithdraw(owner);\n        if (assets > maxAssets) {\n            revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);\n        }\n\n        uint256 shares = previewWithdraw(assets);\n        _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n        return shares;\n    }\n\n    /// @inheritdoc IERC4626\n    function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {\n        uint256 maxShares = maxRedeem(owner);\n        if (shares > maxShares) {\n            revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);\n        }\n\n        uint256 assets = previewRedeem(shares);\n        _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n        return assets;\n    }\n\n    /**\n     * @dev Internal conversion function (from assets to shares) with support for rounding direction.\n     */\n    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {\n        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);\n    }\n\n    /**\n     * @dev Internal conversion function (from shares to assets) with support for rounding direction.\n     */\n    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {\n        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);\n    }\n\n    /**\n     * @dev Deposit/mint common workflow.\n     */\n    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {\n        // If asset() is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the\n        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\n        // calls the vault, which is assumed not malicious.\n        //\n        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\n        // assets are transferred and before the shares are minted, which is a valid state.\n        // slither-disable-next-line reentrancy-no-eth\n        SafeERC20.safeTransferFrom(IERC20(asset()), caller, address(this), assets);\n        _mint(receiver, shares);\n\n        emit Deposit(caller, receiver, assets, shares);\n    }\n\n    /**\n     * @dev Withdraw/redeem common workflow.\n     */\n    function _withdraw(\n        address caller,\n        address receiver,\n        address owner,\n        uint256 assets,\n        uint256 shares\n    ) internal virtual {\n        if (caller != owner) {\n            _spendAllowance(owner, caller, shares);\n        }\n\n        // If asset() is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\n        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\n        // calls the vault, which is assumed not malicious.\n        //\n        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\n        // shares are burned and after the assets are transferred, which is a valid state.\n        _burn(owner, shares);\n        SafeERC20.safeTransfer(IERC20(asset()), receiver, assets);\n\n        emit Withdraw(caller, receiver, owner, assets, shares);\n    }\n\n    function _decimalsOffset() internal view virtual returns (uint8) {\n        return 0;\n    }\n}\n"},"src/tokens/sUSDMEscrow.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\n/// @title sUSDMEscrow\n/// @notice Dumb escrow that holds USDM for sUSDM unstake cooldowns.\n///         No business logic — sUSDM decides when to deposit and release.\n///         Non-upgradeable with immutable bindings so neither admin nor a\n///         compromised sUSDM upgrade can redirect the asset address.\ncontract sUSDMEscrow {\n    using SafeERC20 for IERC20;\n\n    IERC20 public immutable usdm;\n    address public immutable sUSDM;\n\n    error NotSUSDM();\n    error ZeroAddress();\n\n    modifier onlySUSDM() {\n        if (msg.sender != sUSDM) revert NotSUSDM();\n        _;\n    }\n\n    constructor(address _usdm, address _sUSDM) {\n        if (_usdm == address(0) || _sUSDM == address(0)) revert ZeroAddress();\n        usdm = IERC20(_usdm);\n        sUSDM = _sUSDM;\n    }\n\n    /// @notice Pull USDM from sUSDM into escrow. Requires prior approval.\n    function deposit(uint256 amount) external onlySUSDM {\n        usdm.safeTransferFrom(sUSDM, address(this), amount);\n    }\n\n    /// @notice Send USDM from escrow to recipient.\n    function release(address to, uint256 amount) external onlySUSDM {\n        usdm.safeTransfer(to, amount);\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.22;\n\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol\";\n"},"src/governance/IMonetrixAccessController.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity ^0.8.27;\n\n/// @title IMonetrixAccessController\n/// @notice Centralized ACL registry interface consumed by all Monetrix\n///         contracts via MonetrixGovernedUpgradeable. Exposes the canonical\n///         role identifiers and the revert-on-fail `checkRole` helper used by\n///         modifiers.\ninterface IMonetrixAccessController {\n    // ─── Canonical role identifiers ────────────────────────────\n    // Held by Guardian multisig.\n    function GUARDIAN() external view returns (bytes32);\n    // Held by the 24h TimelockController.\n    function GOVERNOR() external view returns (bytes32);\n    // Held by the 48h TimelockController.\n    function UPGRADER() external view returns (bytes32);\n    // Held by bot hot wallets (supports multiple addresses).\n    function OPERATOR() external view returns (bytes32);\n\n    // ─── Role queries ──────────────────────────────────────────\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /// @notice Reverts with NotAuthorized(role, account) when the account\n    ///         lacks the role. Kept as a separate view so callers that want a\n    ///         single external call rather than a boolean check-then-revert\n    ///         can use it (slightly cheaper than two calls).\n    function checkRole(bytes32 role, address account) external view;\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/IERC4626.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"../token/ERC20/extensions/IERC20Metadata.sol\";\n\n/**\n * @dev Interface of the ERC-4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n */\ninterface IERC4626 is IERC20, IERC20Metadata {\n    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed sender,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /**\n     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n     *\n     * - MUST be an ERC-20 token contract.\n     * - MUST NOT revert.\n     */\n    function asset() external view returns (address assetTokenAddress);\n\n    /**\n     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n     *\n     * - SHOULD include any compounding that occurs from yield.\n     * - MUST be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT revert.\n     */\n    function totalAssets() external view returns (uint256 totalManagedAssets);\n\n    /**\n     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n     * through a deposit call.\n     *\n     * - MUST return a limited value if receiver is subject to some deposit limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n     * - MUST NOT revert.\n     */\n    function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n     *   in the same transaction.\n     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Deposit `assets` underlying tokens and send the corresponding number of vault shares (`shares`) to `receiver`.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   deposit execution, and are accounted for during deposit.\n     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n     * - MUST return a limited value if receiver is subject to some mint limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n     * - MUST NOT revert.\n     */\n    function maxMint(address receiver) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n     *   same transaction.\n     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n     *   would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by minting.\n     */\n    function previewMint(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Mints exactly `shares` vault shares to `receiver` in exchange for `assets` underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n     *   execution, and are accounted for during mint.\n     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n     * Vault, through a withdraw call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n     *   called\n     *   in the same transaction.\n     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   withdraw execution, and are accounted for during withdraw.\n     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n     * through a redeem call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n     *   same transaction.\n     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n     *   redemption would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n     */\n    function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   redeem execution, and are accounted for during redeem.\n     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/LowLevelCall.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library of low level call functions that implement different calling strategies to deal with the return data.\n *\n * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended\n * to use the {Address} library instead.\n */\nlibrary LowLevelCall {\n    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.\n    function callNoReturn(address target, bytes memory data) internal returns (bool success) {\n        return callNoReturn(target, 0, data);\n    }\n\n    /// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.\n    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function callReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        return callReturn64Bytes(target, 0, data);\n    }\n\n    /// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.\n    function callReturn64Bytes(\n        address target,\n        uint256 value,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.\n    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function staticcallReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.\n    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function delegatecallReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Returns the size of the return data buffer.\n    function returnDataSize() internal pure returns (uint256 size) {\n        assembly (\"memory-safe\") {\n            size := returndatasize()\n        }\n    }\n\n    /// @dev Returns a buffer containing the return data from the last call.\n    function returnData() internal pure returns (bytes memory result) {\n        assembly (\"memory-safe\") {\n            result := mload(0x40)\n            mstore(result, returndatasize())\n            returndatacopy(add(result, 0x20), 0x00, returndatasize())\n            mstore(0x40, add(result, add(0x20, returndatasize())))\n        }\n    }\n\n    /// @dev Revert with the return data from the last call.\n    function bubbleRevert() internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            returndatacopy(fmp, 0x00, returndatasize())\n            revert(fmp, returndatasize())\n        }\n    }\n\n    function bubbleRevert(bytes memory returndata) internal pure {\n        assembly (\"memory-safe\") {\n            revert(add(returndata, 0x20), mload(returndata))\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Memory.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Memory.sol)\n\npragma solidity ^0.8.24;\n\nimport {Panic} from \"./Panic.sol\";\nimport {Math} from \"./math/Math.sol\";\n\n/**\n * @dev Utilities to manipulate memory.\n *\n * Memory is a contiguous and dynamic byte array in which Solidity stores non-primitive types.\n * This library provides functions to manipulate pointers to this dynamic array and work with slices of it.\n *\n * Slices provide a view into a portion of memory without copying data, enabling efficient substring operations.\n *\n * WARNING: When manipulating memory pointers or slices, make sure to follow the Solidity documentation\n * guidelines for https://docs.soliditylang.org/en/v0.8.20/assembly.html#memory-safety[Memory Safety].\n */\nlibrary Memory {\n    type Pointer is bytes32;\n\n    /// @dev Returns a `Pointer` to the current free `Pointer`.\n    function getFreeMemoryPointer() internal pure returns (Pointer ptr) {\n        assembly (\"memory-safe\") {\n            ptr := mload(0x40)\n        }\n    }\n\n    /**\n     * @dev Sets the free `Pointer` to a specific value.\n     *\n     * WARNING: Everything after the pointer may be overwritten.\n     **/\n    function setFreeMemoryPointer(Pointer ptr) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x40, ptr)\n        }\n    }\n\n    /// @dev `Pointer` to `bytes32`. Expects a pointer to a properly ABI-encoded `bytes` object.\n    function asBytes32(Pointer ptr) internal pure returns (bytes32) {\n        return Pointer.unwrap(ptr);\n    }\n\n    /// @dev `bytes32` to `Pointer`. Expects a pointer to a properly ABI-encoded `bytes` object.\n    function asPointer(bytes32 value) internal pure returns (Pointer) {\n        return Pointer.wrap(value);\n    }\n\n    /// @dev Move a pointer forward by a given offset.\n    function forward(Pointer ptr, uint256 offset) internal pure returns (Pointer) {\n        return Pointer.wrap(bytes32(uint256(Pointer.unwrap(ptr)) + offset));\n    }\n\n    /// @dev Equality comparator for memory pointers.\n    function equal(Pointer ptr1, Pointer ptr2) internal pure returns (bool) {\n        return Pointer.unwrap(ptr1) == Pointer.unwrap(ptr2);\n    }\n\n    type Slice is bytes32;\n\n    /// @dev Get a slice representation of a bytes object in memory\n    function asSlice(bytes memory self) internal pure returns (Slice result) {\n        assembly (\"memory-safe\") {\n            result := or(shl(128, mload(self)), add(self, 0x20))\n        }\n    }\n\n    /// @dev Returns the length of a given slice (equiv to self.length for calldata slices)\n    function length(Slice self) internal pure returns (uint256 result) {\n        assembly (\"memory-safe\") {\n            result := shr(128, self)\n        }\n    }\n\n    /// @dev Offset a memory slice (equivalent to self[start:] for calldata slices)\n    function slice(Slice self, uint256 offset) internal pure returns (Slice) {\n        if (offset > length(self)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);\n        return _asSlice(length(self) - offset, forward(_pointer(self), offset));\n    }\n\n    /// @dev Offset and cut a Slice (equivalent to self[start:start+length] for calldata slices)\n    function slice(Slice self, uint256 offset, uint256 len) internal pure returns (Slice) {\n        if (offset + len > length(self)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);\n        return _asSlice(len, forward(_pointer(self), offset));\n    }\n\n    /**\n     * @dev Read a bytes32 buffer from a given Slice at a specific offset\n     *\n     * NOTE: If offset > length(slice) - 0x20, part of the return value will be out of bound of the slice. These bytes are zeroed.\n     */\n    function load(Slice self, uint256 offset) internal pure returns (bytes32 value) {\n        uint256 outOfBoundBytes = Math.saturatingSub(0x20 + offset, length(self));\n        if (outOfBoundBytes > 0x1f) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);\n\n        assembly (\"memory-safe\") {\n            value := and(mload(add(and(self, shr(128, not(0))), offset)), shl(mul(8, outOfBoundBytes), not(0)))\n        }\n    }\n\n    /// @dev Extract the data corresponding to a Slice (allocate new memory)\n    function toBytes(Slice self) internal pure returns (bytes memory result) {\n        uint256 len = length(self);\n        Memory.Pointer ptr = _pointer(self);\n        assembly (\"memory-safe\") {\n            result := mload(0x40)\n            mstore(result, len)\n            mcopy(add(result, 0x20), ptr, len)\n            mstore(0x40, add(add(result, len), 0x20))\n        }\n    }\n\n    /**\n     * @dev Private helper: create a slice from raw values (length and pointer)\n     *\n     * NOTE: this function MUST NOT be called with `len` or `ptr` that exceed `2**128-1`. This should never be\n     * the case of slices produced by `asSlice(bytes)`, and function that reduce the scope of slices\n     * (`slice(Slice,uint256)` and `slice(Slice,uint256, uint256)`) should not cause this issue if the parent slice is\n     * correct.\n     */\n    function _asSlice(uint256 len, Memory.Pointer ptr) private pure returns (Slice result) {\n        assembly (\"memory-safe\") {\n            result := or(shl(128, len), ptr)\n        }\n    }\n\n    /// @dev Returns the memory location of a given slice (equiv to self.offset for calldata slices)\n    function _pointer(Slice self) private pure returns (Memory.Pointer result) {\n        assembly (\"memory-safe\") {\n            result := and(self, shr(128, not(0)))\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2²⁵⁶ + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * 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\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // 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).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n\n    /**\n     * @dev Counts the number of leading zero bits in a uint256.\n     */\n    function clz(uint256 x) internal pure returns (uint256) {\n        return ternary(x == 0, 256, 255 - log2(x));\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.22;\n\nimport {IERC1822Proxiable} from \"../../interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"../ERC1967/ERC1967Utils.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n *\n * @custom:stateless\n */\nabstract contract UUPSUpgradeable is IERC1822Proxiable {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n    address private immutable __self = address(this);\n\n    /**\n     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`\n     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n     * If the getter returns `\"5.0.0\"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must\n     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n     * during an upgrade.\n     */\n    string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n    /**\n     * @dev The call is from an unauthorized context.\n     */\n    error UUPSUnauthorizedCallContext();\n\n    /**\n     * @dev The storage `slot` is unsupported as a UUID.\n     */\n    error UUPSUnsupportedProxiableUUID(bytes32 slot);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        _checkProxy();\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        _checkNotDelegated();\n        _;\n    }\n\n    /**\n     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view notDelegated returns (bytes32) {\n        return ERC1967Utils.IMPLEMENTATION_SLOT;\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n     * encoded in `data`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, data);\n    }\n\n    /**\n     * @dev Reverts if the execution is not performed via delegatecall or the execution\n     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.\n     */\n    function _checkProxy() internal view virtual {\n        if (\n            address(this) == __self || // Must be called through delegatecall\n            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy\n        ) {\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Reverts if the execution is performed via delegatecall.\n     * See {notDelegated}.\n     */\n    function _checkNotDelegated() internal view virtual {\n        if (address(this) != __self) {\n            // Must not be called through delegatecall\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n     * {upgradeToAndCall}.\n     *\n     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n     *\n     * ```solidity\n     * function _authorizeUpgrade(address) internal onlyOwner {}\n     * ```\n     */\n    function _authorizeUpgrade(address newImplementation) internal virtual;\n\n    /**\n     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.\n     *\n     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value\n     * is expected to be the implementation slot in ERC-1967.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {\n        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {\n                revert UUPSUnsupportedProxiableUUID(slot);\n            }\n            ERC1967Utils.upgradeToAndCall(newImplementation, data);\n        } catch {\n            // The implementation is not UUPS\n            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.21;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {IERC1967} from \"../../interfaces/IERC1967.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This library provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev The `implementation` of the proxy is invalid.\n     */\n    error ERC1967InvalidImplementation(address implementation);\n\n    /**\n     * @dev The `admin` of the proxy is invalid.\n     */\n    error ERC1967InvalidAdmin(address admin);\n\n    /**\n     * @dev The `beacon` of the proxy is invalid.\n     */\n    error ERC1967InvalidBeacon(address beacon);\n\n    /**\n     * @dev An upgrade function sees `msg.value > 0` that may be lost.\n     */\n    error ERC1967NonPayable();\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        if (newImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(newImplementation);\n        }\n        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n        _setImplementation(newImplementation);\n        emit IERC1967.Upgraded(newImplementation);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(newImplementation, data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n     */\n    function getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        if (newAdmin == address(0)) {\n            revert ERC1967InvalidAdmin(address(0));\n        }\n        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {IERC1967-AdminChanged} event.\n     */\n    function changeAdmin(address newAdmin) internal {\n        emit IERC1967.AdminChanged(getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the ERC-1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        if (newBeacon.code.length == 0) {\n            revert ERC1967InvalidBeacon(newBeacon);\n        }\n\n        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n        address beaconImplementation = IBeacon(newBeacon).implementation();\n        if (beaconImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(beaconImplementation);\n        }\n    }\n\n    /**\n     * @dev Change the beacon and trigger a setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-BeaconUpgraded} event.\n     *\n     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n     * efficiency.\n     */\n    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n        _setBeacon(newBeacon);\n        emit IERC1967.BeaconUpgraded(newBeacon);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n     * if an upgrade doesn't perform an initialization call.\n     */\n    function _checkNonPayable() private {\n        if (msg.value > 0) {\n            revert ERC1967NonPayable();\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {UpgradeableBeacon} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC1967.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)\n\npragma solidity >=0.4.11;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\nimport {LowLevelCall} from \"./LowLevelCall.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n        if (LowLevelCall.callNoReturn(recipient, amount, \"\")) {\n            // call successful, nothing to do\n            return;\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {Errors.FailedCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        bool success = LowLevelCall.callNoReturn(target, value, data);\n        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {\n            return LowLevelCall.returnData();\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        bool success = LowLevelCall.staticcallNoReturn(target, data);\n        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {\n            return LowLevelCall.returnData();\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        bool success = LowLevelCall.delegatecallNoReturn(target, data);\n        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {\n            return LowLevelCall.returnData();\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n     * of an unsuccessful call.\n     *\n     * NOTE: This function is DEPRECATED and may be removed in the next major release.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        // only check if target is a contract if the call was successful and the return data is empty\n        // otherwise we already know that it was a contract\n        if (success && (returndata.length > 0 || target.code.length > 0)) {\n            return returndata;\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (returndata.length > 0) {\n            LowLevelCall.bubbleRevert(returndata);\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {Errors.FailedCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else if (returndata.length > 0) {\n            LowLevelCall.bubbleRevert(returndata);\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Errors.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error InsufficientBalance(uint256 balance, uint256 needed);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedCall();\n\n    /**\n     * @dev The deployment failed.\n     */\n    error FailedDeployment();\n\n    /**\n     * @dev A necessary precompile is missing.\n     */\n    error MissingPrecompile(address);\n}\n"}},"compilation":{"language":"Solidity","compiler":"solc","compilerVersion":"0.8.28+commit.7893614a","compilerSettings":{"viaIR":true,"metadata":{"appendCBOR":true,"bytecodeHash":"ipfs","useLiteralContent":false},"optimizer":{"runs":200,"enabled":true},"evmVersion":"cancun","remappings":["@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/","@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/","forge-std/=lib/forge-std/src/","@hyper-evm-lib/=lib/hyper-evm-lib/","erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/","halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/","hyper-evm-lib/=lib/hyper-evm-lib/","openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/","openzeppelin-contracts/=lib/openzeppelin-contracts/"]},"name":"MonetrixVault","fullyQualifiedName":"src/core/MonetrixVault.sol:MonetrixVault"},"matchId":"32159384","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2026-06-13T02:05:08Z","match":"exact_match","chainId":"999","address":"0x08F69C88C47ef1C5274fc11bfE350561252c77F2"}